Sub topic 7
Telling real slice gaps from noise
This chapter assumes you can compute per-slice accuracy with pandas, as in the slicing chapter, and that you know what a mean and a standard deviation are. The question here is narrower. Once a slice looks worse than the rest, how do you decide whether it is a real weakness or a chance result on a small sample?
Why slice gaps are often noise
Every slice score is an estimate from a finite sample. If a slice has 10 examples and the model gets 7 right, the score is 0.70. Change two predictions and it becomes 0.50 or 0.90. The score is a measurement with an error bar, and that error bar grows as the slice shrinks.
For accuracy, the standard error is about sqrt(p * (1 - p) / n), where p is the observed accuracy and n is the number of examples. A 95% interval is roughly two standard errors on each side. For p = 0.8:
| Examples in slice (n) | Standard error | Approximate 95% half-width |
|---|---|---|
| 10 | 0.126 | ±0.25 |
| 50 | 0.057 | ±0.11 |
| 100 | 0.040 | ±0.08 |
| 400 | 0.020 | ±0.04 |
A slice of 10 examples can easily look 15 points worse than the overall score by chance alone. Two things follow from this. Always report the count next to the score, and never act on a gap until you have estimated its uncertainty.
The working model
Treat each example in a slice as a draw from a larger population of inputs like it. The observed accuracy is one sample mean. The question "is this slice worse?" becomes "if I collected a fresh sample of such inputs, would the gap still show up?"
You can answer this without a formula for every metric by using the bootstrap. Resample the slice's examples with replacement many times, recompute the metric each time, and read off the spread.
Interval for a single slice
The bootstrap for one slice takes only a few lines. The input is a 0/1 array of per-example correctness.
import numpy as np
rng = np.random.default_rng(0)
correct = np.array([1, 1, 0, 1, 0, 1, 1, 0, 1, 1]) # per-example correctness in one slice
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% bootstrap CI=({low:.2f}, {high:.2f})")The observed accuracy is 0.70, but with 10 examples the interval is very wide, spanning roughly 0.4 to 0.9. The data cannot tell you whether this slice is truly weak. Compare that interval to the accuracy of the full test set, and you will usually find that it contains it.
Interval for the gap between two slices
A single interval is not quite what you want. You usually compare two groups, such as short and long texts, and the interesting quantity is the difference. Bootstrap each group separately, subtract, and look at the distribution of differences.
import numpy as np
rng = np.random.default_rng(0)
short = np.array([1] * 45 + [0] * 5) # 50 examples, 90% correct
long_ = np.array([1] * 32 + [0] * 8) # 40 examples, 80% correct
diffs = []
for _ in range(5000):
s = rng.choice(short, size=len(short), replace=True).mean()
l = rng.choice(long_, size=len(long_), replace=True).mean()
diffs.append(s - l)
low, high = np.percentile(diffs, [2.5, 97.5])
observed = short.mean() - long_.mean()
print(f"observed gap={observed:.2f}, 95% CI=({low:.2f}, {high:.2f})")
print("interval excludes zero:", bool(low > 0 or high < 0))The observed gap is 0.10, which looks like a meaningful difference. The interval runs from about -0.05 to 0.25 (exact values vary with the seed), so it includes zero. With 50 and 40 examples, a 10-point gap is consistent with no real difference. Reporting "long texts are 10 points worse" would overstate what you know.
If the interval excludes zero, you have evidence of a real gap. It still does not say why the gap exists, which is the job of the error taxonomy and the error inspection from earlier chapters.
Common errors
Reading the score without the count
A table that shows only the mean invites over-reading. Always show the support, meaning the number of examples, beside the metric, as the slicing chapter's agg(["mean", "count"]) did. Decide a minimum support before looking at results, for example 30 examples, and mark smaller slices as "too small to judge" instead of ranking them.
Testing many slices and keeping the worst
If you slice by length, source, topic, punctuation, presence of negation, and 15 other properties, you are making dozens of comparisons. At a 5% error rate, about one in twenty comparisons will look significant even if the model is uniform. The slice at the bottom of a sorted list is selected for being low, so its gap is biased downward.
Ways to handle this:
- Choose the slices you care about before looking at the numbers, based on hypotheses about the task.
- Treat any slice found by searching as a hypothesis, and confirm it on data not used to find it.
- Use a stricter threshold when you test many slices. A simple option is to divide 0.05 by the number of comparisons (the Bonferroni correction), which makes each interval wider.
Treating examples as independent when they are not
The bootstrap above assumes each example is an independent draw. That fails when several examples come from the same document, user, or template. Ten sentences from one review are not ten independent observations. Resampling them individually gives intervals that are too narrow.
When examples are grouped, resample the groups instead.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({
"doc_id": [1, 1, 1, 2, 2, 3, 3, 3, 3, 4],
"correct": [1, 1, 1, 0, 0, 1, 1, 0, 1, 1],
})
groups = {k: g["correct"].to_numpy() for k, g in df.groupby("doc_id")}
ids = list(groups)
means = []
for _ in range(2000):
chosen = rng.choice(ids, size=len(ids), replace=True)
sample = np.concatenate([groups[i] for i in chosen])
means.append(sample.mean())
low, high = np.percentile(means, [2.5, 97.5])
print(f"accuracy={df['correct'].mean():.2f}, cluster 95% CI=({low:.2f}, {high:.2f})")This cluster bootstrap draws whole documents, so the interval reflects how muchuracy varies between documents. It is usually wider than the per-example version.
Confusing a statistically clear gap with an important one
A large test set can make a 1-point gap statistically clear. That does not make it worth fixing. Ask two separate questions: is the gap real, and is it big enough, and in a frequent enough slice, to matter? The second question belongs to prioritization, which a later chapter covers.
Ignoring overlap between slices
Slices defined by different properties overlap. Short texts may also be the ones from one source, and the source may be the real cause. If two slice gaps share most of their examples, you have found one problem, not two. Check by cross-tabulating the two properties, or by computing the gap for one slice within each value of the other.
Practical checklist
- Fix a minimum support before looking at results.
- Report mean, count, and a bootstrap interval for every slice you discuss.
- Compare slices through the interval of their difference, not by eyeballing two means.
- Use a cluster bootstrap if examples share a document, user, or template.
- Count how many slices you examined, and treat the ones found by searching as hypotheses.
- Read the errors in a flagged slice before concluding anything. A real gap with no readable pattern may be a data artifact.
Exercise
A model scores 0.85 overall. Texts containing emoji score 0.60, based on 8 examples. A teammate proposes retraining with more emoji data. What do you check first, and what would change your mind?
Show answer
First check the uncertainty. With 8 examples the standard error is about sqrt(0.6 * 0.4 / 8) ≈ 0.17, so the 95% interval is roughly ±0.34 and easily includes 0.85. Compute a bootstrap interval for the gap against the other texts. If it includes zero, the evidence is inconclusive, so collect or write more emoji examples (aim for at least 30 to 50) before retraining. Also check whether the 8 examples share a document or source, which would make the effective sample even smaller. Only if the enlarged slice still shows a gap whose interval excludes zero, and reading its errors reveals a pattern, would retraining with emoji data be justified.