Sub topic 2
Building an error taxonomy by hand
This chapter assumes you know basic Python, pandas, and NumPy. You should have trained a text classifier at least once and understand accuracy, precision, recall, F1, and train, validation, and test splits.
An aggregate score such as 0.88 accuracy shows how often the model is right, but not why it fails. An error taxonomy is a set of named categories that you assign to misclassified examples after reading them.
Labeling a sample by hand
Collect the errors into a table, sort them by confidence, and read 50 to 100 of them. Give each one a short category name, such as "negation", "sarcasm", or "ambiguous label". Reuse names. Stop when new errors mostly fit existing categories.
import pandas as pd
df = pd.DataFrame({
"text": ["not bad at all", "battery died in a day", "fine I guess", "love it"],
"label": ["pos", "neg", "neu", "pos"],
"pred": ["neg", "neg", "pos", "pos"],
"conf": [0.81, 0.90, 0.64, 0.99],
})
errors = df[df["label"] != df["pred"]].sort_values("conf", ascending=False).copy()
errors["category"] = ["negation", "neutral_as_pos"]
print(errors.to_string(index=False))Slicing results by text properties
A slice is a subset of examples that share a property, such as length. Compare accuracy across slices to find weak spots that the overall score hides.
df["n_tokens"] = df["text"].str.split().str.len()
df["correct"] = df["label"] == df["pred"]
df["bucket"] = pd.cut(df["n_tokens"], bins=[0, 3, 8, 1000],
labels=["short", "medium", "long"])
print(df.groupby("bucket", observed=True)["correct"].agg(["mean", "count"]))Telling real slice gaps from noise
A slice with 10 examples can move by 20 points through chance alone. Bootstrap the per-example correctness to estimate the uncertainty.
import numpy as np
rng = np.random.default_rng(0)
correct = np.array([1, 1, 0, 1, 0, 1, 1, 0, 1, 1])
boot = [rng.choice(correct, size=len(correct), replace=True).mean()
for _ in range(2000)]
low, high = np.percentile(boot, [2.5, 97.5])
print(f"accuracy={correct.mean():.2f}, 95% CI=({low:.2f}, {high:.2f})")If the interval is wide, or it overlaps the overall accuracy, treat the gap as unproven and collect more examples.
> Bootstrap intervals assume independent examples. Near-duplicate texts make the interval too narrow.
Spotting label noise and ambiguous annotations
Some errors come from the gold label, not the model. Look for errors where a careful annotator might pick the predicted label. Tag these as "label noise" in your taxonomy and count them separately, because retraining cannot fix them. Re-annotating a sample of these items with a second annotator shows how often annotators disagree.
Checking confidence and calibration
A calibrated model has confidence that matches its accuracy. Bin predictions by confidence and compute the weighted average gap between confidence and accuracy. This value is the expected calibration error (ECE).
def expected_calibration_error(conf, correct, n_bins=10):
conf = np.asarray(conf, dtype=float)
correct = np.asarray(correct, dtype=float)
bins = np.minimum((conf * n_bins).astype(int), n_bins - 1)
total = 0.0
for b in range(n_bins):
mask = bins == b
if mask.any():
total += mask.mean() * abs(correct[mask].mean() - conf[mask].mean())
return total
conf = [0.95, 0.90, 0.85, 0.99, 0.60, 0.55, 0.70, 0.98]
correct = [1, 0, 1, 1, 0, 1, 1, 0]
print(round(expected_calibration_error(conf, correct), 3))A high ECE means confidence scores cannot be trusted for ranking which errors to review first.
Exercise
Why sort errors by confidence before labeling them?
Show answer
Confident mistakes are often the most informative. They show systematic patterns or label noise, so reading them first surfaces the largest problems early.