Sub topic 4
Collecting errors into an inspectable table
This chapter assumes you can train and evaluate a text classifier, you know accuracy, precision, recall and F1, and you are comfortable with pandas. The previous chapter showed how a confusion matrix tells you which classes the model mixes up. Here you move from counts to the actual examples, so that you can read them.
Why a table of errors comes before everything else
A confusion matrix says that 40 "neutral" reviews were predicted "positive." It does not say why. To learn why, you have to read the 40 reviews. Reading is only practical if the examples sit in one table with the text, the gold label, the prediction and the model's confidence side by side.
This table is the working surface for the rest of the tutorial. The error taxonomy, the slices, the calibration check and the label-noise review all start from it. If you build it carefully once, you reuse it in every later step.
What the table should contain
Start with one row per evaluation example, not only the wrong ones. Keeping the correct rows lets you compute slice accuracy later, because accuracy needs both the numerator and the denominator.
| Column | Meaning | Why you need it |
|---|---|---|
| `id` | Stable identifier from your dataset | Lets you join notes and re-find the example after re-splitting |
| `text` | The raw input | The thing you will read |
| `label` | Gold label | Ground truth, which may itself be wrong |
| `pred` | Predicted label | What the model said |
| `conf` | Probability of the predicted class | Orders the examples and feeds calibration |
| `correct` | `label == pred` | Cheap filter and slice aggregate |
| `split` | train, validation or test | Prevents mixing data you tuned on with data you did not |
Add a model_version column if you compare runs. Add the second-highest class and its probability if you want to see how close the decision was.
Building the table
Most of the work is lining up arrays. Keep predictions in the same order as the inputs, and carry the id through so you never rely on row position alone.
The following snippet takes a small, already-labeled set and filters to the mistakes. It sorts them by confidence, highest 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))The output lists two rows: "not bad at all" (gold pos, predicted neg, confidence 0.81) and "fine I guess" (gold neu, predicted pos, confidence 0.64). The first is a negation failure, which is a pattern worth counting. The second may be an ambiguous label. Even with five rows, the table already suggests two different kinds of problem.
Getting confidence from a real model
With a scikit-learn style classifier, predict_proba returns one probability per class. Take the maximum for conf and the class with that maximum for pred. With a transformer, apply softmax to the logits first. Raw logits are not probabilities and cannot be compared across examples in the same way.
Whatever the source, record what conf means. A softmax maximum is not guaranteed to match the true chance of being right, a point the calibration chapter returns to. For now, treat it as a ranking signal.
Choosing which errors to read
You rarely read every error. The choice of sample shapes what you will conclude, so make it on purpose.
- Highest confidence first. Confident mistakes often point to label noise or a systematic blind spot, because the model is sure and wrong.
- Lowest confidence first. These are borderline cases. They tell you about ambiguity and about where the decision boundary is hard.
- Random sample. A random draw of, say, 50 errors gives an unbiased view of the whole error population. Use it to estimate how common each failure is.
- Stratified by class pair. Draw some errors from each off-diagonal cell of the confusion matrix, so that rare confusions are not drowned out by the common ones.
Use a mixture. Sorting by confidence is good for finding interesting cases, but any frequency you quote should come from the random sample. If you only read the top of a sorted list, you will overestimate how often the model is confidently wrong.
Adding columns that help you read
Raw text and labels are enough to start. A few cheap derived columns make patterns visible sooner.
n_tokens: the number of whitespace tokens, to spot length effects.has_negation: whether the text contains words such as "not" or "never."confusion: a string such asneu->pos, which lets you group errors by class pair.note: an empty column where you write a short free-text comment as you read.
You will use some of these as slice keys in the next chapters. Adding them now costs little.
import pandas as pd
df = pd.DataFrame({
"id": [1, 2, 3, 4],
"text": ["not bad at all", "fine I guess", "love it", "never again"],
"label": ["pos", "neu", "pos", "neg"],
"pred": ["neg", "pos", "pos", "neg"],
"conf": [0.81, 0.64, 0.99, 0.88],
})
df["correct"] = df["label"] == df["pred"]
df["confusion"] = df["label"] + "->" + df["pred"]
df["n_tokens"] = df["text"].str.split().str.len()
df["has_negation"] = df["text"].str.contains(r"\b(?:not|never|no)\b", case=False)
df["note"] = ""
errors = df[~df["correct"]].sort_values("conf", ascending=False)
print(errors[["id", "text", "confusion", "conf", "has_negation"]].to_string(index=False))
print(errors["confusion"].value_counts())The value_counts call tells you which confusions dominate the error set. This is a first, rough ranking, and the taxonomy chapter refines it.
Reading errors well
Reading is a skill with a few habits worth setting early.
- Read with the gold label hidden at first, when you can. Form your own judgment, then compare. If you disagree with the gold label, that is a candidate for label noise.
- Write a note for each example. Even a short phrase such as "negation" or "sarcasm" will do. Notes become the raw material for the taxonomy.
- Do not fix categories yet. Let them emerge. Fixed categories chosen in advance make you see what you expected.
- Look at the full input. Truncated text, stripped punctuation or encoding damage shows up only if you read what the model actually received, not only what was stored.
- Keep the preprocessing the model saw. If the pipeline lowercases or tokenizes before prediction, check that your table shows the same version, or add a second column for it.
Common mistakes
- Misaligned predictions. If you shuffle, filter or deduplicate the data after predicting, labels and predictions can slip out of step. Compare a few rows by hand, and carry an
idcolumn through every step. - Reading only the top of a sorted list. The highest-confidence errors are not representative. Quote frequencies only from a random sample.
- Losing the correct rows. If you save only the errors, you cannot compute slice accuracy or error rates later. Save the whole table and filter when you read.
- Ties and rounding in confidence. Many examples can share a confidence of 0.99 after rounding. Break ties with a second key, such as
id, so that your samples can be reproduced. - Mixing models. If you compare two model versions, store both predictions in separate columns. Errors that both models share often point to data problems, and errors that only one makes point to model differences.
Making the sample reproducible
Draw random samples with a fixed seed, and save the sampled ids to disk. Someone else, or you next week, should be able to read exactly the same examples.
import pandas as pd
errors = pd.DataFrame({
"id": range(1, 21),
"text": [f"example {i}" for i in range(1, 21)],
"conf": [round(0.5 + i * 0.02, 2) for i in range(20)],
})
sample = errors.sample(n=5, random_state=42).sort_values("id")
print(sample["id"].tolist())
sample.to_csv("error_sample.csv", index=False)The CSV is also a convenient format for hand annotation in a spreadsheet. When you load it back, join on id rather than on text, since texts can repeat.
How many errors to read
There is no fixed number. A common starting point is 50 to 100 randomly drawn errors. With 100 errors, a category that accounts for 20 of them is estimated at about 20 percent, with a wide margin of uncertainty. If a category matters for a decision, read more until its share is stable enough to rank against the others. Chapter material on uncertainty later in the tutorial makes this precise.
If the error set is small, for example 30 mistakes in total, read all of them.
Exercise
You sort all errors by confidence, read the top 30, and find that 12 of them look like label noise. A colleague concludes that 40 percent of all model errors are label noise. What is wrong with this conclusion, and what should you do instead?
Show answer
The top 30 are the most confident errors, which are more likely than average to be label noise, so they are not representative of all errors. The 40 percent figure applies only to that slice. Draw a random sample of errors, with a fixed seed, read it, and estimate the label-noise share from that sample. You can still report the confident-error result separately as a finding about high-confidence mistakes.
Exercise
Write the pandas expression that, from a DataFrame df with columns label and pred, adds a confusion column such as neu->pos and then counts how many errors fall in each confusion.
Show answer
df["confusion"] = df["label"] + "->" + df["pred"] Then count only the errors: df[df["label"] != df["pred"]]["confusion"].value_counts(). Filtering first matters, because otherwise the correct pairs such as pos->pos would appear in the counts.