Slice Evaluation and Fairness Checks: Score the Model Group by Group
One overall MAE of $4,181 hides a group the insurance model misses by twice as much. Cut the test rows by smoker, sex, region and age band, check each gap with row counts, bootstrap ranges and 20 re-splits, and write a failure-slice report that says what was measured and nothing more.
What you will learn
- Compute a metric per slice with groupby and compare it with the overall score
- Use row counts, bootstrap ranges and re-splits to tell a real gap from noise
- Build a failure-slice report with a written flag rule
- Describe a bad slice with numbers, without claiming a cause you did not test
Before you start
- Regression Metrics: MAE, RMSE and R-squared
- pandas groupby
One good overall score can hide a group where the model does badly. In this article we check a model group by group: a metric per slice, a failure-slice report, and the row count beside every number.
A class average of 75, and one row failing
Twenty students sit in four rows of five. Three rows scored 90, and the class average comes out at 75. Looks fine. But every student in row four scored 30.
The average looks fine while one whole row is failing. For us, the class average is the overall score, and a row is a slice: a group of test rows that share a value, like smoker = yes.
The same model, and one overall number
The model is the one from Regression Metrics: the insurance data, the same split, the same linear regression, fit on the train rows only. test_table then copies the test rows into one table with the actual bill, the guess and the miss.
"""Train the insurance model, and give back the test rows with misses."""
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
CSV = "data/insurance.csv"
def test_table(seed=42):
df = pd.read_csv(CSV)
X, y = df.drop(columns="charges"), df["charges"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=seed)
pre = ColumnTransformer([
("num", "passthrough", ["age", "bmi", "children"]),
("cat", OneHotEncoder(drop="first"),
["sex", "smoker", "region"])])
model = Pipeline([("pre", pre), ("reg", LinearRegression())])
model.fit(X_train, y_train)
t = X_test.copy()
t["actual"] = y_test
t["pred"] = model.predict(X_test)
t["miss"] = (t["actual"] - t["pred"]).abs()
t["age_band"] = pd.cut(t["age"], [17, 29, 44, 64],
labels=["18-29", "30-44", "45-64"])
return t
if __name__ == "__main__":
t = test_table()
print("test rows", len(t))
print("overall MAE", round(t["miss"].mean()))
test rows 268
overall MAE 4181
The miss is the gap between bill and guess, without the sign. The first person is off by only $126; a smoker a few rows down is off by $7,527. The average of all 268 misses is our score, $4,181, the same number as before. age_band cuts age into three groups so we can slice by it later.
Cut the test rows by one column
slice_report groups the test rows, gives each group its own average miss, and divides it by the overall miss:
import numpy as np
import pandas as pd
MIN_ROWS = 30
FLAG_AT = 1.5
def flag(rows, x_all):
if rows < MIN_ROWS:
return "FEW ROWS"
return "CHECK" if x_all >= FLAG_AT else ""
def slice_report(t, by):
overall = t["miss"].mean()
out = []
for key, g in t.groupby(by, observed=True):
key = key if isinstance(key, tuple) else (key,)
name = " & ".join(f"{c}={v}" for c, v in zip(by, key))
mae = g["miss"].mean()
x_all = mae / overall
bill = g["actual"].mean()
out.append({"slice": name, "rows": len(g), "mae": mae,
"x_all": x_all, "bill": bill, "pct": mae / bill,
"flag": flag(len(g), x_all)})
return pd.DataFrame(out)
python report.py smoker
slice rows MAE x all flag
smoker=no 214 3130 0.75
smoker=yes 54 8348 2.00 CHECK
214 non-smokers with an average miss of $3,130, and 54 smokers at $8,348. The smokers sit at two times the overall miss; the non-smokers at 0.75. Same model, same rows, and each group gets its own score, with the row count right beside it.
Every column is a way to slice
python report.py sex region age_band
slice rows MAE x all flag
sex=female 140 3733 0.89
sex=male 128 4672 1.12
region=northeast 57 3922 0.94
region=northwest 69 3571 0.85
region=southeast 81 5174 1.24
region=southwest 61 3796 0.91
age_band=18-29 87 3845 0.92
age_band=30-44 82 4145 0.99
age_band=45-64 99 4506 1.08
Southeast is the highest, at 1.24 times, but nothing here reaches the flag line. A column with no failing slice is a result too.
A small slice is a noisy slice
How much should we trust a slice with only a few rows? Take the rows of one slice and resample them with replacement 1,000 times. Each resample gives its own average miss; the middle 95% of those averages is the range.
def resample_means(values, n=1000, seed=0):
rng = np.random.default_rng(seed)
return [rng.choice(values, len(values)).mean() for _ in range(n)]
def interval(values, n=1000, seed=0):
return np.percentile(resample_means(values, n, seed), [2.5, 97.5])
python ranges.py
slice rows MAE 95% range
smoker=no 214 3130 2676 to 3626
smoker=yes 54 8348 7729 to 9091
smoker=yes & sex=female 23 8731 7769 to 10304
sex=female 140 3733 3085 to 4404
sex=male 128 4672 3958 to 5356
male minus female: +939, range -28 to +1883
The 54 smokers range from $7,729 to $9,091. The 23 female smokers range much wider, from $7,769 to $10,304. Fewer rows, wider range.
The same works on a gap. Male minus female is $939, but its range runs from -28 to +1,883. Zero is just inside it, so this split alone can't tell you the gap is real.
Is the gap real, or did one split make it?
Another check: split the data 20 other ways, retrain each time, and measure both gaps again.
from model import test_table
smoker_x, sex_gap = [], []
for seed in range(20):
t = test_table(seed)
by_smoker = t.groupby("smoker")["miss"].mean()
by_sex = t.groupby("sex")["miss"].mean()
smoker_x.append(by_smoker["yes"] / t["miss"].mean())
sex_gap.append(by_sex["male"] - by_sex["female"])
# ... then print the counts and ranges (see resplit.py)
20 re-splits, seeds 0 to 19
smoker MAE above overall: 20 of 20
smoker x overall: 1.89 to 2.40
male MAE above female: 14 of 20
male minus female: -707 to +806
The smoker miss is above the overall in every split, between 1.89 and 2.40 times. The sex gap changes side: male is higher in 14 of 20, anywhere from -$707 to +$806. One gap holds; the other doesn't.
The failure-slice report
Now turn all of this into a short report. The flag function above holds two numbers we chose, written down in the code:
- Fewer than
MIN_ROWS = 30rows: flagged FEW ROWS, and it gets no verdict. FLAG_AT = 1.5times the overall miss or more: flagged CHECK.
python report.py --flagged smoker sex region age_band smoker,sex
slice rows MAE x all flag
smoker=yes 54 8348 2.00 CHECK
smoker=yes & sex=female 23 8731 2.09 FEW ROWS
smoker=yes & sex=male 31 8064 1.93 CHECK
Fifteen slices go in (including the four smoker-and-sex combinations), and only three come out. The female smokers have a high miss, but with 23 rows the report refuses to judge them.
The same misses, two readings
python report.py --pct smoker
slice rows MAE x all avg bill % of bill flag
smoker=no 214 3130 0.75 7862 40%
smoker=yes 54 8348 2.00 33204 25% CHECK
In dollars, smokers are missed by more: $8,348 on an average bill of $33,204. As a share of the bill it flips: non-smokers are missed by 40%, smokers by 25%. Neither view is wrong. Pick the one that matches the cost of a mistake, and say which one you used.
A bad slice gets numbers, not a verdict
def describe(row, overall):
if row["flag"] == "FEW ROWS":
return f"{row['slice']}: only {row['rows']} rows, too few to read."
return (f"{row['slice']}: {row['rows']} rows, MAE {row['mae']:.0f}, "
f"{row['x_all']:.1f} times the overall {overall:.0f}.")
python report.py --say smoker sex smoker,sex
smoker=yes: 54 rows, MAE 8348, 2.0 times the overall 4181.
smoker=yes & sex=female: only 23 rows, too few to read.
smoker=yes & sex=male: 31 rows, MAE 8064, 1.9 times the overall 4181.
Put together, the write-up reads like this:
- Smokers: 54 rows, a miss of $8,348, two times the overall, on the same side in 20 of 20 splits. Why? We haven't tested that.
- Sex: no clear gap. $939 on this split, a range that includes zero, and male higher in only 14 of 20 splits. No verdict.
Say what you measured. Don't claim a cause you didn't test. Whether to use the model at all is a decision for the people who own it.
This check shows how the misses differ by group. It doesn't say why.
Common mistakes
- Reporting only the overall score. $4,181 hid a group missed by $8,348.
- Hiding the row count. A slice of 23 rows can swing by thousands of dollars. Always print the count.
- Trusting a gap from one split. The sex gap looked like $939, then changed side across re-splits.
- Moving the flag rule after seeing the results. Choose
MIN_ROWSandFLAG_ATfirst and write them in the code. - Turning a measurement into a cause. "Smokers are missed more" is measured. "Because of X" needs its own test.
Recap
| Check | What it tells you | Here |
|---|---|---|
| Metric per slice | which group the model misses most | smokers 2.00x overall |
| Row count | how much to trust it | female smokers: 23 rows, no verdict |
| Bootstrap range | how far the number could move | sex gap -28 to +1,883 |
| Re-splits | whether the gap survives | smokers 20/20, sex 14/20 |
| Flag rule | which slices deserve a second look | < 30 rows, or >= 1.5x |
Try it yourself
Run python report.py region,age_band. Which slices are too small to read, and what does the report call them?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
Next →Saving and Loading Models with joblib: One Pipeline, One File
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.