Lesson 20 of 227 min
Bias and fairness
A model can be right as often for two groups and still treat them differently, so count every kind of mistake for each group, and choose which one to make equal.
After this lesson you can check whether a model treats groups differently, and why.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Train with and without the group column
Run these cells in order. Use the same held-out people to compare two income models. Both use a threshold of 0.50. Giving the model the sex column changes which gaps are largest. ACSIncome dataset
from fairlearn.datasets import fetch_acs_income
from fairlearn.metrics import MetricFrame, false_positive_rate, selection_rate
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import precision_score, recall_score
from sklearn.model_selection import train_test_split
people = fetch_acs_income(states=["CA"], as_frame=True).frame
features = ["AGEP", "COW", "SCHL", "MAR", "OCCP", "POBP", "RELP", "WKHP"]
train, test = train_test_split(people, test_size=0.2, random_state=0)
y_train, y_test = (train.PINCP > 50000).astype(int), (test.PINCP > 50000).astype(int)metrics = {"picked": selection_rate, "recall": recall_score,
"precision": precision_score, "false alarms": false_positive_rate}
sex = test.SEX.map({1: "men", 2: "women"})
def by_sex(picks):
return MetricFrame(metrics=metrics, y_true=y_test, y_pred=picks, sensitive_features=sex)
baseline = HistGradientBoostingClassifier(random_state=0).fit(train[features], y_train)
baseline_picks = baseline.predict(test[features])with_sex = features + ["SEX"]
second = HistGradientBoostingClassifier(random_state=0).fit(train[with_sex], y_train)
print(by_sex(baseline_picks).difference().round(3).to_dict())
print(by_sex(second.predict(test[with_sex])).difference().round(3).to_dict()){'picked': 0.087, 'recall': 0.013, 'precision': 0.078, 'false alarms': 0.01}
{'picked': 0.134, 'recall': 0.071, 'precision': 0.046, 'false alarms': 0.049}Tune a line for each group
Fit the model on one set, tune the lines on another, then measure the gaps on the test set. ThresholdOptimizer can mix two thresholds to target equal recall. It needs group membership when predicting. Check the rules for your use case before deploying group-specific decisions. ThresholdOptimizer
from fairlearn.postprocessing import ThresholdOptimizer
fit, tune = train_test_split(train, test_size=0.25, random_state=0)
model = HistGradientBoostingClassifier(random_state=0)
model.fit(fit[features], fit.PINCP > 50000)
tuned = ThresholdOptimizer(estimator=model, prefit=True, predict_method="predict_proba",
constraints="true_positive_rate_parity")
tuned.fit(tune[features], tune.PINCP > 50000, sensitive_features=tune.SEX)
picks_tuned = tuned.predict(test[features], sensitive_features=test.SEX, random_state=0)
print(by_sex(picks_tuned).difference().round(3).to_dict()){'picked': 0.066, 'recall': 0.01, 'precision': 0.094, 'false alarms': 0.009}Set a goal during training
ExponentiatedGradient fits models with different weights so the training can target small gaps. EqualizedOdds targets both recall and false alarms. Compare the constrained tree with a plain tree trained on the same rows. Check both error rates on the test set. Fairlearn reductions
from fairlearn.reductions import EqualizedOdds, ExponentiatedGradient
from sklearn.tree import DecisionTreeClassifier
sample = fit.sample(n=15000, random_state=0)
actual = (sample.PINCP > 50000).astype(int)
plain = DecisionTreeClassifier(max_depth=5, random_state=0)
plain.fit(sample[features], actual)
model = ExponentiatedGradient(plain, EqualizedOdds(difference_bound=0.02))
model.fit(sample[features], actual, sensitive_features=sample.SEX)for name, picks in [("plain", plain.predict(test[features])),
("constrained", model.predict(test[features], random_state=0))]:
print(name, by_sex(picks).difference()[["recall", "false alarms"]].round(3).to_dict())plain {'recall': 0.002, 'false alarms': 0.002}
constrained {'recall': 0.006, 'false alarms': 0.007}Both held-out gaps were already under one percentage point. They grew slightly after constrained training.
Put a name on each comparison
Demographic parity compares the share picked. Equalized odds compares recall and false alarm rates together. Calibration compares a score with what happens. For example, among people scored near 0.70, look for about 70 in 100 earning over the line in each group. One score band is a spot check. Fairlearn metrics
print(by_sex(baseline_picks).by_group[["picked", "recall", "false alarms"]].round(3))
scores = baseline.predict_proba(test[features])[:, 1]
band = (scores >= 0.65) & (scores < 0.75)
print("Observed near 0.70:", y_test[band].groupby(sex[band]).mean().round(3).to_dict()) picked recall false alarms
SEX
men 0.450 0.786 0.155
women 0.363 0.773 0.145
Observed near 0.70: {'men': 0.73, 'women': 0.66}Count how many people each rate comes from
Recall uses only people earning over $50,000. A recall of 80 in 100 can come from 8 of 10 people or 800 of 1,000. The second number has a smaller sampling margin. Here is a 95% Wilson interval for each, treating the examples as independent draws.
def recall_interval(found, eligible):
rate, z = found / eligible, 1.96
mid = rate + z**2 / (2 * eligible)
half = z * (rate * (1 - rate) / eligible + z**2 / (4 * eligible**2))**0.5
scale = 1 + z**2 / eligible
return round((mid - half) / scale, 2), round((mid + half) / scale, 2)
print(recall_interval(8, 10))
print(recall_interval(800, 1000))(0.49, 0.94) (0.77, 0.82)
Check what the label measures
In a health study, past spending tracked access to care as well as illness. At equal scores, Black patients were sicker than white patients. This toy example shows how the label changes who qualifies. The EU AI Act also lists certain hiring and credit-scoring uses as high risk. Health study EU AI Act, Annex III
import pandas as pd
patients = pd.DataFrame({"group": ["A", "B"], "conditions": [3, 3], "past_spend": [900, 350]})
patients["qualifies_by_spend"] = patients.past_spend >= 500
patients["qualifies_by_need"] = patients.conditions >= 3
print(patients[["group", "qualifies_by_spend", "qualifies_by_need"]].to_string(index=False))group qualifies_by_spend qualifies_by_need
A True True
B False TrueRun on Python 3.13.3, Fairlearn 0.15.0, scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Precision, recall and the confusion matrix
Of 1,000 calls, 113 said yes. The bank's model is right on 898 of them. A model that says no to everyone is right on 887. What does that tell you?
2 of 3
A model is never given a person's race. Can it still treat people of different races differently?
3 of 3
A model picks people for job interviews. fairlearn's difference() prints the gap between two groups for each count: picked 0.05, recall 0.02, precision 0.09, false alarms 0.02. Which count should be equal?
The ideas in this lesson
- Scores by group
- Count a model's right and wrong picks for each group apart: one score for everyone can hide who pays for the mistakes.
- Proxies
- Other columns can tell a person's group, so a model that never sees the group can still treat groups differently.
- Which mistake to make equal
- When groups differ in how often the answer is yes, no line makes every count equal; choose by who each mistake hurts.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Fairness
Here's a puzzle. This model reads people's answers to a big survey. It guesses who earns a high income. It never sees if a person is a man or a woman. Can it still treat men and women differently?
Keep your guess
Hold on to your guess... The United States government ran this survey in California in 2018. Here are people who worked that year.
Each solid dot is someone who earned over fifty thousand dollars.
The model
The model is boosted trees. They learned to guess it from eight answers: age, job, hours worked, education, and a few more. Sex and race aren't among them. It picks a person when its chance is one half or more. That's its line. Overall, it's right for eighty-two in a hundred.
Each group apart
One score for everyone says nothing about each group. So count each group separately: a thousand men and a thousand women it never learned from. It's right for eighty-two in a hundred men, and eighty-three in a hundred women. About the same, so far. But two classes can do equally well on a test, and still get different questions wrong.
The same mistakes?
So count each kind of mistake, like you did for the bank's calls. Take those who earn over fifty thousand: the people who should be picked.
It finds seventy-seven in a hundred men... and seventy-eight in a hundred women. That's recall, and it's about the same.
Now take those who don't earn that much. It picks thirteen in a hundred men, and fifteen in a hundred women, by mistake.
Those are false alarms, and they're about the same too.
There's one count left.
Precision differs
Now look at its picks. Of the men it picks... eighty-four in a hundred really earn over fifty thousand.
And of the women it picks?
Seventy-four in a hundred. That's precision. A woman it picks is a wrong pick more often. So yes. In one count, it treats men and women differently.
Proxies
This model never sees sex... So how can it treat women differently?
Its other answers give away a person's sex.
A model can guess it from them about three times out of four... mostly from the job, and the hours worked.
A column that stands in for a group is called a proxy. And the groups differ. In this table, forty-seven in a hundred men earn over fifty thousand, and thirty-six in a hundred women. So more of the women are in the group that earns less. The model picks fifteen in a hundred of that group, by mistake. Fifteen in a hundred of a bigger group is more wrong picks: ninety-six, compared to the men's seventy. So more of the women's picks are wrong ones. Leaving the column out does not leave the group out.
A line for each group
Here, a woman the model picks is a wrong pick more often than a man. Can the line fix it?
Give each group its own line. Raise the women's line to zero point seven four.
Now their picks are right eighty-three times out of a hundred, like the men's. But what fell?
Of the women who earn over fifty thousand, it now finds only fifty-five in a hundred. Fixing one count broke another.
No line fixes all
Is there a line that makes every count equal?
Slide the women's line from the bottom to the top. With the men's line fixed, no line here matches both their precision and their recall. There's a trade-off that goes beyond this model. Suppose recall and the false alarm rate both match, and both are above zero.
If one group has more people earning over fifty thousand per hundred, its precision will be higher.
You can see it in real life. A risk score used by courts in Florida, called COMPAS, was right about as often for Black people as for white people.
Now look at people with no repeat offense recorded within two years. It marked forty-five in a hundred Black people as high risk, and twenty-three in a hundred white people.
Count how often the score was right, and the groups look close. Count the false alarms, and the gap is much wider.
Which mistake, for whom
So you choose which count to make equal, based on who each mistake hurts.
On a test, a wrong answer costs the student who gave it. A model's wrong pick costs the person it picked.
If a pick gives people something, like an interview or an offer, look at recall. When recall is equal, the model finds the same share of qualified people in each group. That's called equal opportunity. Here, recall is already close. If a wrong pick hurts people, like a loan they can't pay back, look at precision. Here, there's a gap.
Then write down every count by group, and your choice.
In code
In real code, use fairlearn's MetricFrame. Give it the counts you want: the share it picks, recall, precision and false alarms. Then the true answers, the model's picks, and each person's group. It prints a row for men, and a row for women. Then the gap for each count. Which gap is the biggest?
Precision, at zero point zero nine.
This is the check to run before any model that makes decisions about people goes live.
Three ideas
So: count every kind of mistake, for each group. Leaving a column out does not leave the group out.
And no line makes every count equal, so you choose which one, based on who each mistake hurts.
Count each group's mistakes
So count each group's mistakes, and choose which to make equal. Now try it on this lesson's page, and take the quiz. Make the women's false alarms equal to the men's.
You use this lesson in Lab 8: A check-up for a model in use, after Drift.
Facts last checked on .
