TExcelTAD

Error Analysis and Slices

A single number, "accuracy 0.87", tells you how often the model is wrong, not where or why. Error analysis is the habit of opening up that number: splitting the evaluation data into slices and computing the metric per slice, listing which classes are confused with which, and reading the worst individual mistakes. It is the fastest way to decide what to do next (more data of one kind, a new feature, a label fix, a separate model), and it often finds problems that no aggregate metric shows: a region where the model is no better than a coin, a class that is never predicted, a batch of wrong labels.

Slice metrics

A slice is a subset defined by a feature value or a bin: region, device, age band, image source, text length. For a metric MM and slice SS with nSn_S examples, compare M(S)M(S) with the overall MM and keep nSn_S in view, since small slices have noisy metrics. The standard error of an accuracy aa measured on nSn_S examples is about

SE(a)≈a(1−a)nS.\text{SE}(a) \approx \sqrt{\frac{a(1 - a)}{n_S}} .

A loan-default data set: in two established regions default depends mainly on income, but in a newer, smaller region it depends mainly on age. One logistic regression on income and age (no region feature) is trained on everything:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(0)
n = 6000
region = rng.choice(["north", "south", "east"], size=n, p=[0.45, 0.45, 0.10])
income = rng.normal(35, 10, n)                         # thousands per year
age = rng.integers(20, 70, n)
z = np.where(region == "east", 0.12 * (age - 45), -0.15 * (income - 35))
default = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
df = pd.DataFrame({"region": region, "income": income, "age": age, "default": default})

train, test = train_test_split(df, test_size=0.5, random_state=0, stratify=df["region"])
model = LogisticRegression().fit(train[["income", "age"]], train["default"])
test = test.assign(pred=model.predict(test[["income", "age"]]))
test = test.assign(correct=(test["pred"] == test["default"]).astype(int))
print(f"overall test accuracy {test['correct'].mean():.3f} on {len(test)} rows")

def slice_table(by):
    t = test.groupby(by, observed=True).agg(n=("correct", "size"), accuracy=("correct", "mean"),
                                            default_rate=("default", "mean"))
    t["se"] = np.sqrt(t["accuracy"] * (1 - t["accuracy"]) / t["n"])
    return t.round(3).to_string()

print(slice_table("region"))
test = test.assign(age_band=pd.cut(test["age"], [19, 35, 50, 70]))
print(slice_table(["region", "age_band"]))
overall test accuracy 0.714 on 3000 rows
           n  accuracy  default_rate     se
region
east     285     0.488         0.505  0.030
north   1362     0.730         0.477  0.012
south   1353     0.746         0.496  0.012
                   n  accuracy  default_rate     se
region age_band
east   (19, 35]   88     0.534         0.148  0.053
       (35, 50]   87     0.448         0.448  0.053
       (50, 70]  110     0.482         0.836  0.048
north  (19, 35]  436     0.722         0.468  0.021
       (35, 50]  414     0.720         0.514  0.022
       (50, 70]  512     0.744         0.455  0.019
south  (19, 35]  391     0.765         0.463  0.021
       (35, 50]  430     0.744         0.516  0.021
       (50, 70]  532     0.733         0.504  0.019

Overall accuracy is 0.714, an unremarkable number. The region table shows the problem at once: north and south are at 0.730 and 0.746, the east at 0.488, a coin flip, with a standard error of 0.030, so this is not noise. The finer table by region and age band shows why: in the east the default rate climbs from 0.148 for the young to 0.836 for the over-50s, a strong age effect the model ignores because it learned the income rule of the large regions. In north and south, accuracy is flat across age bands. Note the cost of finer slices: the east cells have under 110 rows each and standard errors around 0.05.

Confusion pairs

For multiclass problems, the off-diagonal cells of the confusion matrix sorted by size list the mistakes worth looking at first. Logistic regression on the 8 x 8 digit images (half for training, half for testing):

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix

X, y = load_digits(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)).fit(X_tr, y_tr)
pred = model.predict(X_te)
cm = confusion_matrix(y_te, pred)
print(f"test accuracy {np.mean(pred == y_te):.3f}, {int((pred != y_te).sum())} errors out of {len(y_te)}")

off = cm.copy()
np.fill_diagonal(off, 0)
pairs = sorted(((int(off[i, j]), i, j) for i in range(10) for j in range(10) if off[i, j] > 0), reverse=True)
print("most frequent confusions (true -> predicted):")
for count, i, j in pairs[:5]:
    print(f"  {i} -> {j}: {count}")
recall = cm.diagonal() / cm.sum(axis=1)
print("lowest per-class recall:", [(int(c), round(float(recall[c]), 3)) for c in np.argsort(recall)[:3]])
test accuracy 0.963, 33 errors out of 899
most frequent confusions (true -> predicted):
  8 -> 1: 5
  3 -> 8: 3
  6 -> 1: 2
  5 -> 9: 2
  4 -> 1: 2
lowest per-class recall: [(8, 0.931), (5, 0.934), (3, 0.935)]

Accuracy is 0.963, with 33 errors on 899 test images. The biggest single confusion, eights read as ones (5 cases), is worth a look at the images: thin, upright eights in an 8 x 8 grid do resemble ones. Classes 8, 5 and 3 have the lowest recall (0.931 to 0.935). With counts of 2 to 5, the ranking among the smaller pairs is noise, but the list says where to look first.

The worst examples, and label errors

Sort the evaluation examples by their loss and read the top of the list. The worst mistakes are often not model failures at all: mislabelled examples, corrupted inputs, or cases the labelling guide never covered. A simple, effective detector for label errors in training data uses out-of-fold predictions: an example whose given label gets a very low predicted probability from a model that never trained on it is suspicious. Here 5 % of the digit labels are deliberately corrupted, and the detector ranks all 1797 examples:

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import cross_val_predict, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_digits(return_X_y=True)
rng = np.random.default_rng(0)
flipped = rng.choice(len(y), size=90, replace=False)                     # 5 % of the rows
y_noisy = y.copy()
y_noisy[flipped] = (y[flipped] + rng.integers(1, 10, size=90)) % 10      # always a different class

model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
proba = cross_val_predict(model, X, y_noisy, cv=StratifiedKFold(5, shuffle=True, random_state=0),
                          method="predict_proba")
p_given = proba[np.arange(len(y)), y_noisy]          # probability of the label we were given
order = np.argsort(p_given)                          # most suspicious first
is_flipped = np.isin(np.arange(len(y)), flipped)
for k in [20, 50, 90, 150]:
    print(f"top {k:3d} suspects: {int(is_flipped[order[:k]].sum()):3d} are real label errors")
top  20 suspects:  20 are real label errors
top  50 suspects:  50 are real label errors
top  90 suspects:  79 are real label errors
top 150 suspects:  87 are real label errors

The 50 most suspicious examples are all real label errors, and 79 of the 90 corrupted labels are in the top 90. Reviewing the 90 most suspicious rows by hand would fix 88 % of the noise while looking at 5 % of the data. Beyond the 90th suspect the hit rate falls off quickly (only 8 more errors in the next 60): those remaining are genuinely hard digits. This is the idea behind "confident learning" tools such as cleanlab. A detector like this suggests, a person decides: some suspects are correctly labelled but unusual, and they are exactly the examples the model most needs.

A routine for error analysis

  1. Fix the evaluation set (validation, not test) and compute the overall metric with its uncertainty.
  2. Slice by every feature that a person would name as meaningful (source, region, device, time, length, class) and by bins of numeric features. Sort slices by metric and by nS⋅(1−metric)n_S \cdot (1 - \text{metric}), the number of errors they account for.
  3. Read 50 to 100 errors and tag each with a cause (label wrong, input broken, ambiguous, model wrong of type X). Counting tags tells you which fix gives the most.
  4. Act, then re-run the same analysis: did the slice improve, and did others get worse?

Beware of slicing too finely: with 100 slices, some will look bad by chance. Treat a weak slice as a hypothesis and confirm it on fresh data. Tools such as fairness and model-monitoring dashboards automate step 2, and Robustness Testing turns weak slices into regression tests.

Practice

  1. A slice has 40 examples and accuracy 0.80; overall accuracy is 0.88. Is the slice clearly worse?
Answer

Not clearly. SE≈0.8⋅0.2/40≈0.063\text{SE} \approx \sqrt{0.8 \cdot 0.2 / 40} \approx 0.063, so 0.88 is about 1.3 standard errors away. Collect more examples of that slice or check it on another split before acting.

  1. In the loan example, what fix does the slice table suggest?
Answer

Give the model what it needs to treat the east differently: add the region and its interaction with age (or use a tree-based model that can split on region), or train a separate model for the east if there is enough data. Then re-check the east slice, which is only about 10 % of the data.

  1. Why use out-of-fold predictions, not the training predictions, to find label errors?
Answer

A model that trained on an example has partly memorised its (possibly wrong) label, so its probability for that label is inflated. Out-of-fold predictions come from a model that never saw the example.

Test yourself

Why compute metrics per slice?

  1. To make the overall metric higher
  2. Because an aggregate metric can hide a subgroup where the model fails
  3. Because scikit-learn requires it
  4. To reduce training time

A slice with 25 examples has accuracy 0.6. Roughly what is its standard error?

  1. 0.01
  2. 0.05
  3. 0.10
  4. 0.25

Which examples does the label-error detector flag first?

  1. Those with the highest loss on the training predictions
  2. Those whose given label gets the lowest out-of-fold predicted probability
  3. Random examples
  4. The examples of the smallest class

What should error analysis be run on?

  1. The test set, after every change
  2. The validation data, keeping the test set for the final estimate
  3. The training data only
  4. Production data without labels