◆ AI All-in-One

Level 3 In-Depth AI · Safety, Ethics and Society

Bias and Fairness

Machine-learning models learn from data about the past, so they can copy and amplify past unfairness. This chapter shows where bias comes from, how to measure fairness, why the different definitions conflict, and what you can do about it.

Level
●●●●● Easy
Reading
17 min
To learn it well
45 minutes to read, an hour to try the code
↗ Plan a path here

Read first

Supervised Learning

This leads to

—
The full path from zero — 4 concepts before this one
  1. What Is AI?
  2. How Machines Learn
  3. Supervised, Unsupervised and Reinforcement Learning
  4. Supervised Learning
  5. Bias and Fairness

Read them roughly in this order. See it on the concept map →

Why it matters

A supervised model learns to copy the patterns in its training data. That is its whole job. But data about people records the world as it was, including its unfairness. If women were hired less often for engineering jobs in the past, a model trained on past hiring decisions learns that being a woman predicts not being hired. It isn't malicious. It is doing exactly what it was trained to do.

This matters because models now help make decisions that shape lives: who gets a loan, a job interview, extra medical care, bail, or a second look from a fraud team. A biased human makes a few hundred decisions a year. A biased model can make millions, quickly and consistently, behind a screen that looks objective.

Algorithmic bias means a system's outputs systematically disadvantage some group of people, whatever the cause. Fairness is the goal of avoiding that. This chapter covers where bias comes from, how to measure it with numbers, why the obvious definitions of "fair" contradict each other, and what practitioners actually do. The same ideas come back for language models, which absorb the stereotypes in their web-scale training text, and in AI Regulation and Governance, where laws such as the EU AI Act now require bias checks for high-risk systems.

The intuition

Think of a model as an extremely diligent apprentice who learns only by watching. Show it ten years of decisions made by a company, and it will reproduce those decisions faithfully, quirks and prejudices included. It never asks "was this fair?" because nobody gave it that question.

Bias can enter at every stage of building a system, not only in the data:

The world how things are Historical past injustice is in reality Data who is recorded Representation some groups rare or missing Labels what is 'good'? Measurement the label is a flawed proxy Model fit to the data Aggregation one model fits the majority Evaluation good enough? Evaluation test set differs from real users Deployment used on people Deployment new purpose or new population Where bias enters a machine-learning system type of bias: Feedback loop: decisions change the world, which becomes tomorrow's training data e.g. more police patrols where a model predicts crime → more recorded crime there
Fig. 1 The machine-learning pipeline, from the world to deployment, with the kind of bias that can enter at each stage. Decisions made by the deployed system then change the world and feed back into future training data.
  • Historical bias. The world itself is unequal, so even perfectly recorded data reflects that. A model trained on it can be "accurate" and still unfair.
  • Representation bias. Some groups are rare or missing from the data. A face dataset that is mostly light-skinned men gives a model little practice on anyone else.
  • Measurement bias. The label you train on is a flawed stand-in for what you really care about. "Was arrested" is not the same as "committed a crime". "Spent a lot on health care" is not the same as "was sick".
  • Aggregation and learning bias. One model is fitted to everyone, and the training objective rewards getting the majority right. Errors on small groups barely move the average loss.
  • Evaluation bias. The test set doesn't look like the real users, so a model that scores well in the lab fails on people the test never included.
  • Deployment bias. The system is used for a purpose, or on a population, it was never designed for.

On top of these sits the feedback loop: the model's decisions change the world that produces the next round of data. If a policing model sends more patrols to one neighbourhood, more crime is recorded there, which "confirms" the model's prediction and sends still more patrols.

Key idea Bias is not a bug in one line of code. It is a property of the whole system: the data, the labels, the objective, the test and the way the system is used. You have to look for it at every stage, and you have to measure it, because it is usually invisible in the overall accuracy.

Real cases

Three well-documented cases show the main patterns.

COMPAS (2016): what does "fair" mean? COMPAS is a commercial risk-assessment tool used in US courts to estimate how likely a defendant is to reoffend. In May 2016 the newsroom ProPublica analysed scores for more than 7,000 people arrested in Broward County, Florida, in 2013 and 2014. Among defendants who did not reoffend within two years, 44.9% of Black defendants had been labelled higher risk, against 23.5% of white defendants. Among those who did reoffend, 47.7% of white defendants had been labelled lower risk, against 28.0% of Black defendants. The developer, Northpointe (now Equivant), replied that the scores were fair in a different sense: a given score meant roughly the same chance of reoffending whatever the defendant's race. Both sides were right about their own numbers. Researchers soon proved that, in situations like this one, both kinds of fairness cannot hold at once. That result is the heart of this chapter, and we will see why below.

Gender Shades (2018): who is in the data? Joy Buolamwini and Timnit Gebru tested commercial face-analysis systems from IBM, Microsoft and Face++ on a balanced set of faces. For classifying gender, the worst error rate for lighter-skinned men was 0.8%. For darker-skinned women it reached 34.7%. Overall accuracy hid this completely. The study is the textbook example of representation and evaluation bias, and of why you must break results down by subgroup, including combinations such as "darker-skinned and female" (an intersectional analysis).

Amazon's recruiting tool (reported 2018): proxies leak. Reuters reported in October 2018 that Amazon had built a model to rate job applicants' résumés, trained on résumés submitted to the company over ten years, most of them from men. The model learned to penalise résumés containing the word "women's", as in "women's chess club captain", and downgraded graduates of two all-women's colleges. Engineers edited it to ignore those terms, but could not be sure it wouldn't find other proxies, and the project was abandoned. Amazon said the tool was never used by its recruiters as the sole basis for evaluating candidates. The lesson: removing the sensitive column does not remove the information.

A fourth case is worth knowing because it shows measurement bias so clearly. In 2019, Obermeyer and colleagues studied an algorithm used by US hospitals to pick patients for extra care. It predicted future health-care cost as a stand-in for health need. Because less money had historically been spent on Black patients with the same illnesses, the algorithm judged them healthier than they were. The authors estimated that correcting the label would raise the share of Black patients flagged for extra help from 17.7% to 46.5%.

How it works: measuring fairness

To measure fairness you need a protected attribute (also called a sensitive attribute): a characteristic such as sex, race, age or disability that the law or ethics says should not drive the decision. Call it AA, with two groups aa and bb to keep things simple. The model makes a yes/no decision Y^\hat{Y} ("hat Y", the prediction). The true outcome is YY. A fairness metric compares some statistic of the model's behaviour across groups.

There are dozens of fairness metrics, but three families cover most of them.

1. Demographic parity: equal selection rates

Demographic parity (also called statistical parity) asks that each group is selected at the same rate, regardless of the true outcomes:

P(Y^=1∣A=a)=P(Y^=1∣A=b)P(\hat{Y} = 1 \mid A = a) = P(\hat{Y} = 1 \mid A = b)

Read the vertical bar as "given". In words: the chance of a "yes" is the same for group aa as for group bb. In practice you report the difference between the two selection rates, or their ratio. A ratio below 0.8 is the traditional US warning sign of disparate impact, from the "four-fifths rule" in the 1978 US federal guidelines on employment selection.

Demographic parity is simple and doesn't need trustworthy labels. Its weakness is that it ignores whether the people selected were actually qualified. If the groups genuinely differ in the outcome, forcing equal rates means accepting less qualified people in one group or rejecting qualified people in the other.

2. Equalized odds: equal error rates

Equalized odds asks that the model makes mistakes at the same rates for each group. Both the true positive rate (the share of truly positive people who get a "yes") and the false positive rate (the share of truly negative people who wrongly get a "yes") must match:

P(Y^=1∣Y=y,A=a)=P(Y^=1∣Y=y,A=b)for y∈{0,1}P(\hat{Y} = 1 \mid Y = y, A = a) = P(\hat{Y} = 1 \mid Y = y, A = b) \quad \text{for } y \in \{0, 1\}

A weaker version, equal opportunity, asks only for equal true positive rates: qualified people in every group get through at the same rate. ProPublica's criticism of COMPAS was, in effect, that it violated equalized odds: its false positive rates differed by race.

3. Predictive parity: equal meaning of a score

Predictive parity asks that a positive prediction means the same thing in every group: among the people flagged, the same share really are positive.

P(Y=1∣Y^=1,A=a)=P(Y=1∣Y^=1,A=b)P(Y = 1 \mid \hat{Y} = 1, A = a) = P(Y = 1 \mid \hat{Y} = 1, A = b)

This is the precision per group. Its close cousin for scores is calibration within groups: a score of 7 means the same risk for everyone. This was Northpointe's defence of COMPAS.

Why you can't have everything

All three sound reasonable. The problem is that they conflict whenever the groups have different base rates, meaning different true rates of the outcome. Here is a worked example with small numbers.

Group A Group B Group A: 10 of 20 reoffend base rate 50% Group B: 5 of 20 reoffend base rate 25% flagged high-risk (selection rate) 10 of 20 = 50% 5 of 20 = 25% unequal ✗ of flagged, truly reoffend 8 of 10 = 80% 4 of 5 = 80% equal ✓ of reoffenders, flagged (TPR) 8 of 10 = 80% 4 of 5 = 80% equal ✓ of non-reoffenders, flagged (FPR) 2 of 10 = 20% 1 of 15 ≈ 7% unequal ✗ actually reoffended did not reoffend flagged high-risk by the model When base rates differ, a score that is equally accurate for both groups must make false alarms at different rates. You cannot equalise everything at once.
Fig. 2 Two groups of 20 people with different base rates. The model is equally precise (80% of flagged people really reoffend) and equally sensitive (80% of reoffenders are flagged) in both groups, yet its false positive rate is 20% in group A and about 7% in group B, and its selection rates differ too.

Group A has 10 reoffenders out of 20; group B has 5 out of 20. The model flags 10 people in A (8 right, 2 wrong) and 5 people in B (4 right, 1 wrong). Check each metric by hand:

Group A Group B Equal?
Selection rate (demographic parity) 10/20 = 50% 5/20 = 25% no
Precision (predictive parity) 8/10 = 80% 4/5 = 80% yes
True positive rate 8/10 = 80% 4/5 = 80% yes
False positive rate 2/10 = 20% 1/15 ≈ 7% no

Try to fix the false positive rates and the precision breaks; force equal selection rates and the error rates break. This isn't bad luck in the example. In 2016 and 2017, Kleinberg, Mullainathan and Raghavan, and separately Alexandra Chouldechova, proved that calibration and equal error rates cannot all hold at once unless the base rates are equal or the model is perfect. Neither condition holds in any real problem.

Note The impossibility result moves the fairness question from mathematics to values. Someone must decide which kind of error matters more in this setting: falsely labelling an innocent person high-risk, or letting the meaning of a score differ by group. That is a decision for the people affected, the law and the organisation, not something the data scientist should settle alone.

Why "just remove the column" fails

The first idea most people have is to delete the protected attribute from the inputs. This is called fairness through unawareness, and it rarely works. Other features act as a proxy variable: a postcode can stand in for race, a first name or a hobby for sex, a gap in employment for disability or parenthood. A flexible model finds those proxies on its own, as the Amazon tool did. Worse, if you delete the attribute you can no longer measure the disparity. Most practitioners therefore keep the protected attribute available for auditing, even when it is not a model input.

In code

The example below builds a synthetic hiring dataset. True skill is identical across groups, but the historical labels were biased against group B. The protected attribute is never given to the model, yet a proxy feature (think postcode) leaks it. We then compute the fairness metrics by hand.

import numpy as np
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(0)
n = 10_000
group = rng.integers(0, 2, n)                   # 0 = group A, 1 = group B
skill = rng.normal(0, 1, n)                     # what we really care about
# Historical labels: same skill, but group B was hired less often (biased past decisions)
y = (skill + rng.normal(0, 0.5, n) - 0.6 * group > 0).astype(int)
# A feature that leaks group membership (think: postcode)
proxy = group + rng.normal(0, 0.3, n)
X = np.column_stack([skill + rng.normal(0, 0.5, n), proxy])   # note: no 'group' column

model = LogisticRegression().fit(X, y)
pred = model.predict(X)

def rates(g):
    m = group == g
    sel = pred[m].mean()                        # selection rate P(pred=1)
    tpr = pred[m & (y == 1)].mean()             # true positive rate
    fpr = pred[m & (y == 0)].mean()             # false positive rate
    return sel, tpr, fpr

for g, name in [(0, "A"), (1, "B")]:
    sel, tpr, fpr = rates(g)
    print(f"group {name}: selection {sel:.2f}  TPR {tpr:.2f}  FPR {fpr:.2f}")

(sa, ta, fa), (sb, tb, fb) = rates(0), rates(1)
print(f"demographic parity difference: {sa - sb:.2f}")
print(f"disparate impact ratio (B/A):  {sb / sa:.2f}")
print(f"equalized odds gap: TPR {ta - tb:.2f}, FPR {fa - fb:.2f}")
print("weight on proxy feature:", model.coef_[0][1].round(2))

# group A: selection 0.48  TPR 0.77  FPR 0.17
# group B: selection 0.29  TPR 0.68  FPR 0.12
# demographic parity difference: 0.19
# disparate impact ratio (B/A):  0.61
# equalized odds gap: TPR 0.09, FPR 0.05
# weight on proxy feature: -1.11

The model never saw group, yet it learned a large negative weight on the proxy, and its selection-rate ratio of 0.61 is well below the four-fifths line. One common mitigation is post-processing: choose a separate decision threshold for each group so that, say, qualified people pass at the same rate (equal opportunity):

proba = model.predict_proba(X)[:, 1]
for g, name in [(0, "A"), (1, "B")]:
    pos = proba[(group == g) & (y == 1)]
    t = np.quantile(pos, 0.25)                  # 75% of qualified people pass
    sel = (proba[group == g] >= t).mean()
    fpr = (proba[(group == g) & (y == 0)] >= t).mean()
    print(f"group {name}: threshold {t:.2f}  selection {sel:.2f}  FPR {fpr:.2f}")

# group A: threshold 0.53  selection 0.46  FPR 0.16
# group B: threshold 0.43  selection 0.33  FPR 0.15

Now true positive rates are equal by construction and the false positive rates nearly match, but the selection rates still differ, exactly as the impossibility result predicts. Notice too that everything is measured against the biased labels y. If the labels themselves are unfair, "equal error rates" against them can still be unfair. The Fairlearn library does the same in one line: fairlearn.metrics.MetricFrame(metrics=..., y_true=y, y_pred=pred, sensitive_features=group) builds the same per-group table for any metric. (Group-specific thresholds can also be legally sensitive in some jurisdictions and settings, such as US employment, so check before deploying them.)

Mitigation in practice

Technical fixes fall into three places in the pipeline:

  • Pre-processing: fix the data. Collect more examples from under-represented groups, relabel with a better target (the health algorithm's fix was to predict illness, not cost), or reweight examples so groups count equally.
  • In-processing: change the training objective, adding a penalty when a fairness metric is violated, or train with a constraint.
  • Post-processing: adjust the decisions after training, for example with per-group thresholds as above.

The non-technical steps usually matter more:

  • Ask whether the system should exist. Some decisions shouldn't be automated, or shouldn't use certain data at all.
  • Choose the fairness definition deliberately, with the people affected, and write down why.
  • Disaggregate every evaluation. Report accuracy, error rates and calibration per group and per intersection, not just overall.
  • Document the data and model with datasheets and model cards (see AI Regulation and Governance), including known limitations.
  • Monitor after deployment. Populations drift and feedback loops build slowly. See Monitoring and Data Drift.
  • Keep a human route of appeal for people who are wrongly judged.

Bias in language and image models

Large generative models raise the same issues at a larger scale. Word embeddings trained on news text famously completed the analogy "man is to computer programmer as woman is to ..." with "homemaker" (Bolukbasi and colleagues, 2016). Language models absorb stereotypes from web text, and Text-to-Image in Practice systems tend to show stereotyped images for prompts such as "a CEO" or "a nurse". Measuring this is harder than for a yes/no classifier, because there is no single decision to count. Developers use targeted benchmark prompts, red-teaming and post-training (see RLHF and Preference Optimization) to reduce stereotyped outputs, but there is no agreed standard. If you build with these models, test them on your own use case with inputs from the groups you serve. See Evaluating LLM Applications.

Common pitfalls

  • Only reporting overall accuracy. Gender Shades showed that a high average can hide a failure rate 40 times larger in one subgroup.
  • Trusting the labels. If the target is a biased proxy (arrests, cost, past hiring), a model that predicts it perfectly is perfectly biased.
  • Dropping the protected attribute and calling it done. Proxies leak, and you lose the ability to audit.
  • Picking a metric because it's convenient. Each metric encodes a value judgement about which errors matter. Make that judgement on purpose.
  • Small groups, noisy numbers. A false positive rate computed on 30 people is very uncertain. Report confidence intervals (see Statistics: Mean, Variance and Sampling).
  • Forgetting deployment. A fair model at launch can become unfair as the population or its use changes.

Watch out No fairness metric certifies a system as "fair". Passing a test shows only that one particular disparity is small on one particular dataset. Treat fairness metrics as smoke detectors, not as proof of safety.

Where it leads

  • Interpretability and Explainability helps you find why a model treats groups differently, for example by revealing reliance on a proxy feature.
  • AI Regulation and Governance covers the legal side: anti-discrimination law, the EU AI Act's requirements for high-risk systems, and documentation duties.
  • Privacy, Data and Copyright covers the tension between collecting sensitive attributes to audit fairness and protecting people's personal data.
  • AI Alignment asks the broader question of how to make systems pursue what we actually intend, of which fairness is one part.
  • Evaluation Metrics explains precision, recall and the confusion matrix that every fairness metric is built from.

A bit of history

Concern about unfair automated decisions is older than machine learning. US credit-scoring and employment-testing laws of the 1960s and 1970s introduced ideas such as disparate impact and the four-fifths rule. Machine-learning research on fairness grew quickly after about 2010. Dwork and colleagues' "Fairness Through Awareness" (2012) argued that similar individuals should be treated similarly, and that ignoring the protected attribute is not enough. Hardt, Price and Srebro defined equalized odds and equal opportunity in 2016. The same year, ProPublica's COMPAS story brought the debate to the public, and the impossibility results of Kleinberg and colleagues and of Chouldechova followed within months. Buolamwini and Gebru's Gender Shades (2018) and the reporting on Amazon's recruiting tool (2018) made "audit your model by subgroup" standard advice. The ACM FAccT conference (originally FAT*, first held in 2018) is now the main research venue for the field.

Try it

  1. In the code, change - 0.6 * group to - 0.0 * group so the historical labels are unbiased. Do the gaps disappear? What does that tell you about where the bias came from?
  2. Remove the proxy column from X and rerun. How much does the demographic parity difference shrink, and why doesn't it reach zero?
  3. Take the table in the worked example and try to change the model's decisions for group B so that the false positive rate becomes 20%. What happens to its precision?

Hint for 3: group B has 15 non-reoffenders, so a 20% false positive rate means flagging 3 of them. Count how many flagged people now really reoffend.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Group A has 100 applicants and 50 are selected; group B has 100 and 30 are selected. What is the disparate impact ratio (B/A), and does it pass the four-fifths rule?

  2. You delete the race column from a loan model's inputs, but approval rates still differ by race. What is the most likely reason?

  3. Two groups have different base rates. Your model has equal precision and equal true positive rates across groups. What else must be true?

  4. A hospital algorithm predicts future health-care cost to pick patients for extra care, and under-selects Black patients. What kind of bias is this mainly?

  5. A policing model sends more patrols to one area, more crime is recorded there, and the next model sends even more patrols. What is this called?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Fairness and Machine Learning

Barocas, Hardt & Narayanan · Intermediate · Free

A careful treatment of fairness definitions, their limits and their trade-offs.

Tool

Fairlearn

Fairlearn contributors · Intermediate · Free

An open-source Python toolkit for measuring group fairness metrics (demographic parity, equalized odds and more) and mitigating unfairness, with a good user guide on the sociotechnical side.

Article

Machine Bias

Julia Angwin, Jeff Larson, Surya Mattu & Lauren Kirchner (ProPublica) · 2016 · Beginner · Free

The investigation of the COMPAS recidivism score in Broward County, Florida, that started the modern debate on algorithmic fairness.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/society/bias-and-fairness.md