Sub topic 13
Assessment with Fairlearn
Earlier chapters showed how to compute per-group rates by hand and turn them into gaps. This chapter shows how to do the same job with Fairlearn, an open-source Python library for fairness assessment and mitigation. It assumes you can already do the following:
- Read a confusion matrix and compute precision, recall, and false positive rate.
- Train and evaluate a scikit-learn classifier.
- Use pandas and NumPy.
- Recognize the definitions of demographic parity, equal opportunity, and equalized odds.
You can install the library with pip install fairlearn.
What Fairlearn gives you
Fairlearn's assessment side has two layers:
MetricFrameis a container. You give it any metrics, your labels and predictions, and a sensitive feature. It computes every metric overall and for each group.- Ready-made gap functions, such as
demographic_parity_differenceandequalized_odds_difference, return a single number for one criterion.
MetricFrame is the more flexible tool, because it works with any function that takes (y_true, y_pred), including your own. The gap functions are shortcuts for the common criteria.
A complete example
The script below builds synthetic data with a majority group A and a minority group B. It shifts one feature for group B so the model behaves differently across groups. Then it trains a model and builds a MetricFrame.
from functools import partial
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score
from sklearn.model_selection import train_test_split
from fairlearn.metrics import (
MetricFrame,
count,
false_positive_rate,
selection_rate,
true_positive_rate,
)
X, y = make_classification(n_samples=4000, n_features=8, random_state=0)
rng = np.random.default_rng(0)
group = rng.choice(["A", "B"], size=len(y), p=[0.8, 0.2])
X[group == "B", 0] += 0.8 # shift one feature for group B
X_train, X_test, y_train, y_test, g_train, g_test = train_test_split(
X, y, group, test_size=0.3, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
y_pred = model.predict(X_test)
mf = MetricFrame(
metrics={
"n": count,
"selection_rate": selection_rate,
"tpr": true_positive_rate,
"fpr": false_positive_rate,
"precision": partial(precision_score, zero_division=0),
"accuracy": accuracy_score,
},
y_true=y_test,
y_pred=y_pred,
sensitive_features=g_test,
)
print(mf.overall)
print(mf.by_group)
print(mf.difference())
print(mf.ratio())The exact numbers depend on your library versions. The structure of the output does not.
Reading the MetricFrame
MetricFrame exposes several attributes and methods that you will use constantly.
| Member | What it returns |
|---|---|
| `mf.overall` | Each metric computed on the whole dataset |
| `mf.by_group` | A DataFrame with one row per group and one column per metric |
| `mf.group_min()` and `mf.group_max()` | The lowest and highest value of each metric across groups |
| `mf.difference()` | Largest gap between groups for each metric (`max - min` by default) |
| `mf.ratio()` | Smallest group value divided by the largest, for each metric |
These map directly onto the criteria from earlier chapters:
- Demographic parity corresponds to the
selection_ratecolumn ofmf.difference(). - Equal opportunity corresponds to the
tprcolumn. - Equalized odds needs both the
tprandfprcolumns. Take the larger of the two gaps. - Predictive parity corresponds to the
precisioncolumn.
The n column matters as much as the rates. A gap computed from 40 people means something very different from one computed from 4,000. We return to this point under pitfalls below.
difference() also accepts method="to_overall". That compares each group to the overall value instead of to the other groups. With more than two groups this is often easier to interpret, because "the largest gap between any two groups" depends on which two groups happen to sit at the extremes.
One-number summaries
When you need a single number for a dashboard or a test, use the dedicated functions:
from fairlearn.metrics import (
demographic_parity_difference,
demographic_parity_ratio,
equalized_odds_difference,
)
dp_diff = demographic_parity_difference(y_test, y_pred, sensitive_features=g_test)
dp_ratio = demographic_parity_ratio(y_test, y_pred, sensitive_features=g_test)
eo_diff = equalized_odds_difference(y_test, y_pred, sensitive_features=g_test)
print(f"demographic parity difference: {dp_diff:.3f}")
print(f"demographic parity ratio: {dp_ratio:.3f}")
print(f"equalized odds difference: {eo_diff:.3f}")equalized_odds_difference returns the larger of the TPR gap and the FPR gap. This is the same definition as the max(...) expression in the hand-written version. You can check your own earlier code against it.
Several sensitive features and control features
You can pass more than one sensitive feature, which is how you get the intersectional view from the earlier chapter. Pass a DataFrame whose columns are the attributes. by_group then has a row for every combination:
import pandas as pd
sensitive = pd.DataFrame({
"group": g_test,
"age_band": np.where(X_test[:, 1] > 0, "older", "younger"),
})
mf2 = MetricFrame(
metrics={"n": count, "tpr": true_positive_rate, "selection_rate": selection_rate},
y_true=y_test,
y_pred=y_pred,
sensitive_features=sensitive,
)
print(mf2.by_group)Here age_band is a made-up attribute derived from a feature, used only to show the mechanics. In a real audit it would come from your data.
MetricFrame also takes a control_features argument. It computes the metrics within each level of the control feature and then compares groups inside it. This is useful when a legitimate factor, such as job category, explains part of a gap. Be careful, though. Choosing a control feature is a judgment about what counts as legitimate. It changes the question you are answering, and a biased control feature can hide the problem you are looking for.
Pitfalls
- Metrics are computed on whatever you pass in. Fairlearn does not check that your test set represents the deployed population. A tidy
MetricFrameon an unrepresentative sample is still misleading. - Empty cells produce odd values. If a group has no positive examples, TPR is undefined. Depending on the metric function, you may get
NaN, a warning, or a zero. The precision metric above useszero_division=0to make that choice explicit. Checknand the label counts before trusting any rate. - Gaps have no confidence intervals by default.
difference()returns a point estimate. For small groups, resample the test set, recompute the gap for each resample, and report the spread. This is the approach from the small-subgroups chapter. - A threshold-dependent metric depends on the threshold. All metrics above use hard predictions at the default 0.5 cutoff. If the deployed system uses a different threshold, evaluate at that threshold. If it ranks people, consider assessing scores or calibration per group as well.
- Group labels are only as good as the sensitive feature. Missing values, inconsistent spellings, or coarse categories silently change which groups exist. Print
mf.by_group.indexand confirm the groups are what you intended. - A smaller gap is not proof of fairness. Fairlearn reports numbers. Deciding which criterion applies, and what gap is acceptable, remains a decision for people with knowledge of the context and the harms involved.
Where mitigation fits
Fairlearn also includes mitigation tools, such as ThresholdOptimizer for post-processing, which the next chapter covers. The assessment workflow stays the same either way. Build the MetricFrame before the change and build it again after. Compare the whole tables, not only the gap you targeted. Save both as part of your audit record.
Exercise
You build a MetricFrame with metrics tpr and fpr and a binary sensitive feature. mf.difference() shows tpr 0.04 and fpr 0.11. What does equalizedoddsdifference return on the same data, and why can a result of 0.04 alone be misleading here?
Show answer
It returns 0.11, the larger of the TPR gap and the FPR gap, because equalized odds requires both rates to match across groups. Reporting only the TPR gap of 0.04 would satisfy equal opportunity but hide the much larger false positive disparity, which is often the more harmful error when a positive prediction triggers a penalty or an investigation.
Exercise
A MetricFrame shows a TPR gap of 0.15 between groups A and B. The n column shows group B has 60 test rows, of which 12 are true positives. List two checks you should run before reporting this gap as a finding.
Show answer
First, resample the test set (bootstrap) and recompute the TPR gap many times to see how wide its spread is. With only 12 true positives in group B, a single TPR value can move a lot from one resample to the next. Second, check whether you can get more data for group B, for example by using cross-validation predictions or a larger evaluation set. Also confirm that group B's labels and group membership are recorded correctly. Report the gap along with the sample sizes and the uncertainty range.