A model that is 87% accurate overall can still treat one group of people very differently from another: approving fewer of them, missing more of the qualified ones, or making more mistakes about them. When models help decide who gets a loan, an interview or an offer, those differences land on real people, and in many countries some of them are illegal. Fairness in machine learning starts with a simple habit: never stop at the overall score; break every metric down by group.
The difficult part comes next. There are several reasonable definitions of "fair", and when groups differ in their base rates, no model can satisfy all of them at once. Here a model predicts high income from US census data, and the analysis measures how it treats men and women, tries the obvious fix (removing the sex column), sees why that fails, and weighs what a real fix costs.
What you need first: accuracy, precision, recall and F1, confusion matrix, ROC and AUC, the Adult income random forest project, and error analysis.
Key terms
- Protected attribute: a characteristic such as sex, race or age that decisions shouldn't unfairly depend on.
- Base rate: the share of a group that really is positive; here, the share of women or men who really earn over $50,000.
- Demographic parity: every group is selected at the same rate.
- Equal opportunity: every group's qualified members are found at the same rate: equal recall (true positive rate).
- Proxy: a feature that carries information about a protected attribute, such as "husband" carrying information about sex.
The data and the model
The Adult census data again: 32,561 people from the 1994 US census, and whether they earned over $50,000 a year. Imagine the model is used to decide who receives an offer for a premium financial product: a "yes" is a benefit.
Download the data: adult-income.csv (5.3 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("adult-income.csv").
import zipfile
import urllib.request
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import HistGradientBoostingClassifier
path = Path("adult.zip")
if not path.exists():
urllib.request.urlretrieve("https://archive.ics.uci.edu/static/public/2/adult.zip", path)
columns = ["age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation",
"relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "income"]
with zipfile.ZipFile(path) as z:
adult = pd.read_csv(z.open("adult.data"), header=None, names=columns, na_values="?", skipinitialspace=True)
X = adult.drop(columns="income")
text_cols = X.select_dtypes("object").columns
X[text_cols] = X[text_cols].astype("category")
y = (adult["income"] == ">50K").astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
sex = X_test["sex"].astype(str).to_numpy()
actual = y_test.to_numpy()
print(adult.groupby("sex")["income"].apply(lambda s: (s == ">50K").mean()).round(3))
sex
Female 0.109
Male 0.306
Name: income, dtype: float64
The file has no header row, so the code names the columns, and "?" marks missing values. sex and actual are plain arrays for the test people, used to break results down by group.
Predict first: in this data, a much larger share of men than women earn over $50,000. If a model is equally accurate for both, will it select both groups at the same rate?
Step 1: break every metric down by group
model = HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=0).fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
def group_report(selected, label):
rows = {}
for group in ["Male", "Female"]:
g = sex == group
sel, act = selected[g], actual[g]
rows[group] = {"selected": sel.mean(), "recall": sel[act == 1].mean(),
"false positive rate": sel[act == 0].mean(), "precision": act[sel].mean(),
"base rate": act.mean()}
print(f"{label}: accuracy {np.mean(selected == actual):.3f}")
print(pd.DataFrame(rows).T.round(3))
return pd.DataFrame(rows).T
baseline = group_report(proba >= 0.5, "threshold 0.5 for everyone")
threshold 0.5 for everyone: accuracy 0.871
selected recall false positive rate precision base rate
Male 0.252 0.645 0.078 0.786 0.307
Female 0.084 0.602 0.021 0.775 0.108
selected is True for the people the model says yes to. Within each group: selected is the share who get a yes; recall is the share of real high earners who get a yes; the false positive rate is the share of the rest who get a yes anyway; precision is the share of yeses that are correct.
Overall accuracy is 0.871, and precision is almost the same for both groups: when the model says yes, it's right about 78% of the time for men and for women. But it says yes to 25.2% of men and only 8.4% of women. Part of that gap reflects the data: in the test set, 30.7% of men and 10.8% of women really are high earners. Not all of it, though. Recall is lower for women (0.602 against 0.645): of the women who really are high earners, the model misses a larger share. And men who aren't high earners are wrongly selected almost four times as often as such women (0.078 against 0.021).
Step 2: three definitions of fairness in machine learning
| Definition | Equal across groups | Here | Argument for | Argument against |
|---|---|---|---|---|
| Demographic parity | Share selected | No: 25.2% against 8.4% | Benefits reach every group equally | Ignores that base rates differ |
| Equal opportunity | Recall | Nearly: 0.645 against 0.602 | Qualified people have the same chance | Says nothing about the unqualified |
| Predictive parity | Precision | Yes: 0.786 against 0.775 | A yes means the same for everyone | Can hide very unequal recall |
import matplotlib.pyplot as plt
ax = baseline[["selected", "recall", "false positive rate", "precision"]].T.plot.bar(figsize=(8, 4), rot=0)
ax.set_ylabel("Rate")
ax.set_title("The same model, measured four ways, by group")
plt.show()
.T turns the table so each metric is a group of bars, one bar per sex.
So is this model fair? By predictive parity, yes. By equal opportunity, nearly, with a 4-point gap against women. By demographic parity, far from it. The same predictions, three different verdicts: "fair" is meaningless until you say which definition you mean and why it suits the decision.
See it fail: just remove the column
The most common first idea is "fairness through unawareness": if the model never sees sex, it can't treat people differently by sex. Experiment: retrain without sex, then also without relationship and marital-status, which contain words like "Husband" and "Wife".
for dropped in [["sex"], ["sex", "relationship", "marital-status"]]:
m = HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=0)
m.fit(X_train.drop(columns=dropped), y_train)
group_report(m.predict_proba(X_test.drop(columns=dropped))[:, 1] >= 0.5, "without " + ", ".join(dropped))
without sex: accuracy 0.872
selected recall false positive rate precision base rate
Male 0.252 0.648 0.076 0.790 0.307
Female 0.085 0.602 0.022 0.764 0.108
without sex, relationship, marital-status: accuracy 0.851
selected recall false positive rate precision base rate
Male 0.190 0.522 0.043 0.843 0.307
Female 0.087 0.473 0.041 0.583 0.108
Removing sex changes almost nothing: the selection rates, recall and precision move by less than 0.02. Removing the obvious proxies as well makes things worse: accuracy falls from 0.871 to 0.851, recall falls for both groups (to 0.522 and 0.473), and precision for women drops from 0.775 to 0.583, so a yes now means much less for a woman than for a man. The model, deprived of useful information, guesses more, and its guesses go wrong unevenly.
How much do the other columns know about sex? Train a model to predict it from them:
from sklearn.metrics import roc_auc_score
sex_model = HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=0)
sex_model.fit(X_train.drop(columns="sex"), X_train["sex"] == "Female")
print(f"AUC for predicting sex from the other columns: "
f"{roc_auc_score(X_test['sex'] == 'Female', sex_model.predict_proba(X_test.drop(columns='sex'))[:, 1]):.3f}")
AUC for predicting sex from the other columns: 0.935
An AUC of 0.935: the remaining columns identify a person's sex almost perfectly. relationship alone gives it away for most married people, and occupation and hours worked differ by sex in this data. A model that "doesn't use sex" can still behave very differently by sex. Removing the column mostly removes your ability to measure the problem.
Step 3: a fix, and its price
One direct fix for equal opportunity is a separate threshold per group: lower the bar for the group whose qualified members are being missed. Experiment: keep 0.5 for men and try lower thresholds for women. Predict first: what happens to accuracy, and to precision for women?
for t in [0.5, 0.45, 0.4, 0.3]:
thresholds = np.where(sex == "Female", t, 0.5)
report = group_report(proba >= thresholds, f"threshold {t} for women, 0.5 for men")
threshold 0.5 for women, 0.5 for men: accuracy 0.871
selected recall false positive rate precision base rate
Male 0.252 0.645 0.078 0.786 0.307
Female 0.084 0.602 0.021 0.775 0.108
threshold 0.45 for women, 0.5 for men: accuracy 0.871
selected recall false positive rate precision base rate
Male 0.252 0.645 0.078 0.786 0.307
Female 0.092 0.645 0.026 0.753 0.108
threshold 0.4 for women, 0.5 for men: accuracy 0.871
selected recall false positive rate precision base rate
Male 0.252 0.645 0.078 0.786 0.307
Female 0.100 0.688 0.029 0.738 0.108
threshold 0.3 for women, 0.5 for men: accuracy 0.869
selected recall false positive rate precision base rate
Male 0.252 0.645 0.078 0.786 0.307
Female 0.120 0.745 0.045 0.668 0.108
np.where(sex == "Female", t, 0.5) gives each person their group's threshold, and proba >= thresholds compares element by element.
At a threshold of 0.45 for women, recall becomes exactly equal: 0.645 for both groups. Overall accuracy doesn't change at all (0.871), because only a few borderline predictions change: the share of women selected rises from 8.4% to 9.2%. The price is paid elsewhere: precision for women falls from 0.775 to 0.753, so a yes is slightly less reliable for women than for men, and the false positive rate for women rises from 0.021 to 0.026. Lowering the threshold further, to 0.3, overshoots: women's recall becomes higher than men's, and their precision falls to 0.668. Every threshold trades one kind of equality for another.
Why you can't have everything
When two groups have different base rates, a model that isn't perfect can't give them equal precision, equal recall and equal false positive rates at the same time. This is a mathematical result, not a weakness of this model. With 30.7% of men and 10.8% of women in the test set being high earners, equal recall and equal false positive rates would force precision to differ, and equal precision forces the error rates to differ, as seen above.
So fairness work is a choice, made by people, about which kind of equality matters most for this decision:
- For a benefit (an offer, a loan, a job interview), missing qualified people is the main harm: equal opportunity is often the focus.
- For a burden (a fraud check, extra scrutiny), wrongly flagging innocent people is the main harm: equal false positive rates matter.
- Using a protected attribute in the decision, even to correct bias, may be prohibited by law in some settings, such as credit decisions in many countries. Fairness choices need legal and domain advice, not just code.
A fairness checklist
| Question | How to check |
|---|---|
| Which groups could be treated differently? | List protected attributes, and collect them for evaluation even if the model doesn't use them |
| How does every metric differ by group? | A group report like group_report |
| Which kind of mistake does most harm here? | Ask the people affected and the domain experts |
| Do other features act as proxies? | Try to predict the protected attribute from the rest |
| Is the training data itself biased? | Check how labels were made, and who is under-represented |
| What does a fix cost, and for whom? | Re-run the group report after every change |
Practice
- Without running code: a model selects 20% of group A and 20% of group B, but finds 90% of qualified people in A and 50% in B. Which fairness definition does it satisfy?
Show the answer
Demographic parity, because the selection rates are equal, but not equal opportunity: qualified people in group B are found far less often. Equal selection rates can hide very unequal treatment of qualified people.
- Break the baseline model's results down by
raceinstead ofsex, for the two largest groups.
Show the answer
race = X_test["race"].astype(str).to_numpy()
selected = proba >= 0.5
for group in ["White", "Black"]:
g = race == group
print(f"{group}: selected {selected[g].mean():.3f}, recall {selected[g][actual[g] == 1].mean():.3f}, "
f"base rate {actual[g].mean():.3f}, people {g.sum()}")
White: selected 0.211, recall 0.646, base rate 0.257, people 8386
Black: selected 0.080, recall 0.565, base rate 0.115, people 937
The same pattern appears: 21.1% of white people and 8.0% of Black people are selected, with base rates of 25.7% and 11.5%, and recall is clearly lower for Black people (0.565 against 0.646). Note the sizes: 937 Black people in the test set against 8,386 white people, so the numbers for the smaller group are less certain. Small groups need especially careful checking, because their errors are easy to miss in an overall score.
- Why does removing
sexfrom the features not remove the model's dependence on sex?
Show the answer
Other features carry the same information: relationship says "Husband" or "Wife", and occupation and hours worked differ by sex in this data. The model reconstructs what it needs from these proxies, as the 0.935 AUC for predicting sex from the other columns shows.
- Find the threshold for women that makes their recall closest to men's at 0.5.
Show the answer
male_recall = (proba[(sex == "Male") & (actual == 1)] >= 0.5).mean()
women_pos = proba[(sex == "Female") & (actual == 1)]
candidates = np.round(np.arange(0.30, 0.51, 0.01), 2)
best_t = min(candidates, key=lambda t: abs((women_pos >= t).mean() - male_recall))
print(best_t, round(male_recall, 3), round((women_pos >= best_t).mean(), 3))
0.45 0.645 0.645
A threshold of 0.45 for women gives recall 0.645, matching men's 0.645, the same answer as the experiment found by trying values.
- The training labels come from past decisions made by people, for example past promotions. Why could a perfectly accurate model still be unfair?
Show the answer
It would learn to copy the past decisions exactly, including any bias in them. Accuracy measures agreement with the labels, so if the labels are biased, the most accurate model is the most faithfully biased one. Check how labels were produced before trusting them.
Interview questions
What is the difference between demographic parity and equal opportunity?
Demographic parity requires equal selection rates across groups, regardless of who is qualified. Equal opportunity requires equal true positive rates: qualified members of each group are selected at the same rate. They conflict when base rates differ.
Why doesn't removing a protected attribute make a model fair?
Other features act as proxies for it, so the model can rebuild the same information. Removing it also stops you from measuring or correcting disparities. It's better to keep the attribute for evaluation and decide explicitly how to treat it.
Can a model satisfy all fairness criteria at once?
Not in general. When groups have different base rates and the model isn't perfect, equal precision (predictive parity) and equal error rates (equalised odds) can't both hold. Teams must choose which criterion matters most for the application.
Key takeaways
- Overall accuracy can hide large differences between groups; break every metric down by group.
- Demographic parity, equal opportunity and predictive parity measure different things, and they conflict when base rates differ.
- Removing the protected attribute doesn't help: other features act as proxies, and here they predict sex with AUC 0.935.
- Group thresholds can equalise recall at little cost in overall accuracy, but they change precision, and they may not be allowed.
- Choosing which kind of fairness matters is a decision for people with domain and legal knowledge, informed by the numbers.
Frequently asked questions
Is there a library for fairness metrics?
Yes: Fairlearn and AIF360 compute group metrics and offer mitigation methods, such as constrained training and threshold optimisation. The idea is what group_report does here; the libraries add many more metrics and methods.
Where does bias in models come from?
Mostly from data: labels that reflect past unfair decisions, groups that are under-represented, and features measured less accurately for some groups. Modelling choices, such as the threshold and the metric optimised, can add to it.
Should I collect protected attributes at all?
To measure fairness you need them, at least for evaluation. Many teams keep them out of the model's inputs but use them, with care and consent, to check and correct group differences. Legal rules differ by country and use case.
What to learn next
- Put this module together in the ML algorithm comparison project, the next lesson.
- Revisit how a single prediction is explained in explaining model predictions with SHAP.
- Revisit how thresholds trade precision for recall in accuracy, precision, recall and F1.