Sub topic 6
Slicing results by text properties
An overall score averages over every kind of input. If a model scores 91% accuracy, that number can't show that it scores 98% on short reviews and 70% on long ones. Slicing splits the evaluation set into subgroups defined by a property of the text. It then computes the same metric on each subgroup. This chapter assumes you can compute accuracy, precision, recall and F1, are comfortable with pandas groupby, and have a table of per-example predictions like the one built in the earlier chapter on collecting errors.
What a slice is
A slice is a subset of the evaluation data selected by a rule. The rule can use any property you can compute without the label:
- Length: the number of tokens or characters.
- Lexical features: whether the text contains a negation word, a number, an emoji, or a URL.
- Surface form: all-caps text, missing punctuation, or heavy misspelling.
- Vocabulary: the share of tokens never seen in training.
- Metadata: the source, product category, date, or annotator.
- Gold label: which class the example truly belongs to.
You define slices from hypotheses. Your taxonomy of errors from the previous chapter is the best source of hypotheses. If hand-reading showed that many errors involve sarcasm or negation, build a slice that approximates it. The slice then tells you how widespread the problem is across the whole evaluation set. A hand-read sample can't tell you that.
Computing slice metrics
The basic operation is a groupby over a column that marks slice membership. You need a per-example correct column, which is True when the prediction equals the gold label.
import pandas as pd
df = pd.DataFrame({
"text": [
"good",
"not good at all really",
"the delivery was late but the product itself works well and looks nice",
"bad",
"I expected more from this brand given the price I paid for it",
"fine",
],
"label": ["pos", "neg", "pos", "neg", "neg", "pos"],
"pred": ["pos", "pos", "neg", "neg", "pos", "pos"],
})
df["n_tokens"] = df["text"].str.split().str.len()
df["length_bucket"] = pd.cut(
df["n_tokens"], bins=[0, 3, 8, 1000], labels=["short", "medium", "long"]
)
df["correct"] = df["label"] == df["pred"]
# Accuracy and support per slice; always report the count next to the score.
print(df.groupby("length_bucket", observed=True)["correct"].agg(["mean", "count"]))This prints accuracy 1.0 on 3 short examples, 0.0 on 1 medium example, and 0.0 on 2 long examples. The pattern looks dramatic, but the counts are tiny. Report the count (also called support) with every slice score. A score without a count is not interpretable.
Why `observed=True`
pd.cut produces a categorical column. Without observed=True, groupby also returns empty categories, which show up as NaN rows. In newer pandas versions the default behavior is changing, so passing the argument explicitly keeps results stable across versions.
Reusable slice reports
Once you have several slice columns, wrap the computation in a function. It should show the gap against the overall score and flag slices that are too small to trust.
import pandas as pd
def slice_report(df, column, min_support=30):
"""Accuracy, support and gap versus overall for each value of `column`."""
overall = df["correct"].mean()
out = df.groupby(column, observed=True)["correct"].agg(
accuracy="mean", support="count"
)
out["gap_vs_overall"] = out["accuracy"] - overall
out["enough_support"] = out["support"] >= min_support
return out.sort_values("gap_vs_overall")
df = pd.DataFrame({
"text": [
"not bad", "it is not good", "great", "never again", "love it",
"no complaints", "awful", "works well", "terrible, not worth it", "fine",
],
"label": ["pos", "neg", "pos", "neg", "pos", "pos", "neg", "pos", "neg", "pos"],
"pred": ["neg", "neg", "pos", "neg", "pos", "neg", "neg", "pos", "neg", "pos"],
})
df["correct"] = df["label"] == df["pred"]
df["has_negation"] = df["text"].str.contains(
r"\b(?:not|no|never)\b|n't", case=False, regex=True
)
print(slice_report(df, "has_negation", min_support=3))Sorting by gap puts the weakest slice at the top. The min_support threshold is set low here only because the toy data is small. On a real evaluation set a common starting point is 30 to 50 examples, though that threshold is a rough guide. The next chapter replaces it with proper uncertainty estimates.
Choosing slice definitions
How you cut a property into slices changes what you see.
| Choice | Benefit | Risk |
|---|---|---|
| Fixed bins, such as 0-3, 4-8 and 9+ tokens | Easy to explain and reuse across runs | Bins can be badly unbalanced |
| Quantile bins, such as quartiles of length | Equal support in each slice | Boundaries change when the data changes |
| Binary flags, such as contains negation | Directly tests one hypothesis | Regex rules miss many real cases |
| Metadata categories, such as source or product | Match how the system is used | Many categories mean many tiny slices |
For length, quantile bins from pd.qcut guarantee comparable support. Fixed bins make results comparable between model versions, because the slice definitions don't move. For a regression-tracking setup, prefer fixed definitions you write down once.
A rule-based flag is a proxy. A regex for negation misses "hardly" and "fails to" and matches "no" in "no. 5 model". Read a few examples from each side of the flag before trusting it. If the proxy is poor, the slice metrics describe the proxy rather than the phenomenon.
Slicing by label and by prediction
Slicing by gold label gives per-class recall, which you have already seen in the classification report. Slicing by predicted label gives per-class precision. These are useful, but they select on something the model influences, so they behave differently from slicing on an input property.
Slicing on an input property such as length or source is safe in the following sense. The rule doesn't depend on the model, so the same slice is the same set of examples for every model version. Slicing on predictions changes membership every time you retrain. For comparing versions, use input-based or label-based slices.
Overlapping slices and confounding
Slices are not independent. Long texts are often from one source. Negation is more common in negative reviews. If the model is weak on long texts and also weak on a particular source, you can't yet tell which factor matters.
Two checks help:
- Cross two properties. Group by both length bucket and source. If the gap in length persists within each source, length matters on its own. If it vanishes, the source was the real driver.
- Compare against class balance. A slice with mostly one class can look easy or hard just because of its class prior. Report the label distribution of the slice alongside accuracy, or use macro-F1 within the slice.
import pandas as pd
df = pd.DataFrame({
"source": ["app", "app", "app", "web", "web", "web", "web", "app"],
"length_bucket": ["short", "long", "long", "short", "long", "long", "short", "short"],
"correct": [True, False, False, True, True, False, True, True],
})
print(
df.groupby(["source", "length_bucket"])["correct"]
.agg(accuracy="mean", support="count")
)Each added grouping column divides the data further, and supports shrink fast. With three or four columns you are reading numbers computed from a handful of examples.
Common mistakes
- Searching for slices until something looks bad. If you test 40 slice definitions, a few will show large gaps by chance. Prefer slices motivated by a hypothesis, and treat unexpected findings as leads to verify on fresh data.
- Slicing the training or validation data you tuned on. Use held-out data. A gap on tuned data may be smaller or larger than the gap in deployment.
- Comparing accuracy across slices with different class balance. Add per-class metrics or macro-F1.
- Ignoring support. A slice of 4 examples cannot support a conclusion, whatever its score.
- Treating a slice gap as a cause. The gap says where the model is weak. It does not say why. Go back to the examples in the slice and read them.
Putting slicing to use
Use slicing at two points in the workflow. First, after building an error taxonomy, create a slice for each plausible category and measure how common and how costly it is. Second, before choosing fixes, check which slices carry the largest share of total errors. A slice with a 30-point accuracy gap but 1% of the data matters less than a slice with a 5-point gap and 40% of the data. The share of errors is support * (1 - accuracy) divided by total errors, and you can add it as a column in slice_report. Prioritization later in this tutorial uses exactly this quantity.
Exercise
A model has 88% overall accuracy. Slicing by source gives 95% accuracy on "web" (900 examples) and 60% on "forum" (100 examples). Compute each slice's share of the total errors, and say which slice a fix should target first if both are equally fixable.
Show answer
Web errors are 900 0.05 = 45. Forum errors are 100 0.40 = 40. Total errors are 85, which matches 1000 * 0.12 = 120 only if the numbers are consistent, so check them: 45 + 40 = 85, giving 91.5% accuracy, not 88%. The slices as stated don't match the overall score, so the first step is to find the inconsistency, for example a third source or a miscomputed score. Taking the slice numbers as correct, web holds 45/85 = 53% of errors and forum holds 47%. The web slice has slightly more errors, so on error count alone it is the first target, even though forum has the much lower accuracy.