Lesson 04 · 45 minutes
Measure fairness between two groups of applicants
- Measure accuracy, selection rate and true positive rate for each group
- Compute the selection-rate ratio and test it against a limit that people chose
- Try two mitigations and report what each one costs
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
LoanScore passes its accuracy test, and the compliance lead of Harbour Credit asks a different question: "Does it treat group A and group B alike?" You get 1,000 invented loan applications, each with a group, three inputs and a known outcome (repaid or not). The group is not an input of the model, and you must still find out whether the model's outcomes differ by group, say by how much, try to narrow the gap, and report what narrowing it costs.
Recall
How AI works, lesson 3: why do you keep a test set that the model never trains on?
A model scored on its own training data looks better than it is. The test set shows how it behaves on cases that it has not seen. Fairness numbers need the same care, so this lesson measures on the held-out rows.
Lesson 3: which row of the risk register does this lesson serve?
R1, "Loan approvals are biased against group B". Its control is a fairness test before every release. This lesson writes that test, and the result is the evidence behind the residual score.
The idea
A model makes a favourable decision (here, approve a loan) for some people and not for others. To compare groups, you count. Three numbers do most of the work:
| Measure | Question | How to compute it |
|---|---|---|
| Accuracy | Is the model right for this group? | decisions that match the outcome, divided by rows |
| Selection rate | How many people get the favourable decision? | approvals divided by rows |
| True positive rate | Of those who would repay, how many get a loan? | approvals among repayers, divided by repayers |
The selection-rate ratio is the lower selection rate divided by the higher one. A ratio of 1.00 means equal rates. Somebody must choose a limit. This course uses 0.80 as an example. It is the figure of the four-fifths rule that US employment guidance uses as a first screen for hiring. Other places use other limits, and the ratio has other names, such as the disparate impact ratio. It is not a law of nature. Your legal and compliance people know which rule applies to your case, and the current official text decides it.
The measures can disagree. When the true repay rates of the groups differ, a model cannot have equal selection rates and equal error rates at the same time, except in special cases. So a fairness metric is a choice that people must make. Code measures. People decide which measure matters, which limit is acceptable, and what price they will pay. A passing ratio does not prove that a system is fair, and a failing ratio does not prove unlawful bias. Each is a signal to look closer.
- Model → Groups: split the decisions
- Groups → Measures: accuracy, selection, true positive
- Measures → Ratio: lower rate over higher rate
- Ratio → People: choose the limit and any change
Removing the group column does not remove the gap. Other inputs can stand in for the group: income here, and the length of a career gap in the exercise. Such an input is a proxy. You still need the group labels to measure, and you must protect them: they are personal data in most settings.
Worked example
Work in ~/krlab/ai-governance with the environment on. data/loans.csv has an id, the group, three inputs and repaid.
1. Count the groups
cut -d, -f2 keeps the second column of a comma-separated file. sort puts lines in order and uniq -c counts equal neighbours, so together they count each value.
cut -d, -f2 data/loans.csv | sort | uniq -c 592 A
408 B
1 group2. Measure the model
The file has three parts. Read the notes of each part before you read its code.
- Load and split (
load,split).load(**LOANS)hands the entries of the dictionaryLOANSto the function as named arguments, anddef split(*arrays)collects any number of arguments.train_test_splitcuts the rows into a training part and a test part, andrandom_state=0makes the cut the same on every machine. - Fit (
fit).LogisticRegressionis the model from "How AI works": it gives each applicant a probability.StandardScalerrescales each input to a similar size, andmake_pipelinechains the two. - Measure (
by_group,ratio,show, and the part under__main__). A numpy mask such asg == "A"is a list of True and False values that picks rows.predict_probagives the probabilities as two columns, and[:, 1]keeps the column for "repaid"..astype(int)turns True and False into 1 and 0.by_groupturns decisions into the three measures for each group. In an f-string,{acc:<10.2f}means left-aligned in 10 characters with 2 decimals.
Save fairness.py.
fairness.py
"""fairness.py: accuracy, selection rate and true positive rate for each group, and the ratio of selection rates.
python3 fairness.py (the loan data set)
"""
import csv
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
LOANS = dict(path="data/loans.csv", features=["income", "debt_ratio", "history_years"], label="repaid")
def load(path, features, label):
with open(path, newline="") as f:
rows = list(csv.DictReader(f))
X = np.array([[float(r[name]) for name in features] for r in rows])
return X, np.array([int(r[label]) for r in rows]), np.array([r["group"] for r in rows])
def split(*arrays):
"""A fixed 70/30 split of any arrays of the same length: the same rows for every reader."""
return train_test_split(*arrays, test_size=0.3, random_state=0)
def fit(X, y, weights=None):
model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(X, y, logisticregression__sample_weight=weights)
return model
def by_group(y, favourable, g):
"""For each group: (rows, accuracy, selection rate, true positive rate). `favourable` is 1 or 0 per row."""
out = {}
for name in sorted(set(g)):
m = g == name
out[name] = (int(m.sum()), (favourable[m] == y[m]).mean(), favourable[m].mean(), favourable[m & (y == 1)].mean())
return out
def ratio(table):
rates = [row[2] for row in table.values()]
return min(rates) / max(rates)
def show(table):
print("group rows accuracy selected true-pos")
for name, (n, acc, sel, tpr) in table.items():
print(f"{name:<7}{n:<6}{acc:<10.2f}{sel:<10.2f}{tpr:.2f}")
print(f"selection-rate ratio {ratio(table):.2f}")
if __name__ == "__main__":
X, y, g = load(**LOANS)
X_train, X_test, y_train, y_test, g_train, g_test = split(X, y, g)
model = fit(X_train, y_train)
chosen = (model.predict_proba(X_test)[:, 1] >= 0.5).astype(int)
show(by_group(y_test, chosen, g_test))python fairness.pygroup rows accuracy selected true-pos
A 177 0.86 0.75 0.94
B 123 0.88 0.56 0.91
selection-rate ratio 0.753. Read the table
Accuracy and the true positive rate are close for the two groups: among people who would repay, almost the same share of each group gets a loan. The selection rate differs, and the ratio is 0.75. By the example limit of 0.80 the model fails.
Look at why. The generator gave group B a lower income on average, and income is the strongest input. In the data, group B repays less often too (about 0.50 against 0.67). The model is accurate for both groups, and it still approves fewer people of group B. That is the point of the lesson: accuracy alone would have passed this model.
4. Try two mitigations
A mitigation is a change that moves a number. The first one lowers the approval threshold for group B until the ratio reaches the limit. A threshold is the probability above which the model says yes. The second one trains with weights: each row counts more or less in training, so that group and outcome look independent. np.where(test, a, b) takes a where the test is true and b elsewhere, and np.arange(0.50, 0.0, -0.01) counts down from 0.50 in steps of 0.01.
The weight of a row is the share that a (group, outcome) pair would have if group and outcome were independent, divided by the share that it has. A pair that is rarer than expected counts more. In fit, the name logisticregression__sample_weight has a double underscore: it sends the weights to the step called logisticregression inside the pipeline. Save mitigate.py.
mitigate.py
"""mitigate.py: two ways to move the selection-rate ratio, and what each costs in accuracy."""
import numpy as np
from fairness import LOANS, by_group, fit, load, ratio, split
TARGET = 0.80 # a limit that people chose. The code only applies it.
def summary(name, y, chosen, g):
table = by_group(y, chosen, g)
bad = int(((chosen == 1) & (y == 0)).sum())
print(f"{name:<26}{(chosen == y).mean():<10.2f}{ratio(table):<8.2f}{table['A'][2]:<8.2f}{table['B'][2]:<8.2f}{bad}")
def group_threshold(score, y, g):
"""Lower the threshold of group B, one step at a time, until the ratio reaches TARGET."""
for cut in np.arange(0.50, 0.0, -0.01):
chosen = np.where(g == "B", score >= cut, score >= 0.50).astype(int)
if ratio(by_group(y, chosen, g)) >= TARGET:
return chosen, round(float(cut), 2)
def weights(y, g):
"""One weight for each (group, outcome) pair, so that group and outcome look independent in training."""
w = np.ones(len(y))
for name in set(g):
for outcome in (0, 1):
m = (g == name) & (y == outcome)
w[m] = (g == name).mean() * (y == outcome).mean() / m.mean()
return w
if __name__ == "__main__":
X, y, g = load(**LOANS)
X_train, X_test, y_train, y_test, g_train, g_test = split(X, y, g)
model = fit(X_train, y_train)
score = model.predict_proba(X_test)[:, 1]
print("method accuracy ratio rate A rate B bad loans")
summary("threshold 0.50", y_test, (score >= 0.50).astype(int), g_test)
chosen, cut = group_threshold(score, y_test, g_test)
summary(f"group B threshold {cut}", y_test, chosen, g_test)
reweighted = fit(X_train, y_train, weights(y_train, g_train))
summary("reweighted training", y_test, (reweighted.predict_proba(X_test)[:, 1] >= 0.50).astype(int), g_test)python mitigate.pymethod accuracy ratio rate A rate B bad loans
threshold 0.50 0.87 0.75 0.75 0.56 25
group B threshold 0.36 0.87 0.80 0.75 0.60 28
reweighted training 0.87 0.77 0.75 0.58 255. Read the cost
The group threshold reaches 0.80 when group B's threshold falls from 0.50 to 0.36. Overall accuracy stays at 0.87, but the number of bad loans (approved, not repaid) rises from 25 to 28. That is the price: the lender takes on three more bad loans in 300 decisions to approve more of group B. Reweighting moves the ratio only to 0.77 and does not reach the limit.
Two more questions are for people, not for code. Is it acceptable to use a different threshold for each group? For credit, using the group in the decision can be unlawful. Treat the group threshold as a test of how big the gap is, not as the fix to ship, unless your legal team has approved it in writing. And is a ratio the right measure at all, or would the lender prefer to equalise the true positive rate, which is already close? The script cannot answer.
Your turn
The HR department has invented data of past hiring decisions in data/screening.csv: id, group, test_score, years, gap_months (months without work) and hired. Past managers penalised career gaps, and gaps are longer in group B on average. The inputs are test_score, years and gap_months, and the label is hired.
Write fairness2.py. It imports load, split, fit, by_group, show and ratio from fairness.py and does not repeat their code. It uses split and trains on the training part, and it prints the table for the test rows with a threshold of 0.50. Then it runs again with gap_months removed from the inputs. Answer from your own runs.
Last, write two sentences for HR: why removing the group column was not enough, and what the gap input did.
Check yourself
Accuracy is high for both groups, and the selection rates differ. Is the model unfair?
The selection-rate ratio fails an example limit, so there is a gap to look at. Whether it is unfair depends on the measure that people chose, on why the groups differ and on the law. The result starts a review. It does not close one.
Why does lowering one group's threshold raise the number of bad loans?
A lower threshold approves applicants whom the model thinks are less likely to repay. Some of them will not repay. That is the cost of moving the ratio, and the lender must decide whether it accepts it.
You remove the group column from the inputs and the ratio does not change much. Why?
The group was never an input here. Other inputs carry the same information: income here, career gaps in the exercise. Removing the label hides the problem from the model, and the outcomes still differ.
Why is "we measured fairness" not enough in a governance pack?
A pack needs the measure, the limit, who chose the limit, the date, the data and the model version. A number without these cannot be audited. Lesson 13 checks the ratio from raw decisions against a limit that the pack states.
Field notes
- Pick the metric and the limit before you see the result, write them down with the reason and the person who chose them, and keep that record with the report. Choosing a limit after the result is a way to pass.
- Measure on data that looks like production, and measure again each month. A model that passes at launch can drift (lesson 3, accuracy drift). Small groups give noisy ratios: report the number of rows with every ratio.
- Several groups and several attributes (for example age and sex together) multiply the checks. Decide in advance which groups matter and why, and do not hunt through many splits for a failure or a pass.
- Group labels are sensitive data. Keep them apart from the model inputs, restrict access, and say in the data sheet (lesson 10) why you hold them.
- The NIST AI RMF names this kind of work under Measure (lesson 7), and the EU AI Act asks high-risk providers to examine their data for possible bias (lesson 6, Article 10 on data and data governance). Take the exact duties from the current official text.