The problem
Regex rules and banned-word lists are easy to bypass. Trolls misspell on purpose, use sarcasm, swap letters for numbers, and let emojis carry the payload. Catching that needs semantic understanding, which means a transformer.
But hate speech datasets are heavily imbalanced, roughly 95% safe and 5% hateful. Train naively and the model learns that predicting 'Safe' every time scores 95% accuracy.
The model looks great on paper while letting 100% of hate speech through. That's the imbalance trap, and it's the biggest way ML projects lie to their own builders.
Model choice: RoBERTa, not SciBERT
This came right after the clinical summarizer, and SciBERT was fresh in my head, but a model trained on PubMed has no idea what internet slang means. You can't teach a medical student to moderate a Twitch chat. RoBERTa, trained on raw web and social text, already understood how people argue online.
A mismatch between pre-training data and your task caps your ceiling, no matter how well you fine-tune.
Emojis are signal
Medical reports have perfect grammar. Social media is chaos. I normalized deliberately misspelled slang and translated emojis into text tags like [angry_face] and [middle_finger], because the venom in a message is often in the emoji. A tokenizer that silently drops them is one of the most common reasons moderation models underperform.
The head swap: a bouncer, not a word-guesser
Pre-trained transformers predict missing words. I wanted a bouncer. I removed RoBERTa's pre-training head and attached a linear classifier on the [CLS] token, the compressed summary of the whole input, with a sigmoid output: Safe or Hate Speech.
Fixing the accuracy trap
On the raw data the model hit 95% accuracy by predicting 'Safe' for everything. The metrics said success. The confusion matrix said broken.
The fix was class weighting in the loss function: a small penalty for misclassifying safe text, a large one for letting hate speech through. Evaluation moved to precision, recall, and F1, with recall prioritized because missed hate speech is the expensive mistake.
What I learned
Accuracy is a vanity metric on imbalanced data. The real engineering is in the loss function. Class weighting is how you encode priorities into the math.
Pick the model for the domain before anything else. Domain fit caps your ceiling.
What I owned
- Chose RoBERTa over SciBERT after identifying the domain mismatch
- Built preprocessing for noisy social text, normalizing slang and converting emojis into text tags
- Replaced RoBERTa's pre-training head with a [CLS]-based linear classifier and sigmoid output
- Diagnosed the imbalance trap and fixed it with class-weighted loss
- Moved evaluation to precision, recall, and F1, showing why a 95% accurate model can be broken
- Published the full build as a technical write-up on Medium