Advanced⏱ 28 min⚑ 130 XP🧩 5-question quiz

Bias and Fairness

Find where bias enters AI systems, measure it with standard fairness metrics, understand why the metrics conflict, and choose mitigations across the ML and LLM lifecycle.


Welcome to the Responsible AI module. Up to now the course has asked "does it work, and what does it cost?" From here on we add a third question: who does it work for, and who might it harm? We start with fairness, because it is where good intentions most often meet uncomfortable mathematics.

In 2018 the "Gender Shades" study by Joy Buolamwini and Timnit Gebru evaluated commercial facial analysis systems and found far higher error rates for darker-skinned women than for lighter-skinned men. Nobody had designed the systems to discriminate. The gap came from data, design and evaluation choices that nobody had looked at closely. That is the usual shape of AI bias: no villain in the code, just a pile of unexamined decisions. This lesson gives you tools to find those decisions, measure what they do, and choose what to do about them.

Where bias comes from

Suresh and Guttag (2021) mapped where harms enter the machine learning lifecycle. Here is a condensed version:

SourceWhat happensExample
Historical biasData accurately reflects an unjust worldPast lending decisions that disadvantaged certain neighbourhoods
Representation biasSome groups are under-sampledSpeech data mostly from one accent; images mostly from a few countries
Measurement biasThe label or feature is a flawed proxyArrests as a proxy for crime; health spending as a proxy for health need
Aggregation biasOne model for groups with different patternsA single clinical threshold that works poorly for a subgroup
Evaluation biasBenchmarks don't represent deployment usersTesting only on majority-group data
Deployment biasSystem used differently than intendedA risk score built to offer support, used to punish

Measurement bias deserves a closer look. Obermeyer et al. (2019) studied a widely used healthcare algorithm that predicted health care costs as a stand-in for health needs. Less money had historically been spent on Black patients with the same level of need, so the algorithm underestimated their needs. The architecture was fine. The label was the problem, and no amount of model tuning would have fixed it.

Rendering diagram…

The diagram shows that bias can enter at every stage, and that deployed decisions feed back into the world that produces the next round of data. A predictive policing system that sends more patrols to an area records more incidents there, which "confirms" the prediction.

Bias in language models

LLMs add some failure modes of their own:

  • Stereotyped associations in generated text, for example defaulting to "he" for engineers and "she" for nurses.
  • Uneven quality across languages and dialects. Models are usually strongest in high-resource languages, and quality can drop sharply for dialects such as African American English or for low-resource languages.
  • Representational harms: erasure, demeaning portrayals, or treating one culture's norms as the default.
  • Allocational harms in pipelines. Once an LLM screens resumes, ranks loan applications or triages support tickets, it makes or shapes decisions, and every classic fairness question applies again.

Measuring fairness

To measure fairness you need groups (often protected attributes such as sex, race, age or disability) and a criterion. For a binary classifier with prediction Y^\hat{Y}, true label YY and group AA, the common criteria are:

  • Demographic parity: P(Y^=1∣A=a)P(\hat{Y}=1 \mid A=a) is equal across groups. Selection rates match.
  • Equal opportunity (Hardt, Price and Srebro, 2016): true positive rates P(Y^=1∣Y=1,A=a)P(\hat{Y}=1 \mid Y=1, A=a) match. Qualified people are equally likely to be selected.
  • Equalized odds: true positive and false positive rates, P(Y^=1∣Y=0,A=a)P(\hat{Y}=1 \mid Y=0, A=a), both match.
  • Predictive parity: precision P(Y=1∣Y^=1,A=a)P(Y=1 \mid \hat{Y}=1, A=a) matches. A positive prediction means the same thing for every group.
  • Calibration within groups (for a score SS): P(Y=1∣S=s,A=a)=sP(Y=1 \mid S=s, A=a) = s for every group. Among people given a score of 0.7, 70% have the outcome, whatever their group.

These fall into three families that Barocas, Hardt and Narayanan call independence (Y^\hat{Y} independent of AA: demographic parity), separation (Y^\hat{Y} independent of AA given YY: equalized odds) and sufficiency (YY independent of AA given the score: calibration). Outside degenerate cases, no two of the three can hold at once when base rates differ across groups.

Why you can't have them all

Here is the key equation. For any group, write the base rate p=P(Y=1)p = P(Y=1). Using only the definitions of TPR, FPR and PPV, Chouldechova (2017) showed:

FPR=p1βˆ’pβ‹…1βˆ’PPVPPVβ‹…TPR\mathrm{FPR} = \frac{p}{1-p} \cdot \frac{1-\mathrm{PPV}}{\mathrm{PPV}} \cdot \mathrm{TPR}

The derivation is three lines of counting, and worth doing once. In a group of NN people the true positives are TP=TPRβ‹…pN\mathrm{TP} = \mathrm{TPR}\cdot pN. Precision is PPV=TP/(TP+FP)\mathrm{PPV} = \mathrm{TP}/(\mathrm{TP}+\mathrm{FP}), so FP=TP (1βˆ’PPV)/PPV\mathrm{FP} = \mathrm{TP}\,(1-\mathrm{PPV})/\mathrm{PPV}. Dividing by the number of negatives, (1βˆ’p)N(1-p)N, gives the identity. No assumption about the model or data went in.

Read it carefully. If two groups have different base rates pp, and you force PPV and TPR to be equal across them, then FPR must differ. Kleinberg, Mullainathan and Raghavan (2016) proved the related result for calibrated scores: calibration and balanced error rates can't all hold at once except when base rates are equal or the predictor is perfect.

Worked example. Group A has base rate 0.5, group B has 0.2. Suppose both get PPV = 0.8 and TPR = 0.8.

  • Group A: FPR=0.50.5Γ—0.20.8Γ—0.8=0.20\mathrm{FPR} = \tfrac{0.5}{0.5} \times \tfrac{0.2}{0.8} \times 0.8 = 0.20
  • Group B: FPR=0.20.8Γ—0.20.8Γ—0.8=0.05\mathrm{FPR} = \tfrac{0.2}{0.8} \times \tfrac{0.2}{0.8} \times 0.8 = 0.05

A negative person in group A is four times as likely to be wrongly flagged. To equalize FPR you would have to give up equal precision or equal TPR. This is not a software limitation. It is arithmetic.

Note: A common misreading is "fair ML is impossible." The theorems are narrower: when base rates differ and prediction is imperfect, these particular criteria cannot all hold together. You can still satisfy any one of them, and making the predictor more accurate for the worse-served group (better data, better features) usually shrinks all the gaps at once, moving you towards the "perfect predictor" escape hatch.

So there is no single "fair" metric. Choosing one is a value judgment about which errors do the most harm in your context. In pretrial risk assessment, a false positive can mean someone is jailed. In cancer screening, a false negative can mean a missed diagnosis. Make the choice explicitly, with the people affected, and write it down.

Computing the metrics

Let's measure these on synthetic data where group 1 has a lower base rate and noisier scores, as it might if it were under-represented in training data:

import numpy as np

rng = np.random.default_rng(7)
n = 20_000
group = rng.integers(0, 2, n)                    # two groups, 0 and 1
base_rate = np.where(group == 0, 0.50, 0.30)     # different base rates
y = rng.random(n) < base_rate
# Scores are noisier for group 1 (e.g. less or worse training data)
noise = np.where(group == 0, 0.15, 0.25)
score = np.clip(0.25 + 0.5 * y + rng.normal(0, noise), 0, 1)

def metrics(yhat, m):
    tp = (yhat & y & m).sum(); fp = (yhat & ~y & m).sum()
    fn = (~yhat & y & m).sum(); tn = (~yhat & ~y & m).sum()
    return {"base": y[m].mean(), "sel": yhat[m].mean(),
            "TPR": tp / (tp + fn), "FPR": fp / (fp + tn),
            "PPV": tp / (tp + fp), "acc": (tp + tn) / m.sum()}

def report(thresholds):
    yhat = score >= np.where(group == 0, thresholds[0], thresholds[1])
    for g in (0, 1):
        r = metrics(yhat, group == g)
        print(f"group {g}: " + "  ".join(f"{k}={v:.2f}" for k, v in r.items()))
    return yhat

print("One threshold (0.5) for everyone")
yhat = report((0.5, 0.5))

# Check Chouldechova's identity: FPR = p/(1-p) * (1-PPV)/PPV * TPR
for g in (0, 1):
    r = metrics(yhat, group == g)
    p = r["base"]
    implied = p / (1 - p) * (1 - r["PPV"]) / r["PPV"] * r["TPR"]
    print(f"group {g}: measured FPR={r['FPR']:.3f}  implied={implied:.3f}")

You should see group 1 with a false positive rate around 0.16 against 0.04 for group 0, lower precision and lower accuracy, even though everyone faces the same threshold. The identity check matches to three decimals. Treating everyone "the same" in the mechanics does not produce equal outcomes when the inputs differ.

Note: Fairness metrics need group labels, which raises privacy and consent questions of its own. Collect them with a clear purpose and strong protection, or use well-governed audit datasets. Libraries such as Fairlearn and AIF360 compute these metrics for you, but run them by hand once so you know what they mean.

Mitigation strategies

Mitigations act at three stages:

Pre-processing (data). Collect more representative data, fix flawed labels, reweight or resample under-represented groups, and question proxies. The Obermeyer team's fix was to change the label from cost to direct measures of health. Going back to the data is often the most effective fix.

In-processing (training). Add fairness constraints or penalties to the objective (for example, the reductions approach of Agarwal et al., 2018, used in Fairlearn), train adversarially to strip group information from representations, or use group-aware models where that is appropriate and lawful.

Post-processing (decisions). Adjust thresholds per group to equalize a chosen error rate, as Hardt et al. (2016) proposed. Append this to the script above to equalize true positive rates:

# Post-processing: pick group 1's threshold so its TPR matches group 0's
def rate(g, t, positives=True):
    m = (group == g) & (y if positives else ~y)
    return (score[m] >= t).mean()

target = rate(0, 0.5)
grid = np.linspace(0.2, 0.9, 141)
t1 = min(grid, key=lambda t: abs(rate(1, t) - target))
print(f"\nGroup-1 threshold {t1:.3f} matches TPR {target:.3f}")
report((0.5, t1))

TPRs now match, but group 1's false positive rate jumps to roughly 0.39 and its precision falls to about 0.5. That is the impossibility result showing up in your terminal. Group-specific thresholds may also be legally restricted in some domains, such as credit and employment in some jurisdictions, so bring in legal and domain experts before you ship one.

Mitigation for LLM systems

  • Counterfactual evaluation. Build pairs of inputs that differ only in a group signal (a name, a pronoun, a dialect) and compare outputs or scores. A consistent gap is evidence that the signal changes behaviour.
  • Bias benchmarks. Datasets such as BBQ (Parrish et al., 2022) probe social bias in question answering. Use them as a smoke test, not proof of fairness, since benchmark items rarely match your deployment.
  • Per-language and per-dialect evals for any product serving a multilingual population.
  • Curated fine-tuning data, system prompt guidance, and output monitoring, plus red-teaming with testers from the communities affected.

Pitfalls and misconceptions

  • "We removed the protected attribute, so we're fair." Proxies such as postcode, school and purchase history reconstruct it, and you lose the ability to audit.
  • "Overall accuracy is high, so it's fine." Aggregates hide subgroup failures. Always slice results, including intersections such as age by sex, where the worst gaps often hide.
  • "One metric certifies fairness." The impossibility results guarantee trade-offs. Report several metrics and justify the one you optimize.
  • Small-group noise. A subgroup with 40 examples gives very wide confidence intervals. Report uncertainty (bootstrap it) before claiming a disparity or claiming there is none.

Fairness is socio-technical

Metrics are necessary but not sufficient. Some questions no metric answers:

  • Should this system exist? Some applications are harmful even when accurate.
  • Who defined the groups and labels? The categories themselves can be contested.
  • Who was consulted? People affected by a system often see harms the developers miss.
  • What recourse exists? Can people understand, contest and correct decisions about them?

Good practice combines quantitative audits with stakeholder engagement, documentation (model cards and datasheets, which we return to later in this module), human oversight for high-stakes decisions, and monitoring after deployment, because populations drift.

Hands-on exercise

  1. Run both scripts. Then equalize false positive rates instead of TPRs. Record selection rate, TPR, PPV and accuracy for both groups under all three policies (single threshold, equal TPR, equal FPR) in a table.
  2. Set group 1's noise to 0.35. How do the disparities under a single threshold change? What does this say about the cost of having less or worse data for a group?
  3. Set both base rates to 0.4 and both noise levels to 0.15. Confirm that the disparities largely vanish. This is the "equal base rates" escape hatch from the impossibility theorem.
  4. Pick a real decision system (loan approval, resume screening, content moderation). Write half a page: likely bias sources from the table, which criterion you would prioritize and why, and one mitigation at each stage.

Expected outcome: a table showing that each threshold policy fixes one metric and moves the others, and a written justification of a criterion that names whose errors matter most.

Key takeaways

  • Bias enters through history, representation, measurement, aggregation, evaluation and deployment, and deployed systems can create feedback loops.
  • Common criteria are demographic parity, equal opportunity, equalized odds, predictive parity and calibration.
  • Impossibility results: when base rates differ, calibration or precision and equal error rates can't all hold, as Chouldechova's identity shows. Picking a criterion is a value judgment.
  • Removing protected attributes is not enough because of proxies, and it hides disparities from audits.
  • Mitigate at the data, training and decision stages, and measure the side effects of each.
  • For LLMs, use counterfactual pairs, per-language evals and diverse red-teaming.

Next, we move from unfairness to a broader question: how do we make AI systems pursue the goals we actually intend, and how do we check that they do? That is AI safety and alignment.

Further reading

  • Barocas, Hardt and Narayanan, Fairness and Machine Learning: Limitations and Opportunities (free online textbook, fairmlbook.org).
  • Chouldechova, "Fair prediction with disparate impact: A study of bias in recidivism prediction instruments" (2017), and Kleinberg, Mullainathan and Raghavan, "Inherent Trade-Offs in the Fair Determination of Risk Scores" (2016).
  • Obermeyer et al., "Dissecting racial bias in an algorithm used to manage the health of populations," Science (2019).
  • Fairlearn documentation and user guide: https://fairlearn.org

Save your progress and earn XP

Create a free account to take the quiz, track progress and unlock badges.