Sub topic 11
Reading the Model's Mistakes
Assume you have trained a text classifier and evaluated it on a held-out test set. Error analysis means inspecting individual predictions instead of looking only at one metric. It helps you find patterns that accuracy and F1 can hide.
Start with a prediction table
Create one row for each example. Include the original text, the true label, the predicted label, and the model's confidence. A confidence score is the probability assigned to the predicted class.
The following code continues from a Trainer run with test_ds, trainer, and id2label already defined:
import numpy as np
import pandas as pd
prediction = trainer.predict(test_ds)
logits = prediction.predictions
true_ids = prediction.label_ids
# Convert logits to probabilities without requiring another library.
shifted = logits - logits.max(axis=1, keepdims=True)
probabilities = np.exp(shifted)
probabilities /= probabilities.sum(axis=1, keepdims=True)
predicted_ids = probabilities.argmax(axis=1)
confidence = probabilities.max(axis=1)
errors = pd.DataFrame({
"text": test_ds["text"],
"true_id": true_ids,
"predicted_id": predicted_ids,
"true_label": [id2label[i] for i in true_ids],
"predicted_label": [id2label[i] for i in predicted_ids],
"confidence": confidence,
})
errors["is_error"] = errors["true_id"] != errors["predicted_id"]
print(errors["is_error"].value_counts())
print(errors[errors["is_error"]].sort_values("confidence", ascending=False).head(10))The first rows to inspect are often high-confidence errors. These are examples where the model is certain but wrong. They may reveal misleading words, unusual writing, annotation mistakes, or a gap between the training data and real use.
Low-confidence examples are useful too. They show where the classes overlap or where the text does not provide enough evidence.
Group errors by type
Do not read mistakes as a random list. Group them into possible causes:
- Ambiguous text can reasonably receive either label.
- Negation can reverse the meaning of a phrase, such as “not especially good.”
- Sarcasm can make positive words express a negative opinion.
- Long documents may lose important information when truncation removes later tokens.
- Spelling, slang, code-switching, and unusual formatting may be rare in training data.
- Incorrect labels create a ceiling that the model cannot overcome.
- Duplicate or near-duplicate examples can make test performance look better than real performance.
Compare the model's mistakes with correct predictions that use similar language. This comparison helps distinguish a missing capability from a genuinely ambiguous example.
Analyze slices, not only the whole test set
A slice is a subset defined by a property of the input, such as document length, presence of a question mark, or a known product category. Calculate metrics for each important slice.
For example, create length buckets:
errors["word_count"] = errors["text"].str.split().str.len()
errors["length_group"] = pd.cut(
errors["word_count"],
bins=[0, 50, 150, 10_000],
labels=["short", "medium", "long"],
)
print(
errors.groupby("length_group", observed=True)["is_error"]
.agg(["count", "mean"])
.rename(columns={"mean": "error_rate"})
)A high error rate for long text suggests that max_length may be too small, or that the task requires information spread across the document. A high error rate for one label suggests checking class balance, label quality, and per-class recall.
Use mistakes to choose the next experiment
Connect each pattern to one controlled change:
| Observed pattern | Possible cause | Reasonable next step |
|---|---|---|
| Errors rise with length | Important tokens are truncated | Increase the maximum length or chunk documents |
| One class has low recall | Class imbalance or weak class features | Inspect class counts and use class-aware training |
| Confident errors share sarcasm | Meaning depends on context | Add representative examples or review labels |
| Errors contain unfamiliar vocabulary | Domain mismatch | Add in-domain labeled data |
Avoid changing several settings at once. Record the error pattern, the hypothesis, the change, and the result. This turns inspection into a repeatable debugging process.
Exercise
Why should you inspect high-confidence errors separately from low-confidence errors?
Show answer
High-confidence errors often expose systematic problems such as misleading patterns, truncation, or bad labels, while low-confidence errors often indicate ambiguity or insufficient evidence.