Sub topic 13
Assessment with Fairlearn
Fairlearn is a Python library that computes per-group metrics and summarizes the gaps between groups. This chapter assumes you can compute the confusion-matrix rates by hand, as in the earlier chapter on per-group rates, and that you know scikit-learn and pandas. Fairlearn replaces the hand-written loop with a tested class.
The MetricFrame idea
MetricFrame takes a dictionary of metric functions, the true labels, the predictions, and the sensitive feature. It evaluates every metric on the whole dataset and on each group. It then exposes the results as pandas objects.
A complete example
The script below builds synthetic data where group B has a shifted feature. It trains a model and audits it.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score
from fairlearn.metrics import (
MetricFrame, count, selection_rate,
true_positive_rate, false_positive_rate,
demographic_parity_difference, equalized_odds_difference,
)
rng = np.random.default_rng(0)
n = 4000
group = rng.choice(["A", "B"], size=n, p=[0.7, 0.3])
x1 = rng.normal(size=n)
x2 = rng.normal(loc=np.where(group == "B", -0.5, 0.0))
p = 1 / (1 + np.exp(-(1.2 * x1 + 0.8 * x2)))
y = (rng.random(n) < p).astype(int)
X = np.column_stack([x1, x2])
X_tr, X_te, y_tr, y_te, g_tr, g_te = train_test_split(
X, y, group, test_size=0.3, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
y_pred = model.predict(X_te)
mf = MetricFrame(
metrics={
"n": count,
"accuracy": accuracy_score,
"precision": precision_score,
"selection_rate": selection_rate,
"tpr": true_positive_rate,
"fpr": false_positive_rate,
},
y_true=y_te,
y_pred=y_pred,
sensitive_features=g_te,
)
print(mf.overall)
print(mf.by_group)
print(mf.difference()) # largest gap between any two groups, per metric
print(demographic_parity_difference(y_te, y_pred, sensitive_features=g_te))
print(equalized_odds_difference(y_te, y_pred, sensitive_features=g_te))Reading the output
mf.overallis the metric on all rows. A good overall value can hide a weak group.mf.by_groupis a DataFrame with one row per group. Look here first.mf.difference()is the largest absolute gap between groups for each metric.mf.ratio()gives the smallest group value divided by the largest.demographic_parity_differenceis the gap in selection rate.equalized_odds_differenceis the larger of the TPR gap and the FPR gap. These match the criteria you computed manually.
Common errors
- Passing the sensitive feature as a model input and also as an audit column without noticing. Auditing needs the attribute even if the model never sees it.
- Mismatched indexes. If
y_trueis a pandas Series with a shuffled index andsensitive_featuresis a NumPy array, rows can be silently misaligned. Reset indexes or use arrays for all three. - Metrics that expect probabilities. Metrics such as AUC need scores, not hard labels. Pass labels for rate metrics, and check each metric's expected input.
- Undefined values. A group with no positive examples makes TPR undefined. Check
countand the label balance per group. - Treating a small difference as zero or a large one as proof. A gap needs a significance judgment and a context judgment.
Exercise
You run mf.difference() and see a recall gap of 0.15, but mf.overall recall is 0.90 and group B has only 25 rows. What do you do before reporting a fairness problem, and which Fairlearn output do you check first?
Show answer
Check mf.by_group for the count column to confirm group B's size. With 25 rows the recall estimate is very noisy, since it rests on perhaps a dozen positive cases. Estimate uncertainty with a bootstrap or confidence interval on the group recall, and gather more data if possible. Report the gap as uncertain rather than as a confirmed violation.