Sub topic 12
Running a fairness audit
A fairness audit is a fixed sequence of steps that turns "is this model fair?" into evidence you can review and repeat. This chapter assumes you know the confusion matrix, precision, recall, and false positive rate. It also assumes you can write basic Python with NumPy and pandas, and that you have read the earlier chapters on group metrics and on small subgroups.
What an audit produces
An audit does not return a verdict of "fair" or "unfair". It produces a written record of five things:
- what the model decides and who is affected
- which groups and metrics you examined, and why
- the measured gaps, each with an uncertainty estimate
- the decision you made about each gap
- what you will re-check, and when
Anyone should be able to rerun the audit on a new model version and compare results.
The workflow
1. Scope the decision and harms
Write down what the model decides, who is affected, and what a wrong decision costs. A false positive in fraud screening can freeze a person's account. A false negative in a medical triage model can delay care. The cost determines which error rate matters most.
2. Define groups and slices
List the sensitive attributes you will use. Add the intersections you can support with enough data, such as sex by age band. Record where each attribute comes from, since self-reported, inferred, and missing values behave differently. If you cannot collect an attribute, say so in the record. Do not silently skip the audit for it.
3. Choose metrics and tolerances before you look
Pick metrics from the deployment context, and set the tolerance for each one before computing anything. If you pick the metric after seeing the results, you can pick the one that looks best.
| Situation | Primary metric | Reason |
|---|---|---|
| Benefit is allocated, such as outreach | Selection rate gap (demographic parity) | The harm is unequal access |
| Qualified people may be missed | TPR gap (equal opportunity) | The harm is false negatives |
| Both error types harm people | TPR and FPR gaps (equalized odds) | Both error rates matter |
| Scores drive human decisions | Precision and calibration by group | A score must mean the same thing for each group |
Because these criteria cannot all hold at once (see the chapter on incompatibility), state which one you prioritize and which you will only report.
4. Measure with uncertainty
Compute per-group rates on a held-out set that was not used for training or threshold tuning. Then attach an interval to every gap. A gap of 0.05 measured on 40 people is not the same evidence as a gap of 0.05 measured on 4,000.
5. Decide and mitigate
Compare each gap and its interval with the tolerance from step 3. There are three outcomes:
- The interval lies inside the tolerance. Record a pass.
- The interval lies outside the tolerance. Investigate causes, then consider mitigation.
- The interval is wide and straddles the tolerance. Record the result as inconclusive and plan to collect more data.
6. Document and monitor
Save the numbers, the data version, the model version, and the decisions. Re-run the audit whenever the model, the data, or the population changes.
A runnable audit
The script below builds synthetic predictions where group B has a lower true positive rate and is much smaller than group A. It computes the rates and a bootstrap interval for each gap.
import numpy as np
def group_rates(y_true, y_pred, group):
"""Per-group selection rate, TPR, FPR, and precision for binary labels."""
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
group = np.asarray(group)
out = {}
for g in np.unique(group):
m = group == g
yt, yp = y_true[m], y_pred[m]
out[g] = {
"n": int(m.sum()),
"selection_rate": yp.mean(),
"tpr": yp[yt == 1].mean() if (yt == 1).any() else float("nan"),
"fpr": yp[yt == 0].mean() if (yt == 0).any() else float("nan"),
"precision": yt[yp == 1].mean() if (yp == 1).any() else float("nan"),
}
return out
def gap_interval(y_true, y_pred, group, metric, g1, g2, n_boot=1000, seed=0):
"""95% bootstrap interval for metric(g1) - metric(g2)."""
rng = np.random.default_rng(seed)
y_true, y_pred, group = (np.asarray(a) for a in (y_true, y_pred, group))
n = len(y_true)
gaps = []
for _ in range(n_boot):
idx = rng.integers(0, n, n)
r = group_rates(y_true[idx], y_pred[idx], group[idx])
if g1 in r and g2 in r:
gaps.append(r[g1][metric] - r[g2][metric])
gaps = np.array(gaps)
gaps = gaps[~np.isnan(gaps)]
return np.percentile(gaps, [2.5, 97.5])
# Synthetic held-out data: B is small and has a lower TPR.
rng = np.random.default_rng(42)
group = np.array(["A"] * 2000 + ["B"] * 300)
y_true = (rng.random(len(group)) < 0.3).astype(int)
tpr = np.where(group == "A", 0.75, 0.60)
fpr = np.full(len(group), 0.10)
y_pred = (rng.random(len(group)) < np.where(y_true == 1, tpr, fpr)).astype(int)
rates = group_rates(y_true, y_pred, group)
for g, r in rates.items():
print(g, {k: round(float(v), 3) for k, v in r.items()})
TOLERANCE = 0.05 # fixed before looking at results
for metric in ["selection_rate", "tpr", "fpr", "precision"]:
point = rates["A"][metric] - rates["B"][metric]
lo, hi = gap_interval(y_true, y_pred, group, metric, "A", "B")
if max(abs(lo), abs(hi)) <= TOLERANCE:
status = "pass"
elif min(abs(lo), abs(hi)) > TOLERANCE and lo * hi > 0:
status = "FAIL"
else:
status = "inconclusive"
print(f"{metric:15s} gap={point:+.3f} 95% CI=({lo:+.3f}, {hi:+.3f}) {status}")The decision rule has three branches. "FAIL" requires the whole interval to sit beyond the tolerance on one side. "pass" requires the whole interval to sit inside it. Anything else is "inconclusive", which is an honest result when a group has few examples.
With group B at 300 rows and about 90 positives, the TPR interval is wide. Expect the TPR gap to come out as inconclusive or a marginal failure depending on the seed. That is the typical audit outcome for small groups, and it is a reason to gather more data before drawing a conclusion.
Reading the results
Look at the metrics together. A selection rate gap with no TPR gap usually means the groups have different base rates, so the model may be accurate on both. A TPR gap with a similar FPR means qualified members of one group are being missed more often. A precision gap with equal TPR and FPR is expected when base rates differ, and it is one form of the incompatibility between criteria.
For any failed or inconclusive gap, ask where it could come from:
- Label quality differs by group, for example because past decisions were biased.
- One group is under-represented in training data.
- A feature acts as a proxy for the sensitive attribute.
- A single global threshold fits one group's score distribution better than another's.
Common audit errors
| Error | Consequence | Fix |
|---|---|---|
| Auditing on training data | Gaps look smaller than real ones | Use a held-out set |
| Choosing metrics after seeing results | Cherry-picked conclusions | Fix metrics and tolerances first |
| Reporting gaps without intervals | Noise reads as signal | Bootstrap or use a binomial interval |
| Only single attributes | Intersectional harm is hidden | Add slices where counts allow |
| Auditing once at launch | Drift goes unseen | Re-run on a schedule and on every release |
Recording the audit
Store one record per audit run. At minimum, include the model version, the dataset version and date, the groups with their counts, the metrics and tolerances, the gaps with intervals, the outcome for each, the decisions taken, and the next review date. The next chapters cover mitigation options and how to document and govern changes.
Exercise
Your audit of a loan model shows an equal opportunity gap (TPR) of 0.08 between groups A and B. The 95% bootstrap interval is (-0.04, 0.20), and your tolerance is 0.05. What is the outcome, and what should you do next?
Show answer
The outcome is inconclusive. The interval contains values both inside and outside the tolerance, and it includes zero. Do not report a pass or a fail. Record the result as inconclusive, collect more data for the smaller group (or pool across time periods if that is valid), and re-run the audit. Meanwhile, check the other metrics and the possible causes (labels, representation, proxies, thresholds) for supporting evidence.