Sub topic 1
Why aggregate scores are not enough
Prerequisites
This chapter assumes you can do the following:
- Write basic Python and use pandas and NumPy.
- Train and evaluate a text classifier or sequence tagger at least once.
- Read accuracy, precision, recall and F1.
- Explain the difference between train, validation and test splits.
You do not need any particular NLP library. The code uses scikit-learn, pandas and NumPy only for small illustrations.
What a single number hides
A test-set score such as "F1 = 0.88" answers one question: how does the model do on average over this particular test set? It does not tell you which inputs fail, why they fail, or whether the failures are acceptable. Two models with the same F1 can fail in very different places. One may miss every negated sentence. Another may be weak only on a rare class.
Error analysis is the practice of reading, grouping and counting a model's mistakes so that the next change you make is aimed at a cause instead of a guess. The rest of this tutorial builds that practice step by step. This chapter explains why it is needed and how the whole process fits together.
Aggregate scores hide problems in at least five ways:
- Averaging over classes. Accuracy is dominated by frequent classes. A model that is 95% accurate on a class making up 90% of the data and 50% accurate on the rest scores about 91% overall.
- Averaging over input types. Short and long texts, formal and informal writing, and different topics are all pooled. A weakness on one group is diluted by the others.
- Averaging over error kinds. A wrong prediction caused by a mislabeled example looks the same as one caused by a real model weakness. Both lower the score, but only one calls for a model fix.
- Ignoring confidence. The score counts a confident wrong answer and a hesitant wrong answer equally. In a deployed system they behave very differently.
- Ignoring the test set's origin. The score describes the data you tested on. If production text looks different, the number may not transfer.
A worked illustration
Consider a three-class sentiment task. The data below are tiny, but the effect is general.
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
y_true = ["pos", "neg", "neu", "pos", "neg", "neu", "pos", "neg"]
y_pred = ["pos", "neg", "pos", "pos", "neu", "neu", "neg", "neg"]
labels = ["neg", "neu", "pos"]
print("accuracy:", accuracy_score(y_true, y_pred))
# Rows are true labels, columns are predicted labels, in the order of `labels`.
print(confusion_matrix(y_true, y_pred, labels=labels))
print(classification_report(y_true, y_pred, labels=labels, zero_division=0))Accuracy is 0.625. That figure alone suggests a mediocre model with evenly spread problems. The confusion matrix shows more: one "neg" was predicted as "neu", one "neu" was predicted as "pos", and one "pos" was predicted as "neg". Each class has its own pattern of mistakes, and the per-class report gives each a different precision and recall. Later chapters read these tables in detail. The point here is that the table carries information the single number removed.
The error analysis loop
Error analysis is a cycle, not a one-time report. Each pass takes you from a score to a decision and back to a new score.
The steps map onto the chapters of this tutorial:
| Step | What you do | Where it is covered |
|---|---|---|
| Evaluate | Pick metrics and a baseline | Choosing metrics; confusion matrices |
| Collect | Put errors in a sortable table | Collecting errors |
| Categorize | Label a sample of errors by hand | Error taxonomy; span-level errors |
| Slice | Compare subgroups of the data | Slice analysis; uncertainty |
| Diagnose data | Look for label noise and shift | Label noise; distribution shift |
| Probe | Test confidence and behavior | Calibration; behavioral tests; attribution |
| Decide | Rank categories and choose fixes | Prioritization; iteration loop |
What good error analysis produces
The output of error analysis is not a long list of bad examples. It is a short, ranked set of claims that you can act on. A useful claim has four parts: a category, a count, an estimate of how much of the error it explains, and a candidate fix. For example:
- "About 30% of sampled errors involve negation ('not bad at all'). The training set has few negated positives. Candidate fix: add targeted examples and re-train."
- "Accuracy on texts over 40 tokens is 8 points lower than on short texts, based on 120 long examples. Candidate fix: check whether truncation cuts off the sentiment."
- "Twelve of the 50 inspected errors have labels we disagree with. Candidate fix: send those examples for re-annotation before touching the model."
Notice that the third claim is not about the model. Sometimes the correct result of error analysis is that the data, the label guidelines or the metric needs work.
Looking at examples early
You can start with one cheap step before any statistics: read the errors. The snippet below builds a table of mistakes and sorts it so that the most confident wrong predictions come first.
import pandas as pd
df = pd.DataFrame({
"text": [
"great phone",
"not bad at all",
"battery died in a day",
"fine I guess",
"love it",
],
"label": ["pos", "pos", "neg", "neu", "pos"],
"pred": ["pos", "neg", "neg", "pos", "pos"],
"conf": [0.97, 0.81, 0.90, 0.64, 0.99],
})
errors = df[df["label"] != df["pred"]]
# Confident mistakes are often the most informative to read first.
print(errors.sort_values("conf", ascending=False).to_string(index=False))Two errors appear. "not bad at all" is a negation case predicted as negative with confidence 0.81. "fine I guess" is a neutral example predicted as positive with confidence 0.64. Even with two rows you can form hypotheses: negation may be a weakness, and the boundary between neutral and positive may be vague. These are hypotheses, not findings. You would need more examples and a count to support them.
When to do error analysis
Do it whenever a decision depends on understanding failure instead of just measuring it:
- After the first reasonable baseline. Before tuning hyperparameters or switching to a larger model, find out what kind of errors you have. A bigger model will not fix mislabeled data or a train/test mismatch.
- When a score plateaus. If more tuning gives only small gains, the remaining errors usually have structure you can name.
- Before release. Check the groups of users and text types you care about, not only the average.
- After a regression. When a new model version scores lower on some input type, comparing its errors with the old model's shows what changed.
- When the metric and the goal disagree. If users complain but the dashboard looks fine, the metric is probably missing something that error analysis can find.
You can skip a deep analysis when the model is a throwaway prototype, or when the score is already well above what the application needs and the cost of a mistake is low.
Common mistakes at the start
- Reading only the test set repeatedly. If you inspect test errors and then tune the model against them, the test score becomes optimistic. Do your inspection and fixes on validation data or a separate development split, and keep a final test set that you touch rarely.
- Reading too few or too many errors. Five examples gives anecdotes. Thousands cannot be read. A random sample of 50 to 200 errors is a workable range for a first pass, and you can enlarge it for categories that matter.
- Only reading the most confident or most striking errors. These are useful to start with, but they can over-represent unusual cases. Include a random sample too, so your category counts reflect the real error mix.
- Fixing the first problem you see. Without counts you cannot tell whether a problem accounts for 2% or 40% of errors. Later chapters cover ranking.
- Treating every gap as real. A difference between two small groups may be chance. Report group sizes with every score and estimate uncertainty before acting.
A note on scope
This tutorial concentrates on supervised text classification and sequence labeling, because their errors are easy to count and categorize. The same loop applies to other tasks, but the categories and metrics change. For generation or summarization, for example, you categorize outputs by faithfulness or fluency and you often need human judgment for the labels.
Exercises
Exercise
A binary classifier has 96% accuracy on a test set where 95% of examples are the negative class. Name two things you would check before calling the model good, and say what each could reveal.
Show answer
First, check per-class precision and recall (or the confusion matrix). A model that always predicts the negative class already reaches 95% accuracy, so 96% may mean the positive class is mostly missed. Second, slice by text properties or source, such as length or domain. A weakness on one group would be diluted in the overall figure. Checking a majority-class baseline and the calibration of confident errors are also acceptable answers.
Exercise
You inspect the 40 test-set errors of your model, add training examples to fix the most common pattern, retrain, and report the new test accuracy. What is wrong with this process, and how would you change it?
Show answer
The fix was designed by looking at the test set, so the new test accuracy is optimistically biased: the test set influenced the model. Do the error inspection on a validation or development split, make the fix based on that, and evaluate on a held-out test set that was not used for analysis, or collect a fresh one.
Exercise
Write a claim from error analysis that is actionable, and list the four parts it should contain.
Show answer
An actionable claim has a category, a count (or share of sampled errors), an estimate of how much error it explains, and a candidate fix. Example: "Negation accounts for 12 of 50 sampled errors (24%); training data has few negated positives; add targeted examples and re-evaluate."