Sub topic 14
Reading your errors and using results responsibly
This chapter assumes you can train and score a sentiment classifier (a lexicon such as VADER, a TF-IDF plus logistic regression baseline, or a pretrained transformer). You should also know precision, recall, F1, and how to read a confusion matrix. Here we look at what to do after you have a number. A single F1 score tells you how often a model is wrong. It does not tell you why, for whom, or what that costs.
Why aggregate metrics are not enough
Suppose a model reaches a macro F1 of 0.82 on held-out reviews. That could mean errors spread evenly across all kinds of text. It could also mean the model is nearly perfect on short, plain reviews and close to random on sarcastic posts, posts with mixed opinions, or posts in a dialect that was rare in training. The score hides which case you are in.
Error analysis is the practice of collecting the examples a model gets wrong, grouping them by cause, and deciding what to change. It usually gives better returns than trying another model architecture.
Collecting the errors
Start by putting predictions, labels, and the original text in one table. Keep the original, un-normalized text next to the cleaned text, because some bugs come from the cleaning step itself.
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
train_texts = [
"Great product, works perfectly",
"Absolutely love it",
"Fantastic quality and fast shipping",
"Terrible, broke after one day",
"Waste of money, very disappointed",
"Awful customer service",
]
train_labels = ["pos", "pos", "pos", "neg", "neg", "neg"]
test_texts = [
"Love the quality",
"Disappointed, it broke quickly",
"Not great, not terrible",
"Oh great, another outage",
]
test_labels = ["pos", "neg", "neu", "neg"]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(max_iter=1000),
)
model.fit(train_texts, train_labels)
proba = model.predict_proba(test_texts)
df = pd.DataFrame({
"text": test_texts,
"gold": test_labels,
"pred": model.predict(test_texts),
"confidence": proba.max(axis=1).round(3),
})
errors = df[df["gold"] != df["pred"]]
print(errors.sort_values("confidence", ascending=False).to_string(index=False))Sort errors by confidence, highest first. A confident wrong prediction is more informative than a hesitant one. It often points to label noise or to a pattern the model has learned incorrectly.
A taxonomy of errors
Read at least 50 to 100 errors, or all of them if there are fewer. Tag each with one primary cause. The categories below are a common starting point. Adapt them to your data.
| Category | What it looks like | Typical fix |
|---|---|---|
| Label noise | The gold label is wrong or debatable | Re-annotate, measure annotator agreement |
| Negation and scope | "not bad at all" predicted negative | More data with negation, n-grams, or a contextual model |
| Sarcasm and irony | "Oh great, another outage" predicted positive | Context features, targeted training data, or accept as a limit |
| Mixed sentiment | Praise for one feature, complaint about another | Aspect-based analysis or a mixed label |
| Neutral boundary | Factual text split between neutral and weak sentiment | Clearer guidelines, review the neutral class |
| Preprocessing damage | Emoji, punctuation, or casing removed by cleaning | Change normalization |
| Domain vocabulary | "sick" or "unreal" read in the wrong sense | Domain data, fine-tuning |
| Out of scope | Spam, non-target language, questions | Filter before classification |
Count the tags. If 35 percent of your errors are label noise, a better model will not help. Fix the labels first. If most errors are neutral-boundary cases, the problem is the label scheme, and you should go back to how the task was defined.
Checking label quality
Disagreement between the model and the gold label is sometimes the model's fault and sometimes the label's. To tell them apart, have a second person label a sample of the disputed examples without seeing the gold label or the prediction. Then compute agreement.
from sklearn.metrics import cohen_kappa_score
annotator_a = ["pos", "neg", "neu", "neg", "pos", "neu", "neg", "pos"]
annotator_b = ["pos", "neg", "pos", "neg", "pos", "neu", "neu", "pos"]
kappa = cohen_kappa_score(annotator_a, annotator_b)
print(round(kappa, 3))Cohen's kappa corrects raw agreement for the agreement expected by chance. Values near 1 mean strong agreement. Values below roughly 0.6 suggest the guidelines are unclear or the task is subjective. If two humans agree only moderately, a model cannot be expected to exceed that level against a single annotator's labels. Human agreement is a practical ceiling for the benchmark.
Slicing: where does the model fail?
Overall metrics average over very different kinds of text. Compute the same metrics on slices.
slices = {
"has_negation": df["text"].str.contains(r"\b(?:not|no|never|n't)\b", case=False, regex=True),
"short": df["text"].str.split().str.len() <= 4,
}
for name, mask in slices.items():
subset = df[mask]
if len(subset) == 0:
continue
acc = (subset["gold"] == subset["pred"]).mean()
print(f"{name}: n={len(subset)}, accuracy={acc:.2f}")Useful slices include text length, presence of negation, presence of emoji, source (reviews versus social posts), language variety, and product category. Always report the slice size next to the metric. A slice with eight examples gives a noisy number, and a drop from 0.9 to 0.75 on it may not mean anything.
Fixing what you find
Match the fix to the cause.
- Label problems. Re-annotate the disputed items, write down the rule you used, and retrain. Rerunning the same model on better labels often gives the largest gain.
- Preprocessing problems. If cleaning removed signal, such as stripping "!!!" or emoji, change the normalization and compare scores again.
- Coverage problems. If the model fails on a recognizable pattern, collect or label more examples of that pattern. A small set of targeted examples can help more than a large generic set.
- Model limits. Some errors, especially sarcasm that depends on outside knowledge, will remain. Record them as known limitations.
Change one thing at a time and re-evaluate on the same held-out set. Be careful not to tune repeatedly against the test set. If you read test errors and then adjust the model to fix them, the test score becomes optimistic. Keep a separate validation set for iteration and use the final test set once.
Responsible use
A sentiment score looks precise but is a statistical guess. Several practices keep its use honest.
Report uncertainty. Show per-class precision and recall, the confusion matrix, and a confidence interval where possible. For a small test set, bootstrap resampling gives a rough interval. A claim like "sentiment improved by 2 points" needs a sample large enough to support it.
State what the data represents. Posts from one platform are not a random sample of customers. People who write reviews or post online tend to have stronger opinions than those who do not, and bots and duplicate posts can distort counts. A dashboard that says "72 percent positive" describes the collected posts, not the public.
Check for uneven performance across groups. Models trained mostly on one dialect or style can score text from other groups as more negative or less reliably. Dialect features, identity terms, and non-standard spelling can all shift a score. Compute metrics by available group or proxy, such as language variety or source, and look at both error rates and the direction of errors. If a group is mislabeled as negative more often, any downstream action based on those labels will treat that group differently.
Match the decision to the error cost. Using sentiment to route a support ticket to a human is low risk, because a wrong guess costs a short delay. Using it to rank employees, flag individuals, screen applicants, or take enforcement action is high risk. In those settings a model of this kind should not be the sole basis for a decision, and a human should review the outcome.
Respect privacy and terms of use. Posts can contain names, locations, and other personal details. Collect only what you need, remove identifiers you do not need, store data securely, and follow the platform's terms and applicable law.
Monitor after deployment. Language changes. New slang, products, and events shift the vocabulary, so a model that was good at launch can degrade. Label a small fresh sample on a schedule, recompute the metrics, and compare them to the baseline. Alert on a drop, not just on a crash.
Document the model. Write a short note covering the label scheme, training data source, evaluation data, per-class and per-slice results, known failure modes, and intended and unintended uses. This is the simplest way to stop a model from being used for something it was never tested on.
Exercise
A team trains a sentiment classifier and gets macro F1 of 0.80. They read 100 errors and tag them: 38 label noise, 20 sarcasm, 15 neutral-boundary, 12 negation, 10 preprocessing damage, 5 other. What should they do first, and why? Name one mistake to avoid while fixing it.
Show answer
Fix label quality first, because label noise is the largest category (38 of 100). Re-annotate the disputed items with a second annotator, compute Cohen's kappa, and tighten the guidelines, which will also help the neutral-boundary cases. The preprocessing damage is a cheap second fix. A mistake to avoid is tuning repeatedly against the same test set after reading its errors. Use a validation split for iteration and keep a fresh test sample for the final number.
Exercise
A dashboard shows that posts written in one dialect are labeled negative 30 percent more often than similar posts in standard English. Name two checks you would run and one decision-level safeguard.
Show answer
First, compare per-class precision and recall on each dialect slice, with slice sizes, to see whether the model is making more false negatives for that dialect. Second, have annotators label a sample from that slice blind to the model output to see whether the gold labels or the model are at fault. As a safeguard, do not use the scores for any decision about individuals without human review, and document the gap as a known limitation until it is fixed.