Back to Tutorials
Machine Learning
Intermediate

Bias in Machine Learning: Measuring What’s Fair

Watch a model fail a group it barely saw, then try to make a loan score fair four different ways, and find out why you can’t have them all.

11 minInteractive: drag, click and try things as you read


A model learns from records of the past: who was hired, who repaid a loan, who needed extra care. If those records are skewed, or simply thin for some people, the model inherits the problem and repeats it at scale, usually without anyone noticing. You find bias by measuring a model’s results group by group, and you can only fix it once you decide which kind of fairness you need, because the usual definitions can’t all hold at once. Here you’ll watch a model fail a group it barely saw, then try to make a score fair in four different ways.

Where bias gets in#

Three routes account for most of the well-known cases.

  • Who is in the data. In 2018, Joy Buolamwini and Timnit Gebru tested three commercial systems that guessed a person’s gender from a photo. They misclassified darker-skinned women up to 34.7% of the time, and lighter-skinned men at most 0.8%. Two widely used face datasets they examined were 79.6% and 86.2% lighter-skinned.
  • What the labels really measure. A 2019 study in Science by Ziad Obermeyer and colleagues looked at a widely used algorithm that picked US patients for extra care. It predicted future health costs, as a stand-in for health needs. Because less had been spent on Black patients with the same needs, the algorithm rated them as healthier than equally sick white patients. The authors estimated that fixing this would raise the share of Black patients flagged for extra help from 17.7% to 46.5%.
  • Proxies. In 2018 Reuters reported that Amazon had scrapped an experimental tool for scoring job applicants. It had learned from ten years of applications, mostly from men, and marked down CVs containing the word “women’s”, as in “women’s chess club captain”. Amazon edited out those terms, but couldn’t be sure the model wouldn’t find other stand-ins. Deleting a sensitive column doesn’t delete the other columns that reveal it.

Averages hide groups#

Here’s the first route in miniature. Two made-up groups, A and B, and a model that says yes or no about each person from two measurements. In B the right answer follows a different pattern from A’s. The model is k-nearest neighbours: for each new person it finds the 15 most similar people in its training data and goes with the majority. It only learns B’s pattern if it has seen enough of B.

Predict first

The training data is 1,000 people, and only 10 are from group B. Overall, the model is right 86% of the time. How often is it right about people in group B?

Try it
1% (10 people)

ABfilled: yes, hollow: nowhere the model says yes

Accuracy on 1,000 new people from each group

Group A91%
Group B48%
Everyone (90% A, 10% B)86%

The dashed line is 50%: a coin flip.

With only 10 people from group B to learn from, the model applies group A’s pattern to everyone and gets B right 48% of the time, no better than guessing. Yet overall accuracy is still 86%.

Made-up people and a k-nearest-neighbours model, trained and tested in your browser. The test uses 1,000 new people from each group; “everyone” weights them the way the model would meet them, 9 in 10 from A.

With 10 people from B in the training data, the model is right about 91% of A and 48% of B, and 86% overall. Give it 20 and B climbs to 73%; at 100, the same 1 in 10 it meets in use, 84%. With an even split, A and B both land around 90%. Meanwhile, from 2% upwards, the overall figure sits between 89% and 90%. It barely moves while B’s accuracy changes by 16 points. An overall score can look fine while one group gets a far worse model, so always report results group by group.

Gender Shades found the largest errors where two groups intersect, darker skin and female, which neither a gender breakdown nor a skin-type breakdown alone would show as starkly. Check combinations too, wherever the numbers allow.

What does “fair” mean?#

Now a score that is accurate in both groups. A lender’s model gives each applicant a score: the chance they’ll repay. It’s calibrated: of everyone scored 0.7, 70% repay, whichever group they’re in. The difference is in the history: in this data 59% of group A repay, against 40% of group B. Anyone at or above a threshold is approved. Four common definitions of a fair decision, each with its own name:

  • Demographic parity: both groups are approved at the same rate.
  • Equal opportunity: among people who would repay, both groups are approved at the same rate. Add the same for people who wouldn’t repay, and it’s called equalised odds.
  • Predictive parity: among people approved, both groups repay at the same rate, so an approval means the same thing for everyone.

Predict first

You can set a different threshold for each group. Is there a pair of thresholds that makes all four measures equal?

Try it
0.50
0.50

Approved

gap 49 points

A
74%
B
25%

Equal here: equal approval rates (demographic parity)

Approved, of those who would repay

gap 46 points

A
82%
B
36%

Equal here: equal opportunity

Approved, of those who wouldn’t

gap 45 points

A
62%
B
18%

Equal here: with the row above: equalised odds

Repay, of those approved

gap 7 points

A
65%
B
58%

Equal here: predictive parity

None of the four rows match. Use the buttons to make one of them equal, and watch the others.

10,000 made-up applicants, 5,000 per group, each with a score that is their true chance of repaying. Every number is counted live from those applicants. Rows count as equal when they’re within 2 points.

With one threshold of 0.5 for everyone, 74% of group A is approved and 25% of group B. Among people who would repay, 82% of A get a loan and 36% of B. Matching approval rates (B’s threshold at 0.295) leaves only 46% of approved B applicants repaying, against 65% in A. Matching the chance for people who’d repay (0.315) also evens out the row for people who wouldn’t, but approved B applicants still repay less often, 47% to 65%. Matching repayment among the approved (0.625) approves just 7% of B.

This is a theorem, not a quirk of the example. Jon Kleinberg, Sendhil Mullainathan and Manish Raghavan proved in 2016, and Alexandra Chouldechova independently in 2017, that when base rates differ, a score that isn’t perfect can’t be calibrated and also give both groups the same error rates. Choosing a fairness definition is a decision about values, and no amount of engineering removes the choice.

That’s exactly the argument over COMPAS, a tool used in US courts to score how likely defendants are to reoffend. In 2016 ProPublica found that among defendants who did not reoffend, 44.9% of Black defendants had been labelled higher risk, against 23.5% of white defendants. The tool’s maker and several researchers replied that the scores were calibrated: a given score meant about the same chance of rearrest for either group. Both were right about the numbers, and the recorded reoffending rates differed between the groups, so both kinds of fairness could not hold at once.

What you can do#

  • Measure by group, and by combination of groups. Accuracy, error rates and approval rates, before launch and again in use.
  • Fix the data where you can. Collect more examples from under-represented groups, as the first figure showed. Check that labels measure what you mean: the health algorithm’s makers reduced its bias by predicting health as well as cost.
  • Hunt for proxies. Postcodes, names, schools and gaps in work history can stand in for protected characteristics. SHAP shows which inputs a model leans on.
  • Adjust deliberately. Group-specific thresholds, as in the figure, or training methods that trade a little accuracy for a chosen fairness measure. Libraries such as Fairlearn and AIF360 implement both.
  • Document it. Model cards, proposed by Margaret Mitchell and colleagues in 2019, record what a model is for, how it was evaluated and how it performs for different groups.

In code#

Fairlearn’s MetricFrame computes any metric group by group (pip install fairlearn scikit-learn). This is the figure’s set-up with one threshold, drawn with different random applicants, so the numbers differ by a point or two:

import numpy as np
from fairlearn.metrics import MetricFrame, false_positive_rate, selection_rate, true_positive_rate
from sklearn.metrics import precision_score

rng = np.random.default_rng(0)
group = np.repeat(["A", "B"], 5000)
score = np.concatenate([rng.beta(6, 4, 5000), rng.beta(4, 6, 5000)])  # chance each person repays
repays = rng.random(10_000) < score                                    # what actually happens
approved = score >= 0.5                                                # one threshold for everyone

frame = MetricFrame(
    metrics={"approved": selection_rate, "approved if would repay": true_positive_rate,
             "approved if wouldn't": false_positive_rate, "repay if approved": precision_score},
    y_true=repays, y_pred=approved, sensitive_features=group,
)
print(frame.by_group.round(2).T)
print(frame.difference().round(2))
# sensitive_feature_0         A     B
# approved                 0.75  0.25
# approved if would repay  0.84  0.37
# approved if wouldn't     0.62  0.18
# repay if approved        0.68  0.58
# approved                   0.50
# approved if would repay    0.47
# approved if wouldn't       0.44
# repay if approved          0.10
# dtype: float64

difference() gives the gap between the groups for each measure. Swap in your own model’s predictions and your own groups; the hard part is deciding which gaps you must close.

What to remember

  • Bias gets in through who is in the data, what the labels really measure, and inputs that act as proxies for group membership.
  • Overall accuracy can hide a group the model serves badly; measure every result group by group.
  • When groups’ base rates differ, the common definitions of fairness conflict, so choosing one is a decision about values.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.