Sub topic 11
Looking at errors and slices, not only averages
This chapter assumes you can train a scikit-learn classifier, you know precision and recall, and you have read the earlier chapters on metrics, splits and baseline comparison. You should be comfortable with pandas groupby. By the end you will know how to find where a model fails, check whether the failure is real or noise, and feed that finding into a good-enough decision.
Why one number hides the problem
A single test score averages over every example. If the model is excellent on 90% of the data and poor on 10%, the average still looks fine. The poor 10% may be the part that matters most to users, to regulators, or to the business.
Comparing to a baseline has the same blind spot. Suppose a candidate beats the baseline by 4 points overall. That gain could come from one easy segment while the model is worse than the baseline on another. Averages cannot show this. Errors and slices can.
A slice is a subset of the evaluation data defined by a rule, such as device == "mobile", age < 25, or text length > 500 characters. Slice evaluation means computing your chosen metric separately on each slice. Error analysis means reading individual wrong predictions to find patterns.
Step 1: compute metrics per slice
The example below builds data where a minority segment ("store") follows a different rule from the others. A single linear model fits the majority and fails the minority.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 4000
segment = rng.choice(["web", "mobile", "store"], size=n, p=[0.6, 0.3, 0.1])
x1 = rng.normal(size=n)
x2 = rng.normal(size=n)
# The "store" segment follows a different rule from the other two.
signal = np.where(segment == "store", -x1 + x2, x1 + x2)
y = (signal + rng.normal(scale=0.7, size=n) > 1.0).astype(int)
X = pd.DataFrame({"x1": x1, "x2": x2})
X_train, X_test, y_train, y_test, seg_train, seg_test = train_test_split(
X, y, segment, stratify=y, random_state=0
)
model = LogisticRegression().fit(X_train, y_train)
report_df = pd.DataFrame(
{"segment": seg_test, "y_true": y_test, "y_pred": model.predict(X_test)}
)
print("overall accuracy:", round(accuracy_score(report_df.y_true, report_df.y_pred), 3))
rows = []
for name, g in report_df.groupby("segment"):
rows.append(
{
"segment": name,
"n": len(g),
"positives": int(g.y_true.sum()),
"precision": precision_score(g.y_true, g.y_pred, zero_division=0),
"recall": recall_score(g.y_true, g.y_pred, zero_division=0),
}
)
print(pd.DataFrame(rows).round(3).to_string(index=False))Expect a high overall accuracy and a "store" row with much lower recall than "web" and "mobile". Exact values depend on the library version. The point is that the overall number looks acceptable while one slice is poor.
Always print the slice size n and the number of positives next to the metric. A recall of 0.40 on 5 positive examples means something very different from 0.40 on 500.
Step 2: check whether a slice gap is real
Small slices give noisy metrics. Before you report that a slice is worse, estimate how much the metric could move from sampling alone. A bootstrap is a simple way to do this. It resamples the slice's predictions with replacement many times and recomputes the metric each time.
import numpy as np
from sklearn.metrics import recall_score
# Reuses report_df from the previous example.
def bootstrap_interval(y_true, y_pred, metric, n_boot=1000, seed=0):
rng = np.random.default_rng(seed)
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
stats = []
for _ in range(n_boot):
idx = rng.integers(0, len(y_true), size=len(y_true))
stats.append(metric(y_true[idx], y_pred[idx], zero_division=0))
return np.percentile(stats, [2.5, 97.5])
for name, g in report_df.groupby("segment"):
low, high = bootstrap_interval(g.y_true, g.y_pred, recall_score)
print(f"{name:7s} recall 95% interval: [{low:.2f}, {high:.2f}]")If the intervals for two slices barely overlap, the gap is probably real. If they overlap heavily, you cannot tell from this test set, and you should collect more data for that slice before acting.
Like the repeated cross-validation standard error from the earlier chapter, this interval is a rough guide. It does not account for the model's own training variance. It only reflects the finite size of the test slice.
Step 3: compare baseline and candidate per slice
The slice view is most valuable when you apply it to both models. For each slice, compute the metric for the baseline and the candidate on the same rows, then look at the difference.
| Slice | Baseline recall | Candidate recall | Difference |
|---|---|---|---|
| web | 0.55 | 0.71 | +0.16 |
| mobile | 0.52 | 0.69 | +0.17 |
| store | 0.50 | 0.38 | -0.12 |
The numbers above are illustrative. They show a pattern you should look for: the candidate wins on the largest slices and loses to a simple baseline on a small one. The overall number would still favor the candidate. Whether that regression is acceptable is a product decision, not a statistical one. What you must not do is ship without having seen it.
Step 4: read the errors
Metrics tell you where the model fails. Reading examples tells you why. A practical routine:
- Collect the false positives and false negatives from the held-out set.
- Sort them by confidence, so the most confidently wrong predictions come first. Those are often label errors or missing features.
- Read at least 30 to 50 examples per error type. Write a short tag for each one, such as "label looks wrong", "feature missing", "rare category", or "ambiguous input".
- Count the tags. The most common tag shows which fix is worth trying first.
errors = report_df[report_df.y_true != report_df.y_pred].copy()
errors["proba"] = model.predict_proba(X_test.loc[errors.index.map(lambda i: 0) if False else slice(None)])[:, 1][: len(errors)] if False else np.nan
print(errors.groupby(["segment", "y_true"]).size())That snippet is more convoluted than it needs to be, so use this version instead. It keeps predicted probabilities in the frame from the start and sorts by confidence.
import numpy as np
import pandas as pd
# Reuses model, X_test, report_df from the first example.
report_df = report_df.reset_index(drop=True)
report_df["proba"] = model.predict_proba(X_test)[:, 1]
errors = report_df[report_df.y_true != report_df.y_pred].copy()
errors["confidence_in_wrong_answer"] = np.where(
errors.y_pred == 1, errors.proba, 1 - errors.proba
)
print(errors.groupby(["segment", "y_true"]).size())
print(errors.sort_values("confidence_in_wrong_answer", ascending=False).head(10))The grouped counts show which segment and error direction dominate. The sorted list gives you the first rows to read by hand.
Choosing which slices to examine
You cannot check every possible slice. Start with these sources:
- Business-relevant groups: customer tiers, regions, product lines, languages.
- Data-quality groups: rows with missing values, rows imputed from defaults, rows from a newly added source.
- Input-property groups: short versus long text, small versus large amounts, rare versus common categories.
- Time groups: older versus recent data, to see drift inside the test set.
- Error-driven groups: any pattern you spotted while reading errors in step 4.
Common mistakes
- Choosing slices after looking at test scores. If you search the test set for the worst slice and then tune on it, the test set is no longer a clean estimate. Do exploratory slicing on validation data and keep the final test set for one confirmation.
- Ignoring slice size. A metric on 8 examples is not evidence. Report
nand an interval, or merge small slices. - Using accuracy per slice when slices have different class balance. Slice-level accuracy can look fine purely because one slice has few positives. Use the same metric you chose for the whole task, such as recall or balanced accuracy.
- Comparing slices across different models on different rows. Evaluate baseline and candidate on identical rows, as in the cross-validation chapter.
- Fixing the metric instead of the model. If a slice is weak, changing the metric to hide it is not an improvement.
- Treating label noise as model error. If the most confident errors look correctly predicted on reading, the labels are wrong. Fixing labels may raise the ceiling more than any model change. This links directly to irreducible error in the ceiling chapter.
Connecting this to good-enough criteria
Slice results turn a vague "good enough" into a concrete rule. Instead of writing only "balanced accuracy at least 0.80", add slice requirements, for example:
- Overall recall at least 0.75, with the lower bound of its interval above the baseline.
- Recall on every slice with at least 100 positives no worse than 0.60.
- No slice where the candidate is more than 0.05 worse than the baseline.
- Known gaps listed in the release notes, each with an owner.
Fix these thresholds before you look at the final test results, using the product requirement and the cost of errors for each group. Then the decision to ship or keep iterating follows from the rule instead of from a judgment made after seeing the numbers.
Summary
Averages answer "how good is the model overall?" Slices and errors answer "where is it bad, and why?" Compute metrics per slice with sizes and intervals. Run the same slices on the baseline and the candidate. Read the most confident errors. Pick slices for reasons you can state, not by searching for bad ones. Write slice requirements into your good-enough criteria.
Exercise
A candidate model improves overall recall from 0.62 to 0.70 over the baseline. On a slice with 12 positive examples, recall drops from 0.58 to 0.42. A teammate says the model is worse on that slice and should not ship. What do you do before deciding, and why?
Show answer
Do not decide from 12 positives. One example changes recall by about 8 points, so the drop equals roughly two examples and may be noise. Compute a bootstrap interval for the slice difference and check whether it excludes zero. If it is inconclusive, collect more data for that slice or merge it with a related one. Read the errors on that slice to see whether there is an explainable cause. Then compare the result with the prespecified good-enough criteria. If the slice matters for the product and the criteria set a minimum for it, hold the release until you have enough data to judge. If it does not matter, record it as a known gap.