Sub topic 10
Why negation, sarcasm, and slang cause errors
This chapter explains why sentiment models fail on certain kinds of language, and how to find those failures in your own data. It assumes you can run Python and scikit-learn, and that you have met the VADER lexicon baseline, the TF-IDF plus logistic regression baseline, and precision, recall, and F1. You do not need to know how transformers work internally.
The common root of the errors
Every sentiment method makes a simplifying assumption about language.
- A lexicon scores words one by one, using a fixed value per word.
- A TF-IDF model with logistic regression assigns one weight to each word or n-gram, then adds the weights up.
- A transformer reads context, but it learned from examples. It is only as good as the patterns in its training data.
Negation, sarcasm, and slang each break one of these assumptions. The sections below take them in turn. Knowing which assumption breaks tells you which fix to try.
Negation
Negation reverses or weakens the polarity of the words near it.
- "The food was good" is positive.
- "The food was not good" is negative.
- "The food was not bad" is mildly positive, not negative.
- "I can't say I loved it" is negative, and "love" sits far from the negator.
How each model handles it
VADER has explicit rules for negation. It looks at the three words before a sentiment word and flips and dampens the score if one of them is a negator such as "not" or "never". This handles "not good" well. It handles long-range cases like "I can't say I loved it" less reliably, because "can't" is two words from "loved" and the rule is local.
A unigram bag-of-words model has no such rule. "not" and "good" are separate features. The model might learn a negative weight for "not" and a positive weight for "good", and then the sum decides the label. For "not good" this often works by accident. For "not bad" it often fails, since "bad" has a strong negative weight.
Adding bigrams, as in ngram_range=(1, 2), helps. The feature "not good" gets its own weight. The cost is a larger, sparser feature space, so you need enough data to estimate those weights. A bigram that appears twice in training gives you a noisy weight.
A pretrained transformer reads the whole sentence at once, so it usually handles both short and long-range negation better. It is not perfect, especially with double negatives and negation inside a clause ("I don't think it's terrible").
Testing negation directly
You can probe a model with minimal pairs: sentences that differ only in the negation. This is a cheap, useful check.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
pairs = [
("The screen is good.", "The screen is not good."),
("The screen is bad.", "The screen is not bad."),
("I loved the ending.", "I can't say I loved the ending."),
("This is great.", "This is never great."),
]
for plain, negated in pairs:
a = analyzer.polarity_scores(plain)["compound"]
b = analyzer.polarity_scores(negated)["compound"]
print(f"{plain!r}: {a:+.2f} | {negated!r}: {b:+.2f}")Look at the signs and the size of the change. A good model flips the sign for "good" to "not good". For "not bad", the compound score should land near zero or slightly positive, not strongly negative. The exact numbers depend on the VADER version, so read them as a probe, not a benchmark.
Preprocessing mistakes that make negation worse
Some cleaning steps remove the signal. The most common one is stop-word removal. Standard English stop-word lists include "not", "no", "nor", and "never". If you strip them, "not good" becomes "good" and the label flips silently. Either use a stop-word list without negators, or skip stop-word removal for sentiment. Stripping apostrophes can also turn "can't" into "cant", which your vocabulary may not recognize as a negator. Tokenizer choices matter here as well.
Sarcasm and irony
Sarcasm says the opposite of what it means. "Great, another outage on launch day" contains a positive word ("great") and a negative situation. Irony is a close relative: the literal meaning and the intended meaning differ.
Why sarcasm is hard
- The positive words are really there. A lexicon or bag-of-words model sees "great" and scores it positive.
- The signal is often outside the text: shared knowledge, the author's history, a preceding post in a thread, or the tone of voice.
- Sarcasm is rare in most datasets, so models see few examples. Rare patterns get small weights.
- Human annotators disagree about it. If humans cannot agree on the label, you cannot expect a model to learn a consistent rule.
Weak cues exist: exaggerated punctuation, quotation marks around a positive word, positive words combined with a negative event ("love waiting two hours"), or hashtags like #sarcasm. Hashtags are a trap, though. If you use #sarcasm to build labels and then delete the hashtag, as the normalization step from earlier chapters does, the model learns from labels it cannot see at inference time. Check that the cue you used for labeling is not leaking into your features, or that it is absent when you deploy.
What you can realistically do
- Measure it. Tag a sample of errors as sarcastic and count them. If sarcasm is 2% of your errors, do not spend a week on it.
- Add context if you have it. A reply's parent post, the product category, or the user's rating often disambiguates.
- Use a model trained on text similar to yours. Models trained on social posts have seen more sarcasm than models trained on product reviews.
- Accept a ceiling. Set expectations with whoever uses the results. Say plainly that sarcastic posts will sometimes be mislabeled.
Slang, emojis, and informal spelling
Slang and informal text cause a different kind of error. The model does not misread the structure. It does not know the word.
- Out-of-vocabulary words. "That concert was fire" is positive, but "fire" is a neutral or negative word in a general-purpose lexicon.
- Words that change meaning across communities. "Sick" can mean ill or impressive. "Insane" and "wicked" can be praise.
- Creative spelling: "soooo gooood", "gr8", "luv". A TF-IDF vocabulary built from clean text has none of these tokens.
- Abbreviations: "smh", "ngl", "imo", "fr".
- Emojis. A thumbs-up or a crying face carries strong sentiment, but "😭" can mean sadness or laughing so hard you cry, depending on context.
- New terms. Slang changes faster than a lexicon or a training set gets updated, so a model's accuracy drifts down as time passes.
How each approach copes
| Approach | Behavior on unseen slang | Typical fix |
|---|---|---|
| Lexicon (VADER) | Unknown words score zero, so they are ignored. VADER does include some slang and emoticons. | Add entries to the lexicon dictionary |
| TF-IDF + logistic regression | Words not in the training vocabulary are dropped at prediction time | Retrain on recent in-domain data; consider character n-grams |
| Pretrained transformer | Subword tokenization splits unknown words into pieces, which gives partial information | Choose a model trained on social text; fine-tune |
VADER lets you extend its lexicon, which is a fast fix when you know your domain's vocabulary:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
text = "That concert was fire, the band was sick!"
print("before:", analyzer.polarity_scores(text)["compound"])
analyzer.lexicon.update({"fire": 2.5, "sick": 2.0})
print("after: ", analyzer.polarity_scores(text)["compound"])The values follow VADER's scale, roughly from -4 to +4. Be careful with edits like this. Adding "sick" as positive will hurt on "I felt sick after eating there". Every override trades one error for another, so check the change against a labeled sample, not one example.
For TF-IDF models, character n-grams give some robustness to spelling variants. The token "gooood" shares many character sequences with "good":
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 5), lowercase=True)
vec.fit(["so good", "really good", "gooood stuff", "not good"])
print(len(vec.vocabulary_), "character n-gram features")Character n-grams increase the feature count considerably and can make the model slower to train, so compare them against word n-grams on a validation set before you adopt them.
Finding these errors in your data
Aggregate metrics hide these failures. A model with 0.88 F1 might be at 0.60 on sentences with negation. Slice your evaluation by phenomenon.
The approach:
- Take misclassified examples from a validation set.
- Add simple tags using rules (for example, contains a negator, contains an emoji, contains
#), and manual tags for sarcasm. - Compute accuracy per slice and compare it with the overall score.
import re
NEGATORS = re.compile(r"\b(not|no|never|n't|cannot|can't|don't|isn't|wasn't)\b", re.I)
EMOJI = re.compile(r"[\U0001F300-\U0001FAFF\u2600-\u27BF]")
def tags(text):
found = []
if NEGATORS.search(text):
found.append("negation")
if EMOJI.search(text):
found.append("emoji")
if re.search(r"(.)\1{2,}", text):
found.append("elongation")
return found or ["none"]
examples = [
("not good at all", "neg", "neg"),
("not bad actually", "pos", "neg"),
("soooo good", "pos", "pos"),
("love it 😭", "pos", "neg"),
("works fine", "pos", "pos"),
]
stats = {}
for text, truth, pred in examples:
for tag in tags(text):
right, total = stats.get(tag, (0, 0))
stats[tag] = (right + (truth == pred), total + 1)
for tag, (right, total) in sorted(stats.items()):
print(f"{tag:11s} {right}/{total} correct")The regex for negators is crude and will miss some forms such as curly apostrophes. That is acceptable for slicing. The goal is a quick signal about where to look, not a perfect label. With only five examples the counts mean nothing. Use at least a few dozen per slice before you draw any conclusion.
Choosing a response
| Finding | Likely cause | First thing to try |
|---|---|---|
| Errors on "not bad" and "no complaints" | Negation not modeled | Add bigrams, keep negators, test a transformer |
| Positive-word, negative-label errors with an annoyed tone | Sarcasm | Add context; measure frequency before investing |
| Neutral predictions on posts full of unfamiliar words | Slang outside the vocabulary | Extend lexicon, use character n-grams, switch to a social-text model |
| Emoji posts mislabeled | Emojis removed or unknown | Keep emojis; map to text descriptions or use a model that knows them |
| Good score on reviews, poor score on posts | Domain shift | Evaluate on a labeled sample of posts; see the domain shift chapter |
Exercise
A TF-IDF plus logistic regression model, trained with unigrams only after removing English stop words with a standard list, labels "The service was not good" as positive. Give two changes that would likely fix this, and say how you would confirm the fix.
Show answer
First, the stop-word list probably removes "not", leaving "service good". Remove negators from the stop-word list, or skip stop-word removal. Second, add bigrams (ngram_range=(1, 2)) so "not good" becomes its own feature. To confirm, build minimal pairs such as "The service was good" and "The service was not good", check that the predictions differ, and compare F1 on a validation slice of sentences containing negators before and after the change.
Exercise
Your team labeled sarcastic posts by searching for the hashtag #sarcasm, then removed the hashtag during normalization and trained a classifier. Offline results look excellent. What is the risk, and what would you do?
Show answer
The label was derived from a cue (the hashtag) that is missing from real inference data, so the offline result overstates real performance, and the model may have learned artifacts of how the sample was collected. Evaluate on a separate sample labeled by human annotators without relying on the hashtag, report agreement between annotators, and measure how often sarcasm actually appears in your data before investing further.
Exercise
You add "fire": 2.5 to the VADER lexicon after seeing "That concert was fire" scored as neutral. Why should you not stop at that one example?
Show answer
The override changes every sentence containing "fire", including negative ones such as "the kitchen was on fire" or "the fire alarm kept going off". Run the change against a labeled sample from your domain, compare precision and recall before and after, and keep it only if the net result improves.