Sub topic 9
Uncertainty and small subgroups
This chapter assumes you can compute per-group selection rate, TPR, FPR, and precision from the earlier chapters. It also assumes basic familiarity with confidence intervals and NumPy. It covers how to tell a real gap between groups from sampling noise, and what to do when a group has few examples.
Why a gap is only an estimate
A fairness metric is computed on a finite test set, so it is a sample estimate of the rate you would see on all future data. Two groups with identical true error rates will almost never show identical measured rates. The smaller the group, the larger the random gap you should expect.
The sample size that matters depends on the metric:
| Metric | Computed over | Effective sample size |
|---|---|---|
| Selection rate | All rows in the group | Group size |
| TPR (recall) | Rows with true label 1 | Positives in the group |
| FPR | Rows with true label 0 | Negatives in the group |
| Precision | Rows predicted 1 | Predicted positives in the group |
A group of 500 people with a 4% base rate has only about 20 positives. Its TPR is then estimated from roughly 20 rows, even though the group looks large. Always report the effective sample size next to each metric.
For a rate near 0.5, the 95% margin of error is about 1.96 × √(0.25 / n). A margin of ±0.05 therefore needs about 385 relevant rows per group. A margin of ±0.10 needs about 96. The margin of a gap between two groups is larger than either margin alone, because the variances add.
Confidence intervals for a group rate
The normal approximation (p ± 1.96 √(p(1−p)/n)) fails for small n or for p near 0 or 1. It can even produce intervals outside [0, 1]. The Wilson score interval behaves better and is cheap to compute.
import numpy as np
def wilson(k, n, z=1.96):
"""Wilson score interval for k successes out of n trials."""
if n == 0:
return (float("nan"), float("nan"))
p = k / n
denom = 1 + z**2 / n
center = (p + z**2 / (2 * n)) / denom
half = z * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
return (center - half, center + half)
# TPR for a small group: 14 of 24 positives were found.
# TPR for a large group: 1400 of 2000 positives were found.
print("small group:", wilson(14, 24))
print("large group:", wilson(1400, 2000))Both groups have a TPR near 0.58 to 0.70, but the small group's interval is many times wider. A table of group metrics without these intervals hides that difference.
Confidence intervals for a gap
Fairness criteria are about differences between groups, so you need an interval for the difference. The bootstrap handles this for any metric, including precision and FPR, without a formula. Resample rows within each group, recompute the metric for each resample, and take percentiles of the resulting gaps.
import numpy as np
def tpr(y_true, y_pred):
pos = y_true == 1
return y_pred[pos].mean() if pos.any() else np.nan
def bootstrap_gap(y_true, y_pred, group, metric, g1, g2, n_boot=2000, seed=0):
"""Observed gap metric(g1) - metric(g2) with a 95% percentile bootstrap interval."""
y_true, y_pred, group = map(np.asarray, (y_true, y_pred, group))
rng = np.random.default_rng(seed)
idx1 = np.flatnonzero(group == g1)
idx2 = np.flatnonzero(group == g2)
observed = metric(y_true[idx1], y_pred[idx1]) - metric(y_true[idx2], y_pred[idx2])
gaps = []
for _ in range(n_boot):
s1 = rng.choice(idx1, size=idx1.size, replace=True)
s2 = rng.choice(idx2, size=idx2.size, replace=True)
gaps.append(metric(y_true[s1], y_pred[s1]) - metric(y_true[s2], y_pred[s2]))
gaps = np.array(gaps)
gaps = gaps[~np.isnan(gaps)] # drop resamples where a group had no positives
lo, hi = np.percentile(gaps, [2.5, 97.5])
return observed, lo, hi, gaps.size
# Simulated data: group B is small and its true TPR is 15 points lower.
rng = np.random.default_rng(1)
def simulate(n, base_rate, tpr_true, fpr_true):
y = (rng.random(n) < base_rate).astype(int)
p = np.where(y == 1, tpr_true, fpr_true)
return y, (rng.random(n) < p).astype(int)
ya, pa = simulate(2000, 0.30, 0.70, 0.10)
yb, pb = simulate(80, 0.30, 0.55, 0.10)
y_true = np.concatenate([ya, yb])
y_pred = np.concatenate([pa, pb])
group = np.array(["A"] * 2000 + ["B"] * 80)
obs, lo, hi, used = bootstrap_gap(y_true, y_pred, group, tpr, "A", "B")
print(f"TPR gap A-B = {obs:.3f}, 95% CI [{lo:.3f}, {hi:.3f}], valid resamples = {used}")Group B has only about 24 positives, so the interval is wide. It may include 0 even though the true gap is 0.15. A wide interval that includes 0 does not show the model is fair. It shows the test set cannot tell.
The bootstrap resamples within each group, so group sizes stay fixed. The percentile bootstrap is itself unreliable when a group has only a handful of positives. Treat intervals from groups with fewer than about 20 relevant rows as rough.
Reading the interval against a tolerance
Do not stop at "is the gap significantly different from zero?" With a large enough test set, a trivial gap becomes significant. With a small one, a serious gap does not. Instead, decide a tolerance before looking at results, for example 0.05 for the TPR gap, and compare the interval to it.
The inconclusive branch is common for small groups. Record it as inconclusive in the audit, not as a pass.
Many groups, many metrics, many chances
If you check 6 groups on 4 metrics at the 5% level, you run 24 comparisons. Even with a fair model you should expect about one false alarm. Two practical responses:
- Decide up front which metrics and groups matter for the deployment, based on the harms you identified earlier. Test those as the primary checks.
- For exploratory scans, adjust for multiplicity. The Bonferroni correction divides the significance level by the number of tests, so 0.05 / 24 ≈ 0.002. Equivalently, use wider intervals (about 99.8%). It is conservative but simple.
Treat exploratory findings as leads to confirm on new data, not as conclusions.
Dependence between rows
Bootstrap intervals assume rows are independent. If one person appears several times (repeat applications, multiple visits), or rows cluster by hospital or branch, the true uncertainty is larger than the interval suggests. Resample whole clusters instead of rows: draw person IDs with replacement, then take all rows for each drawn ID.
What to do when a group is too small
- Collect more data. Targeted collection for the small group is the only fix that adds information.
- Report the interval and flag the group. State the effective sample size, such as "TPR 0.58, 95% CI [0.39, 0.75], 24 positives". Mark the result inconclusive instead of omitting the group.
- Merge groups only with a reason. Combining small groups into "other" raises the sample size but can hide a problem that affects one of them. Merge only if the groups are similar in the way that matters for the harm.
- Use a larger evaluation set. If you cannot add data for the group, a cross-validated or repeated evaluation can stabilize estimates. It cannot create information the group's rows do not contain.
- Do not mitigate on noise. Fitting group-specific thresholds to 24 positives can overfit and make the real error rates worse. Check any mitigation on held-out data with intervals.
The table in the first section also shows what to log with every fairness number: the group, the metric, the relevant count, the estimate, and the interval.
Common mistakes
- Reporting group size when the metric depends on positives or negatives only.
- Treating "not significant" as "fair".
- Dropping
nanmetrics silently when a group has no positives in a resample. Count and report how many resamples were dropped, asbootstrap_gapdoes. - Choosing the tolerance after seeing the gap.
- Reusing the same test set many times to tune the model and then to audit it. Audit on data not used for tuning.
Exercise
In a test set, group B has 30 true positives, and the model finds 15 of them (TPR 0.50). Using the normal approximation, what is the approximate 95% margin of error on this TPR, and what does it imply about a measured TPR gap of 0.10 against a group with a precisely estimated TPR of 0.60?
Show answer
The margin is about 1.96 × √(0.5 × 0.5 / 30) = 1.96 × 0.0913 ≈ 0.18, so the interval is roughly 0.32 to 0.68. The comparison group's TPR of 0.60 lies inside it. The 0.10 gap is therefore well within sampling noise, and the result is inconclusive, not evidence of fairness.
Exercise
A group has 2,000 rows but a 2% base rate. You want a TPR estimate with a margin of about ±0.10 near 0.5. Is the group large enough, and why?
Show answer
No. It has about 40 positives (2,000 × 0.02), and TPR uses only positives. A ±0.10 margin needs about 96 positives, so you need roughly 4,800 rows at this base rate, or targeted collection of positive cases.