Chapter 2 · Fairness and Data
Comparing Fairness Goals and Their Limits: Small Samples and Conflicting Metrics
- Page 6 of 22
- 21 min read
On the previous page, Fairness Metrics on Toy Data: Selection Rates and Error Rates in Python, three differences disagreed about the same table. This page asks what a team does next. It learns to read an equalised-odds result, to see why several fairness goals cannot all be met at once, to say how sure it is when a group is small, to refuse a comparison that means nothing, and to write down findings with their limits.
You need Python 3.12, standard library only. Type the blocks in order into one session; they share variables, and the text under a block is its real output.
Honesty convention. Every table is synthetic and labelled
Toy data:; every group, person and number is invented. Results show how a calculation works. They are not evidence about any real system or any real group of people.
What you will learn
- How to read equalised-odds gaps (direction, size and who bears each error) and what a tolerance trades away.
- The difference between calibration or precision parity and error-rate parity, and why they conflict when base rates differ, shown on a worked table.
- How to compare two threshold choices on the same data and report what improves and what gets worse.
- How to give an interval for a rate in a small group, and when to decline a comparison.
- How to write a fairness findings note that separates what was measured, what it cannot show and what is recommended.
The helper file, rebuilt
Compute group metrics with the standard library. Page 5 built rows one by one. Here the data are confusion counts per group, so the helper is shorter and replaces page 5's fair.py (use a new folder): it takes tp (suitable and shortlisted), fn (suitable, missed), fp (unsuitable, shortlisted) and tn. It adds the base rate (the share of a group that is truly suitable) and a wilson function used later. Rates with nothing to divide by stay None, shown as n/a.
# file: fair.py
from math import sqrt
def ratio(top, bottom):
return top / bottom if bottom else None # None = undefined, never 0
def rates(c):
pos, neg, chosen, n = c["tp"] + c["fn"], c["fp"] + c["tn"], c["tp"] + c["fp"], sum(c.values())
return {"n": n, "base": ratio(pos, n), "selection": ratio(chosen, n), "tpr": ratio(c["tp"], pos),
"fpr": ratio(c["fp"], neg), "precision": ratio(c["tp"], chosen)}
def fmt(x, signed=False):
return "n/a" if x is None else f"{x:+.2f}" if signed else f"{x:.2f}"
def show(table, keys):
print(f"{'group':<8}" + "".join(f"{k:>11}" for k in keys))
for g, c in table.items():
r = rates(c)
print(f"{g:<8}" + "".join(f"{r[k] if k == 'n' else fmt(r[k]):>11}" for k in keys))
def gap(table, key, ref="A"):
"""Each group minus the reference group; None if either side is undefined."""
out = {}
for g, c in table.items():
a, b = rates(c)[key], rates(table[ref])[key]
if g != ref:
out[g] = None if None in (a, b) else a - b
return out
def wilson(k, n, z=1.96):
"""Wilson score interval for k successes in n trials (approximate, deterministic)."""
if n == 0:
return None
p = k / n
mid = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return mid - half, mid + halfEqualised odds: reading the result
Examine equalised-odds differences. Equalised odds asks for two things at once: the same true-positive rate (tpr) and the same false-positive rate (fpr) in every group. So you report two gaps, not one, and you read both. First the counts from page 5, which come from the 40 invented applicants.
Toy data: the page 5 counts.
from fair import *
# Toy data: the 40 invented applicants of page 5, as confusion counts
PAGE5 = {"A": {"tp": 9, "fn": 3, "fp": 3, "tn": 9}, "B": {"tp": 3, "fn": 3, "fp": 1, "tn": 9}}
show(PAGE5, ["n", "base", "selection", "tpr", "fpr", "precision"])
tg, fg = gap(PAGE5, "tpr")["B"], gap(PAGE5, "fpr")["B"]
print("tpr gap (B - A):", fmt(tg, True), "| fpr gap (B - A):", fmt(fg, True))
print("largest gap:", fmt(max(abs(tg), abs(fg))), "| gaps point the same way:", (tg < 0) == (fg < 0))group n base selection tpr fpr precision
A 24 0.50 0.50 0.75 0.25 0.75
B 16 0.38 0.25 0.50 0.10 0.75
tpr gap (B - A): -0.25 | fpr gap (B - A): -0.15
largest gap: 0.25 | gaps point the same way: TrueHow to read these two numbers:
| Pattern | What it suggests | Question to ask |
|---|---|---|
| Both gaps negative (as here) | Group B faces a stricter bar at both levels: suitable and unsuitable people are selected less often | Does the score or its cut-off behave differently for B? |
| tpr gap negative, fpr gap positive | B's suitable people are missed more, and B's unsuitable people are selected more: the tool separates B less well | Is the input data weaker for B? |
| One gap near zero, one large | Meeting one half of equalised odds is not enough | Which error does the decision punish more? |
| Both gaps within tolerance | Equalised odds holds on this table, for this label | Is the sample large enough? Is the label trusted? (see below) |
The trade-off is in the tolerance. A tight one (say 0.02) fails almost everything on small groups, because one person moves a rate by 0.1 or more. A loose one (say 0.20) passes real differences. No value is a standard; write the number you chose and why. The Beginner page Fairness and Its Trade-Offs: Inclusion, Accessibility and Language gave the same warning in words.
Calibration against error-rate parity
Distinguish calibration from error-rate parity. The two groups above have the same precision, 0.75, and different tpr. These are different kinds of question (our gloss of the standard definitions; Chouldechova, 2016, applied them to a risk instrument):
| Idea | Question | Looks from the viewpoint of |
|---|---|---|
| Calibration | Does a given score mean the same real chance of being suitable in every group? | The person reading the score |
| Predictive parity | Among those selected, is the share who are suitable the same (equal precision)? | The person reading the shortlist |
| Error-rate parity (equal tpr and fpr) | Among suitable people, is the chance of selection the same? Among unsuitable people, too? | The person being scored |
A recruiter and an applicant can both call their own question "fairness" and both be right. Now a worked table in which the score is calibrated by construction.
Toy data: 160 invented applicants in three score bands, as (people, suitable people) per band.
BANDS = {"A": {"low": (20, 4), "mid": (30, 15), "high": (50, 40)},
"B": {"low": (30, 6), "mid": (20, 10), "high": (10, 8)}}
def at(bands, selected):
"""Confusion counts when exactly the bands in `selected` are shortlisted."""
c = {"tp": 0, "fn": 0, "fp": 0, "tn": 0}
for band, (n, s) in bands.items():
c["tp" if band in selected else "fn"] += s
c["fp" if band in selected else "tn"] += n - s
return c
print("share suitable in each score band")
for band in ("low", "mid", "high"):
print(f"{band:<5}" + "".join(f" {g}: {BANDS[g][band][1]}/{BANDS[g][band][0]} = "
f"{BANDS[g][band][1] / BANDS[g][band][0]:.2f}" for g in BANDS))
T1 = {g: at(b, {"high"}) for g, b in BANDS.items()} # threshold 1: shortlist the high band only
print("\nthreshold T1: shortlist the high band")
show(T1, ["n", "base", "selection", "tpr", "fpr", "precision"])share suitable in each score band
low A: 4/20 = 0.20 B: 6/30 = 0.20
mid A: 15/30 = 0.50 B: 10/20 = 0.50
high A: 40/50 = 0.80 B: 8/10 = 0.80
threshold T1: shortlist the high band
group n base selection tpr fpr precision
A 100 0.59 0.50 0.68 0.24 0.80
B 60 0.40 0.17 0.33 0.06 0.80In every band, the same share of each group is suitable (0.20, 0.50, 0.80): the score is calibrated within groups. The base rates differ, 0.59 for A and 0.40 for B, because B has more people in the low band. Check one cell by hand. In A the high band has 50 people, 40 suitable: tp 40, fp 10. The other 50 hold 4 + 15 = 19 suitable people, who are missed (fn 19), and 31 unsuitable (tn 31). Precision is 0.80 for both groups, yet B's suitable people are shortlisted at 0.33 against A's 0.68, and B's unsuitable at 0.06 against 0.24.
Why metrics conflict, and the role of base rates
Explain why fairness metrics can conflict. Precision, tpr, fpr and the base rate p are tied by one identity: precision = tpr×p / (tpr×p + fpr×(1−p)). If two groups have the same precision and the same tpr but different p, their fpr values cannot be equal. The code solves for the fpr that group B would need.
a, b = rates(T1["A"]), rates(T1["B"])
need = a["tpr"] * b["base"] * (1 - a["precision"]) / (a["precision"] * (1 - b["base"]))
print("precision A, B:", fmt(a["precision"]), fmt(b["precision"]), "| tpr A:", fmt(a["tpr"]))
print("B would need fpr", fmt(need), "to match A's precision and tpr; A's own fpr is", fmt(a["fpr"]))precision A, B: 0.80 0.80 | tpr A: 0.68
B would need fpr 0.11 to match A's precision and tpr; A's own fpr is 0.24Examine how base rates affect comparisons. Equal tpr and equal precision are possible for B only with an fpr of 0.11, less than half of A's 0.24. So with different base rates you must give up at least one goal. Kleinberg, Mullainathan and Raghavan (arXiv 1609.05807) prove that three fairness conditions for probabilistic classification cannot in general all hold at once, except in highly constrained special cases. Chouldechova (arXiv 1610.07524) shows the same tension between predictive parity and equal error rates when prevalence differs. Our toy table is an instance of that tension, not a proof of it. The conflict goes away if base rates are equal or the classifier is perfect (the Medium exercise). To see the base rate at work, add group C with A's band mix.
BANDS["C"] = {"low": (40, 8), "mid": (60, 30), "high": (100, 80)} # same mix as A, twice the size
T1 = {g: at(b, {"high"}) for g, b in BANDS.items()}
show(T1, ["n", "base", "selection", "tpr", "fpr", "precision"])
print("C - A gaps:", {k: fmt(gap(T1, k, "A")["C"], True) for k in ("selection", "tpr", "fpr", "precision")})group n base selection tpr fpr precision
A 100 0.59 0.50 0.68 0.24 0.80
B 60 0.40 0.17 0.33 0.06 0.80
C 200 0.59 0.50 0.68 0.24 0.80
C - A gaps: {'selection': '+0.00', 'tpr': '+0.00', 'fpr': '+0.00', 'precision': '+0.00'}Groups with the same base rate and the same calibrated score show no gaps at all. The disagreement between metrics comes from the base rates, not from the arithmetic. A base-rate difference may itself come from history, from how the label was made, or from who applied; the metrics cannot say which.
Documented case:
Year: 2016.
Reported: ProPublica analysed COMPAS risk scores (a tool made by Northpointe) for defendants in
Broward County, Florida. It reported that defendants who did not reoffend were
labelled higher risk more often if they were Black than if they were white.
Disputed: Northpointe disputed ProPublica's methodology and defended the tool's accuracy.
Lesson: the dispute is a standard example of two reasonable fairness definitions, error rates
and calibration, that cannot both hold when base rates differ. This course does not
say who was right; it shows why the two arguments can both be coherent.Two threshold choices on one dataset
Compare two threshold choices on the same toy dataset. A threshold decides which scores are shortlisted. T1 shortlists the high band only. T2 shortlists the mid and high bands. The data are the same; only the choice changes.
T1 = {g: at(BANDS[g], {"high"}) for g in "AB"}
T2 = {g: at(BANDS[g], {"mid", "high"}) for g in "AB"}
print(f"{'gap B - A':<16}{'T1 high':>9}{'T2 mid+high':>13}")
for k in ("selection", "tpr", "fpr", "precision"):
print(f"{k:<16}{fmt(gap(T1, k)['B'], True):>9}{fmt(gap(T2, k)['B'], True):>13}")
for name, t in (("T1", T1), ("T2", T2)):
read = sum(c["tp"] + c["fp"] for c in t.values())
missed = {g: c["fn"] for g, c in t.items()}
print(name, "CVs a recruiter reads:", read, "| suitable people missed:", missed)gap B - A T1 high T2 mid+high
selection -0.33 -0.30
tpr -0.34 -0.18
fpr -0.19 -0.28
precision +0.00 -0.09
T1 CVs a recruiter reads: 60 | suitable people missed: {'A': 19, 'B': 16}
T2 CVs a recruiter reads: 110 | suitable people missed: {'A': 4, 'B': 6}No threshold wins on every line. T2 narrows the tpr gap (-0.34 to -0.18) and misses far fewer suitable people (10 instead of 35), but it widens the fpr gap (-0.19 to -0.28), opens a precision gap (0.00 to -0.09) and makes the recruiters read 110 CVs instead of 60. T2 is better for the people at risk of being missed and worse for workload; reasonable teams weigh that differently. Using a different threshold for each group would also close some gaps, but whether that is acceptable is a policy and legal question that differs between places and sectors, so ask your legal or privacy owner before trying it.
Small groups: how sure are we?
Measure uncertainty in small groups. B has 6 suitable people on page 5. One different decision moves its tpr by 1/6, about 0.17. This page uses the Wilson score interval: a closed-form, deterministic range for a rate k/n, with no random numbers (a seeded bootstrap is the usual alternative). Its limits: it is an approximation; it assumes the people are independent and drawn from the population you care about; 95% is a convention; and it covers only luck in who is in the sample, not a wrong label or a biased sample.
rows = [("page 5, A tpr", 9, 12), ("page 5, B tpr", 3, 6), ("T1, A tpr", 40, 59), ("T1, B tpr", 8, 24),
("T2, A tpr", 55, 59), ("T2, B tpr", 18, 24)]
for label, k, n in rows:
lo, hi = wilson(k, n)
print(f"{label:<14}{k:>3}/{n:<3} = {k / n:.2f} interval {lo:.2f} to {hi:.2f}")
print("rate 0.50 with more people:", end=" ")
print(", ".join(f"{n // 2}/{n}: {wilson(n // 2, n)[0]:.2f}-{wilson(n // 2, n)[1]:.2f}" for n in (6, 24, 120, 600)))page 5, A tpr 9/12 = 0.75 interval 0.47 to 0.91
page 5, B tpr 3/6 = 0.50 interval 0.19 to 0.81
T1, A tpr 40/59 = 0.68 interval 0.55 to 0.78
T1, B tpr 8/24 = 0.33 interval 0.18 to 0.53
T2, A tpr 55/59 = 0.93 interval 0.84 to 0.97
T2, B tpr 18/24 = 0.75 interval 0.55 to 0.88
rate 0.50 with more people: 3/6: 0.19-0.81, 12/24: 0.31-0.69, 60/120: 0.41-0.59, 300/600: 0.46-0.54The page 5 gap (0.75 against 0.50) sits inside two wide, overlapping intervals (0.47 to 0.91 and 0.19 to 0.81). Overlap is not a statistical test, and it does not show that the groups are equal. It shows that this table cannot separate a real gap from luck. With the larger T1 table the intervals for B (0.18 to 0.53) and A (0.55 to 0.78) do not overlap, and under T2 they overlap only a little (B 0.55 to 0.88, A 0.84 to 0.97). That is a stronger hint that a gap exists, still on invented data.
When a comparison is not meaningful
Identify when a group comparison is not meaningful. Make the refusal a rule that runs before any gap is reported. The minimum below is a choice made for this page, not a standard.
MIN = 10 # a team's choice for this page, not a standard
def usable(c, minimum=MIN):
pos, neg = c["tp"] + c["fn"], c["fp"] + c["tn"]
ok = lambda m, what: "ok" if m >= minimum else f"do not compare ({m} {what})"
return {"tpr": ok(pos, "suitable people"), "fpr": ok(neg, "unsuitable people")}
PAGE5["D"] = {"tp": 0, "fn": 0, "fp": 1, "tn": 2} # the 3-person group of the page 5 Hard exercise
for g, c in PAGE5.items():
print(g, usable(c))A {'tpr': 'ok', 'fpr': 'ok'}
B {'tpr': 'do not compare (6 suitable people)', 'fpr': 'ok'}
D {'tpr': 'do not compare (0 suitable people)', 'fpr': 'do not compare (3 unsuitable people)'}| Situation | Why a comparison misleads | What to do |
|---|---|---|
| Too few people with the outcome | One case swings the rate; the interval is very wide | Report counts and interval; decline the gap |
| Undefined rate (no suitable people) | There is nothing to divide by | Keep n/a; never write 0 |
| Label made differently for the groups | The groups are not measured on the same scale | Fix or document the labelling first |
| Groups defined inconsistently, or overlapping | People may be counted twice or moved between groups | Write the definition; check overlaps |
| Groups face different decisions or jobs | The mix of cases differs, so a gap may reflect that mix | Compare within one decision type |
What toy data cannot establish
Recognise that toy data cannot establish real-world fairness. Everything above was invented, so the only things you learned are how to calculate and how to read. Even with real data, a table describes one dataset, one label and one threshold. To say anything about a real tool you would also need a representative sample, a label you trust, the affected people's views, a check on causes, and an owner who can act on the result.
Writing the findings note
Exercise: write a fairness findings note with limitations. The note is what leaves the analysis desk. It keeps three things apart: what was measured, what the measurement cannot show, and what you recommend.
Template:
Fairness findings note: <feature, decision, date>
1 Question and data decision, groups, label, data source (toy or real), people per group
2 Measured each metric, threshold, counts and interval; numbers only, no verdict words
3 Cannot show causes, label quality, other groups, real-world fairness, legal compliance
4 Uncertainty small groups, wide intervals, rates left as n/a
5 Trade-offs seen what improves and what worsens between the options compared
6 Recommendation decision, conditions, what to collect or check next
7 Owner, review date a named role; the date or event that triggers a re-runExample note (invented scenario, toy data): ShortlistHelper from page 1, two thresholds on 160 invented applicants.
1 Question and data
Does ShortlistHelper's shortlist fall equally on groups A (100 people) and B (60)? Label:
"suitable in a later full review". Toy data: invented counts, one score in three bands.
2 Measured (gaps are B minus A)
T1 shortlist high band: selection -0.33, tpr -0.34, fpr -0.19, precision +0.00.
T2 shortlist mid+high: selection -0.30, tpr -0.18, fpr -0.28, precision -0.09.
tpr for B: T1 8/24 (0.18 to 0.53), T2 18/24 (0.55 to 0.88). Suitable people missed: T1 35, T2 10.
3 Cannot show
Whether any real tool behaves like this; why B is selected less (the score mix differs, so
base rates differ: 0.59 and 0.40); whether the label is fair; results for other groups;
whether either threshold meets a rule.
4 Uncertainty
B has 24 suitable people: the tpr intervals are wide, and no minimum sample size is a standard.
5 Trade-offs seen
T2 misses fewer suitable people but adds 50 CVs to read, widens the fpr gap and opens a
precision gap. No threshold satisfies all four metrics; the score is calibrated within groups,
so with different base rates this is expected.
6 Recommendation
Do not approve either threshold from this table. If a real pilot goes ahead: use the score
only to order CVs, start with T2 because missing suitable people is the harm of concern,
re-measure on real data per group with intervals, and review the label with recruiters.
7 Owner, review date
Head of recruitment (role). Re-run after the pilot or after any change to the score.Notice that section 2 contains only numbers, section 3 says what the numbers cannot do, and the recommendation is conditional and has an owner. It does not say "fair" or "biased". Where reasonable people disagree (T1 against T2) the note records the trade-off and gives the reason for its lean, so a decision-maker can overrule it knowingly. The lean toward T2 is a worked-example recommendation on an invented feature. It is conditional and is not a general rule: a team that weighs recruiter workload more heavily, or doubts the label, could reasonably choose T1 or neither.
Where this shows up at work
Analysts run a table like this before a pilot, after each model or threshold change, and when someone complains. Reviewers ask for the note, not the code. The same helper, with real data, needs a privacy review first for the group column.
Common mistakes
- Reporting one gap and calling it equalised odds. You need both the tpr and the fpr gap.
- Chasing every metric to zero. With different base rates it cannot be done in general; choose and explain.
- Comparing small groups without counts. A rate of 0.50 on 6 people and on 600 people is not the same finding.
- Treating overlapping intervals as proof of equality. They show the table cannot separate the groups.
- A note that says "fair" or "biased". State measurements, limits and a conditional recommendation.
Try it yourself
Use the namespace from this page. The exercises revisit the three-person group from page 5.
- Easy. By hand, for group B under T2, work out tpr, fpr and precision from the band counts (B: low 30 people with 6 suitable, mid 20 with 10, high 10 with 8). Then check with
rates(T2["B"]). - Medium. Build a perfect classifier (it shortlists exactly the suitable people) for A (59 suitable, 41 not) and B (24 suitable, 36 not). Print the metrics. Which goals hold and which fail?
- Hard. Write a findings note, using the template, for the page 5 table (A and B in
PAGE5). Use the intervals above and your own tolerance.
Answers
Easy. Shortlisted: mid and high, so 30 people, of whom 10 + 8 = 18 are suitable: tp 18, fp 12. Not shortlisted: 30 people with 6 suitable: fn 6, tn 24. tpr = 18/24 = 0.75, fpr = 12/36 = 0.33, precision = 18/30 = 0.60. Pass checklist: the three values match the table; each uses its own denominator (suitable people, unsuitable people, shortlisted people). A weak answer uses all 60 people each time.
Medium.
perfect = {"A": {"tp": 59, "fn": 0, "fp": 0, "tn": 41}, "B": {"tp": 24, "fn": 0, "fp": 0, "tn": 36}}
show(perfect, ["base", "selection", "tpr", "fpr", "precision"])group base selection tpr fpr precision
A 0.59 0.59 1.00 0.00 1.00
B 0.40 0.40 1.00 0.00 1.00Equalised odds and predictive parity hold exactly (tpr 1.00, fpr 0.00, precision 1.00); demographic parity fails (selection 0.59 against 0.40) because it follows the base rates. Pass checklist: you state which goals hold and which fail; you link the failure to the base rates; you do not call the result unfair. A weak answer treats the selection gap as an error by the classifier.
Hard. A model note:
1 Question and data Do ShortlistHelper's decisions and errors fall equally on A (24) and B (16)?
Label: suitable in a later review. Toy data from page 5.
2 Measured B minus A: selection -0.25, tpr -0.25, fpr -0.15, precision +0.00.
tpr: A 9/12 (0.47 to 0.91), B 3/6 (0.19 to 0.81). Tolerance chosen: 0.10.
3 Cannot show Causes; label quality; real-world fairness; any legal question.
4 Uncertainty B has 6 suitable people: its tpr gap is inside overlapping intervals and
fails the minimum of 10, so it is reported but not compared.
5 Trade-offs seen Precision is equal while tpr is not; with base rates 0.50 and 0.38 both
cannot be equalised in general.
6 Recommendation Collect more cases for B before any decision; re-run then.
7 Owner, review date Analytics lead (role); re-run when B has 10 or more suitable people.Pass checklist: measured, cannot-show and recommendation are in separate sections; counts and intervals appear; the recommendation is conditional with a named owner; no verdict word appears. A weak note says "the tool is biased against B" or hides the small group.
Summary
- Equalised odds means two gaps; read their direction and size, and write down the tolerance you chose and why.
- Calibration and precision parity ask the reader of a score a question; error-rate parity asks the person scored a different one.
- With different base rates and an imperfect score, the goals conflict in general (Kleinberg et al.; Chouldechova), as the worked table shows.
- Show counts and an interval for small groups, and decline comparisons that are not meaningful.
- Toy data teaches the calculation only; a findings note separates measured, cannot show and recommended.
Next: Data Governance: Purpose, Consent, Minimisation, Quality and Re-Identification turns from measuring outputs to the data behind them: who owns it, what it may be used for, and how long it is kept.

