Sub topic 11
Reading the model's mistakes
This chapter assumes you finished the previous chapters. You need a trained trainer, the tokenized val_ds and test_ds splits, and the tokenizer from the earlier examples. You should also know basic pandas and what a confusion matrix is.
A single F1 score tells you how often the model is wrong. It does not tell you why. Error analysis is the step where you read the wrong predictions and look for patterns. The patterns point to the next fix: more data, a different max_length, cleaner labels, class weights, or a different model.
Why look at errors at all
Two models with the same F1 can fail in very different ways. One may miss every sarcastic review. Another may fail only on long reviews that were truncated. A metric cannot separate these cases, but reading 50 wrong predictions often can.
Most errors fall into a few causes:
| Cause | What you see | Typical fix |
|---|---|---|
| Label noise | The model looks right and the label looks wrong | Relabel or drop the examples |
| Truncation | Errors concentrate in long texts | Raise `max_length`, or keep the head and tail of the text |
| Hard language | Sarcasm, negation, mixed opinions | More examples of that kind, or a larger model |
| Distribution shift | Errors cluster in one domain or style | Add training data from that domain |
| Class imbalance | One class is missed far more often | Class weights, resampling, a different decision threshold |
| Ambiguous task | Humans disagree on the same examples | Tighten the label definitions |
Read the table as a list of hypotheses. You still have to check each one against your data.
The workflow
The diagram below shows the loop. You start from predictions and end with a decision about what to change.
Use the validation set, not the test set
Do your analysis on the validation split. If you read test errors and then change the model to fix them, the test score stops being an honest estimate. Treat the test set as a final check that you look at once. The code below uses val_ds for that reason.
Collect predictions
trainer.predict returns raw logits (unnormalized scores) and the true labels. Convert the logits to probabilities with a softmax. The highest probability is the model's confidence in its own answer.
import numpy as np
import pandas as pd
from scipy.special import softmax
from sklearn.metrics import classification_report, confusion_matrix
output = trainer.predict(val_ds)
probs = softmax(output.predictions, axis=-1)
preds = probs.argmax(axis=-1)
labels = output.label_ids
print(confusion_matrix(labels, preds))
print(classification_report(labels, preds, target_names=["NEGATIVE", "POSITIVE"]))The confusion matrix has true classes in rows and predicted classes in columns. Off-diagonal cells are the errors. Check whether they are balanced. If most errors are false negatives (true POSITIVE predicted NEGATIVE), the model is biased toward one class, and the imbalance fixes from the previous chapter become relevant.
The per-class report shows precision and recall for each class separately. A big gap between the two classes is a stronger signal than a modest overall F1.
Build an error table
Put everything in one DataFrame so you can sort and filter it. Store the length in tokens as well. It lets you test the truncation hypothesis.
df = pd.DataFrame(
{
"text": val_ds["text"],
"label": labels,
"pred": preds,
"confidence": probs.max(axis=-1),
"n_tokens": [len(ids) for ids in val_ds["input_ids"]],
}
)
df["correct"] = df["label"] == df["pred"]
errors = df[~df["correct"]]
print(f"{len(errors)} errors out of {len(df)} ({len(errors) / len(df):.1%})")Because max_length=256 truncates during tokenization, n_tokens never exceeds 256. A value of exactly 256 means the text was cut.
Sort by confidence
Confidence separates two kinds of mistake that need different responses.
- Confident errors (high probability on the wrong class) are the most informative. They are often label noise, or a pattern the model learned wrongly.
- Uncertain errors (probability near 0.5 for two classes) are usually genuinely hard or ambiguous cases. They are the least surprising.
confident_errors = errors.sort_values("confidence", ascending=False).head(20)
for _, row in confident_errors.iterrows():
print(f"true={row['label']} pred={row['pred']} conf={row['confidence']:.2f}")
print(row["text"][:300].replace("\n", " "))
print("-" * 60)Print only the first 300 characters of each text, so that you can read 20 examples in a few minutes. Open the full text only when the start of a review is not enough.
For each example, write a short tag in a spreadsheet or a notes file: label noise, sarcasm, mixed opinion, truncated, other. After 30 to 50 examples you will usually see one or two tags dominate. That count is your evidence for what to change.
Slice the errors
Reading examples one at a time can mislead you, because memorable examples feel more common than they are. Slices give you numbers. A slice is a subset of the data defined by a property, and you compare accuracy across slices.
df["truncated"] = df["n_tokens"] >= 256
df["has_but"] = df["text"].str.contains(r"\bbut\b", case=False)
for column in ["truncated", "has_but"]:
summary = df.groupby(column)["correct"].agg(["mean", "count"])
print(f"\nAccuracy by {column}")
print(summary)Look at both columns of the output. A slice with 12 examples and accuracy 0.50 is noise. A slice with 600 examples and accuracy 0.84 against 0.94 overall is a finding.
Useful slices for text classification include:
- Length in tokens, and whether the text was truncated.
- Presence of negation or contrast words ("not", "but", "although").
- Source or domain, if your data has a metadata column.
- Language features such as all-caps, emoji, or very short texts.
You can choose slices before you look at the errors (to test a hypothesis) or after (to quantify a pattern you noticed). In both cases, report the slice size next to the accuracy.
Check the labels
When confident errors show the model agreeing with you and disagreeing with the label, suspect the label. Public datasets have noisy labels, and annotation guidelines are often unclear on borderline cases.
If you find label noise, you have three options:
- Correct the labels you are sure about and retrain.
- Remove clearly ambiguous examples from the training set.
- Keep them but accept that the achievable score has a ceiling below 100%.
Fix labels in the training and validation splits. Be careful with the test split. Changing test labels after seeing the model's errors makes comparisons with earlier runs unfair, so record what you changed.
A rough check on how noisy the data is: sample 50 errors, relabel them yourself without looking at the original label, and count how often you side with the model. If you side with the model on 15 of 50, about 30% of your errors are label problems.
Turn findings into changes
Change one thing at a time and compare against the same validation split.
- If errors cluster in truncated texts, increase
max_lengthto 512 (the limit for DistilBERT-style models) and compare. Longer inputs cost more memory and time, so check the trade-off. For reviews, the verdict often sits at the end, so keeping the last tokens can help more than keeping the first ones. - If one class has much lower recall, apply the class-imbalance fixes from the previous chapter and check that recall rises without precision collapsing.
- If the model fails on a specific kind of text, add training examples of that kind. Even a few hundred targeted examples can move a slice noticeably.
- If errors look random and low-confidence, you are probably near the ceiling for this model and data. A larger model or more data is the remaining option.
Common mistakes
- Analyzing the test set repeatedly. This leaks information into your decisions. Use validation.
- Reading only the first few errors. The default order of a DataFrame is arbitrary but not random in every dataset. Sort by confidence or sample randomly with
errors.sample(30, random_state=0). - Trusting small slices. Always show the count.
- Fixing symptoms. Adding a rule for one phrase hides the pattern instead of resolving it.
- Skipping the baseline. Save the metrics of the current model before you change anything, so you can tell whether a change helped.
Summary
Metrics tell you how well the model performs. Error analysis tells you where it fails. Build a table of predictions with confidence and length, look at the confusion matrix, read the most confident errors, and measure slices with their sizes. Tag the causes, pick the most common, change one thing, and compare on the same validation split.
Exercise
On your validation set, 40 of the 50 most confident errors are examples where you believe the label is wrong. What does this suggest, and what should you do before changing the model?
Show answer
It suggests label noise rather than a model weakness: the model is confidently disagreeing with labels that appear incorrect. Before changing the model, correct or remove the mislabeled examples in the training and validation data (documenting any change to the test labels), then retrain and compare. Also check a random sample of errors, not only the most confident ones, to see whether the noise is as common among all errors.
Exercise
Your validation accuracy is 0.93 overall. The slice with n_tokens >= 256 has 900 examples at accuracy 0.86. The slice for short texts has 4 examples at accuracy 0.50. Which finding would you act on first, and what would you try?
Show answer
Act on the truncated slice. It has 900 examples and a clear gap of 7 points from the overall figure, while the short-text slice has only 4 examples, which is too few to conclude anything. Try raising max_length (up to the model's limit of 512), or keep the head and tail of long texts, retrain, and compare accuracy on the same slice and on the full validation set. Watch the cost: longer sequences use more memory and time.