File size: 3,130 Bytes
3768681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""
train_baseline.py

Trains a lightweight, fully-offline TF-IDF + Logistic Regression baseline
toxicity classifier on sample_data.csv. This is NOT used by the live
Gradio app (app.py) — it's kept as a separate script for:

  1. Quick sanity-checking new labeled data before it goes into the
     pretrained-model pipeline.
  2. A fast, interpretable comparison point against unitary/toxic-bert.
  3. A template for a retraining loop as more labeled examples arrive.

Run locally:  python train_baseline.py
"""

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
import joblib


def load_data(path: str = "sample_data.csv") -> pd.DataFrame:
    df = pd.read_csv(path)
    print(f"Loaded {len(df)} rows | class balance:\n{df['label'].value_counts()}")
    return df


def train(df: pd.DataFrame):
    X_train, X_test, y_train, y_test = train_test_split(
        df["text"], df["label"], test_size=0.3, random_state=42, stratify=df["label"]
    )

    vectorizer = TfidfVectorizer(max_features=2000, ngram_range=(1, 2))
    X_train_vec = vectorizer.fit_transform(X_train)
    X_test_vec = vectorizer.transform(X_test)

    clf = LogisticRegression(max_iter=1000, class_weight="balanced")
    clf.fit(X_train_vec, y_train)

    y_pred = clf.predict(X_test_vec)
    print("\nClassification report:")
    print(classification_report(y_test, y_pred, target_names=["non-toxic", "toxic"]))
    print("Confusion matrix:")
    print(confusion_matrix(y_test, y_pred))

    return clf, vectorizer


def run_edge_case_suite(clf, vectorizer):
    """Regression-test the model against known tricky cases (sarcasm,
    identity terms, code-switching) — expand this list as real examples
    are found in production moderation logs."""
    edge_cases = [
        ("Oh great, ANOTHER meeting that could've been an email. Love it.", "non-toxic"),
        ("The Black Lives Matter panel was thoughtful and well organized.", "non-toxic"),
        ("I'm so sick of dealing with buggy code, this is so frustrating.", "non-toxic"),
        ("Ang bobo mo talaga, wala kang alam.", "toxic"),
        ("You did an amazing job on this project, congrats to the whole team!", "non-toxic"),
    ]
    print("\nEdge-case suite results:")
    for text, expected in edge_cases:
        vec = vectorizer.transform([text])
        pred = clf.predict(vec)[0]
        proba = clf.predict_proba(vec)[0][1]
        pred_label = "toxic" if pred else "non-toxic"
        flag = "OK " if pred_label == expected else "MISS"
        print(f"  [{flag}] expected={expected:9s} got={pred_label:9s} score={proba:.3f}  {text!r}")


def main():
    df = load_data()
    clf, vectorizer = train(df)
    run_edge_case_suite(clf, vectorizer)

    joblib.dump(clf, "toxicity_baseline_model.joblib")
    joblib.dump(vectorizer, "toxicity_vectorizer.joblib")
    print("\nSaved: toxicity_baseline_model.joblib, toxicity_vectorizer.joblib")


if __name__ == "__main__":
    main()