CoolFace
Apppublic

yasnarezvani/explainable-content-moderation

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
App README

Explainable Content Moderation

๐Ÿ›ก๏ธ Explainable Content Moderation System

An AI-powered content moderation system that provides transparent, interpretable decisions using transformer models and Integrated Gradients explainability.

โšก Live Demo A lightweight demo of the interactive dashboard (live content moderation) is available on Hugging Face Spaces: [https://huggingface.co/spaces/yasnarezvani/explainable-content-moderation]. This demo uses pre-computed artifacts and does not include the full training pipeline.


๐Ÿ“‹ Project Overview

Problem Statement: Online platforms struggle with two major challenges:

  1. 1.Over- and under-moderation - Inconsistent flagging damages user trust
  2. 2.Lack of transparency - Black-box systems provide no justification for decisions

Solution: This project develops an interpretable AI system that classifies content as safe/unsafe and explains the reasoning behind each decision through an interactive dashboard.


๐ŸŽฏ Key Features

1. High-Performance Classifier

  • โ€”Model: RoBERTa-base fine-tuned on 127k toxic comments
  • โ€”Performance: 0.677 macro F1 (>20% improvement over baseline)
  • โ€”Categories: Toxic, Severe Toxic, Obscene, Threat, Insult, Identity Hate
  • โ€”Training: 3-fold cross-validation with per-label threshold optimization

2. Explainability Module

  • โ€”Method: Integrated Gradients for token-level attribution
  • โ€”Output: Human-readable explanations with semantic categorization
  • โ€”Coverage: 100% of flagged content has explanations
  • โ€”Format: JSON-ready for integration

3. Interactive Dashboard

  • โ€”Live Moderation: Real-time analysis with explanations
  • โ€”Example Gallery: Browse 100 pre-computed explanations
  • โ€”Batch Analysis: Upload CSV files for bulk processing
  • โ€”Professional Display: Censored profanity, clean interface

4. Bias Testing

  • โ€”Identity Bias: 4% false positive rate
  • โ€”False Positive Rate: 0.18-1.71% across all categories
  • โ€”Context Sensitivity: 80% accuracy on nuanced cases
  • โ€”Comprehensive Report: Demographic and contextual analysis

๐Ÿ“Š Performance Metrics

MetricValue
Test Macro F10.677
Toxic F10.829
Obscene F10.825
Insult F10.773
Severe Toxic F10.539
Identity Hate F10.567
Threat F10.529
Identity Bias FP Rate4.0%
Context Sensitivity80.0%

๐Ÿ—๏ธ Project Structure

explainable-content-moderation/
โ”œโ”€โ”€ notebooks/
โ”‚   โ”œโ”€โ”€ 01_data_preparation.ipynb                 # Data preparation and visualization
โ”‚   โ”œโ”€โ”€ 02_baseline_model.ipynb                   # Baseline model
โ”‚   โ”œโ”€โ”€ 03_failed_ml_models.ipynb                 # Failed Basic ML models
โ”‚   โ”œโ”€โ”€ 04_failed_model_bert.ipynb                # Failed BERT base model
โ”‚   โ”œโ”€โ”€ 05_failed_model_distilbert.ipynb          # Failed DistilBERT model
โ”‚   โ”œโ”€โ”€ 06_roberta_final_model.ipynb              # RoBERTa Final model
โ”‚   โ”œโ”€โ”€ 07_explainability.ipynb        # Integrated Gradients implementation
โ”‚   โ”œโ”€โ”€ 09_bias_testing.ipynb          # Fairness evaluation
โ”‚   โ””โ”€โ”€ artifacts/                     # Saved models & results
โ”‚       โ”œโ”€โ”€ primary_v3_fold0.pth
โ”‚       โ”œโ”€โ”€ primary_v3_fold1.pth
โ”‚       โ”œโ”€โ”€ primary_v3_fold2.pth
โ”‚       โ”œโ”€โ”€ explanation_dataset_100.json
โ”‚       โ”œโ”€โ”€ bias_testing_report.md
โ”‚       โ””โ”€โ”€ test_predictions_final.npy
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ 08_dashboard.py                    # Streamlit interactive demo
โ”œโ”€โ”€ data/
โ”‚   โ””โ”€โ”€ processed_text.csv             # Training data
โ”œโ”€โ”€ README.md                          # This file
โ””โ”€โ”€ requirements.txt                   # Dependencies

๐Ÿš€ Quick Start

๐Ÿ’ก Note: For a quick demo without setup, check out the live Hugging Face Space: [https://huggingface.co/spaces/yasnarezvani/explainable-content-moderation]

Installation

bash
# Clone repository
git clone https://github.com/YasnaRezvani/explainable-content-moderation.git
cd explainable-content-moderation

# Install dependencies
pip install -r requirements.txt

Run Dashboard

bash
streamlit run 08_dashboard.py

Access at http://localhost:8501

Note: Model files will be automatically downloaded from Google Drive on first run (~476 MB). The Hugging Face Space hosts a lightweight demo version. The full project with training notebooks is on GitHub.

Model Files

The trained model and explanation dataset are hosted on Google Drive and will be downloaded automatically when you first run the dashboard. If you need to download them manually:

Place them in cache_artifacts/ directory if downloading manually.

Test a Single Comment

python
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

# Load model
model = AutoModelForSequenceClassification.from_pretrained(
    "roberta-base", num_labels=6
)
model.load_state_dict(torch.load("notebooks/artifacts/primary_v3_fold0.pth"))
tokenizer = AutoTokenizer.from_pretrained("roberta-base")

# Predict
text = "Your text here"
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
outputs = model(**inputs)
probs = torch.sigmoid(outputs.logits)[0]

labels = ["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"]
for label, prob in zip(labels, probs):
    print(f"{label}: {prob:.3f}")

๐Ÿ”ฌ Technical Details

Model Architecture

  • โ€”Base: RoBERTa-base (125M parameters)
  • โ€”Fine-tuning: 2-stage (head-only โ†’ top-4 layers)
  • โ€”Loss: Focal loss (ฮฑ=0.25, ฮณ=2.0) for class imbalance
  • โ€”Optimization: AdamW with linear warmup
  • โ€”Hardware: RTX 3050 Laptop (4GB VRAM)

Explainability Method

  • โ€”Algorithm: Integrated Gradients (Sundararajan et al., 2017)
  • โ€”Integration Steps: 30 (balance of speed/accuracy)
  • โ€”Baseline: Zero embeddings
  • โ€”Output: Per-token attribution scores aggregated to full words

Threshold Optimization

  • โ€”Method: Per-label threshold search
  • โ€”Metric: F1 score maximization
  • โ€”Constraint: Minimum precision 3%
  • โ€”Search Space: 100 thresholds per label (0.03-0.95)

๐Ÿงพ Model Card (Summary)

Model Name: Explainable Content Moderation System (RoBERTa-based)

Intended Use: Educational and demonstrative content moderation support. Designed to assist human moderators by flagging potentially unsafe content and providing interpretable explanations. Not intended as a sole decision-maker in production moderation systems.

Model Type: Multi-label text classification with transformer architecture (RoBERTa-base).

Training Data: Jigsaw Toxic Comment Classification dataset (~127k comments). Data contains user-generated online comments labeled across six toxicity-related categories.

Evaluation Metrics: Primary metric: Macro F1 score (0.677 on held-out test set). Per-label F1, precision, and recall reported in the Performance Metrics section.

Explainability: Token-level attributions generated using Integrated Gradients. All flagged examples include human-readable explanations surfaced through an interactive dashboard.

Bias & Fairness Considerations: Bias testing conducted across identity-related terms and contextual variants. Observed identity false positive rate of ~4%. Known sensitivity to reclaimed terms and slang is documented.

Limitations: Reduced performance on rare classes (e.g., threat, severe toxicity). Context-dependent language and sarcasm may be misclassified. Model may flag passionate but non-toxic speech.

Ethical Considerations: Predictions should be interpreted with caution and reviewed by humans. Thresholds are optimized for balanced performance, not harm minimization in high-risk settings.


๐Ÿ“ˆ Results & Insights

What Works Well

โœ… High precision on major categories (toxic, obscene, insult) โœ… Low false positive rates (<2% for most categories) โœ… Minimal demographic bias (4% overall) โœ… Clear, interpretable explanations

Known Limitations

โš ๏ธ Context sensitivity on slang/reclaimed terms (20% FP on "gay", "lesbian") โš ๏ธ Lower performance on rare categories (threat: 0.529 F1) โš ๏ธ May flag passionate but non-toxic speech

Future Improvements

  • โ€”Fine-tune on context-aware examples (AAVE, slang, reclaimed terms)
  • โ€”Ensemble with DeBERTa-v3 for performance boost
  • โ€”Implement user feedback loop for continuous learning
  • โ€”Add multi-language support

๐ŸŽ“ Educational Use

This project demonstrates:

  • โ€”Production ML Pipeline: Data โ†’ Training โ†’ Evaluation โ†’ Deployment
  • โ€”Explainable AI: Moving beyond black-box models
  • โ€”Bias Testing: Proactive fairness evaluation
  • โ€”Dashboard Development: User-friendly ML interfaces
  • โ€”Model Optimization: Threshold tuning, cross-validation, focal loss

๐Ÿ“š References

Dataset

  • โ€”Jigsaw Toxic Comment Classification Challenge
  • โ€”Source: thesofakillers/jigsaw-toxic-comment-classification-challenge

Key Papers

  • โ€”Sundararajan et al. (2017) - Integrated Gradients
  • โ€”Liu et al. (2019) - RoBERTa
  • โ€”Lin et al. (2017) - Focal Loss

Tools & Libraries

  • โ€”Transformers (Hugging Face)
  • โ€”Captum (Explainability)
  • โ€”Streamlit (Dashboard)
  • โ€”PyTorch (Deep Learning)

๐Ÿ‘ค Author

Yasna Rezvani LinkedIn | GitHub


๐Ÿ“„ License

This project is for educational and portfolio purposes.


๐Ÿ™ Acknowledgments

  • โ€”Anthropic's Claude for project guidance
  • โ€”Jigsaw/Conversation AI for the dataset
  • โ€”Hugging Face for transformer tools