Sub topic 11
Looking at errors and slices, not only averages
This chapter assumes you can train a scikit-learn model, compute a metric on a held-out split, and use pandas groupby. Earlier chapters showed how to compare a candidate with a baseline using one overall score. An overall score can hide the places where a model fails.
Why averages mislead
A slice is a subset of the evaluation data defined by a property of the rows, such as region, device type, or a range of a feature. An average is dominated by the largest slices. A model can beat its baseline overall and still be worse than the baseline on a small group. If that group matters to the product, the overall gain is not enough.
The code below builds data where the label rule reverses for a small island group. It then scores a logistic regression on the whole test set and on each slice.
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 = 4000
region = rng.choice(["north", "south", "island"], size=n, p=[0.55, 0.40, 0.05])
x1 = rng.normal(size=n)
x2 = rng.normal(size=n)
# The rule linking features to the label flips sign on the small slice.
signal = np.where(region == "island", -x1, x1) + 0.5 * x2
y = (signal + rng.normal(scale=0.5, size=n) > 0).astype(int)
X = pd.DataFrame({"x1": x1, "x2": x2})
X_train, X_test, y_train, y_test, r_train, r_test = train_test_split(
X, y, region, stratify=y, random_state=0
)
model = LogisticRegression().fit(X_train, y_train)
pred = model.predict(X_test)
results = pd.DataFrame({"region": r_test, "correct": pred == y_test})
print("overall accuracy:", round(results["correct"].mean(), 3))
print(results.groupby("region")["correct"].agg(["mean", "size"]).round(3))The overall accuracy looks respectable. The island row is far lower, and its size column shows it has only a few dozen test rows.
A routine for error analysis
Run the same steps for the baseline and the candidate, using the same split.
- Choose slices before looking at results. Use groups that matter to users or that follow known data differences, such as new versus returning customers. Slicing after the fact on many columns will always turn up some bad-looking group by chance.
- Compare each slice to the baseline on that slice. A slice with a low score may also be hard for the baseline. The useful question is whether the candidate is worse than the baseline there.
- Check slice size. A score on 40 rows has a wide error range. Report the count next to every slice score, and use the noise estimate from the uncertainty chapter before acting on a small gap.
- Read individual errors. Sort the wrong predictions by confidence or by error size and read the top 20 to 50. Look for patterns: mislabeled rows, missing values, duplicated inputs, or one input format the model never saw.
Reading what you find
Each finding points to a different fix. Label errors call for cleaning data, not a bigger model. A slice with very few training examples calls for more data or a rule for that slice. A systematic pattern, like the flipped rule above, may need a feature that identifies the slice. Some errors are acceptable, and that decision belongs in your good-enough criteria. State a minimum score for each slice that matters, not only for the overall metric.
| Finding | Typical response |
|---|---|
| Mislabeled rows among top errors | Correct labels, then re-evaluate |
| Weak slice with few training rows | Collect data or reweight |
| Candidate worse than baseline on a slice | Route that slice to the baseline, or hold back the release |
| Errors near the irreducible-noise level | Stop; no model change will help |
Exercise
A candidate model improves overall balanced accuracy from 0.70 to 0.82 over the baseline. On a slice holding 3% of the data, it scores 0.55 against the baseline's 0.60 on that slice. What two things should you check before deciding, and what are your options?
Show answer
First check how many test rows are in the slice and whether the 0.05 drop is larger than the noise at that sample size, for example with repeated cross-validation. Second, check whether the slice matters to the product requirements. If the drop is real and the slice matters, you can fix the cause (data, features), serve that slice with the baseline, or hold the release. If the drop is within noise or the slice is not critical, record it as a known limit.