Fairness & Responsible ML
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A model trained on records of past decisions learns the patterns in those decisions, including unfair ones. Fairness work asks who is affected by a model, measures how well it serves each group, and decides what to change when the groups are treated differently. It is not a feature that can be switched on: no metric certifies a model as fair, and the right criterion depends on the decision and its context.
This page targets Python 3.13, scikit-learn 1.9 and Fairlearn 0.15, and was checked on 2026-10-30. Examples were run on Python 3.13 with scikit-learn 1.9 and Fairlearn 0.15 on 2026-11-01. The data-handling side of the topic (lawful basis, minimisation, anonymisation, the sources of bias, and the full Fairlearn audit with a mitigation comparison) is in Ethics & Privacy and is not repeated here. This page adds the machine-learning view: definitions in terms of a trained classifier, the mitigation families, and how fairness work connects to the rest of the model life cycle. Governance and risk management are covered in Responsible AI Practices, NIST AI Risk Management Framework and EU AI Act; the threats to a deployed model are in the AI Security section.
Where harm comes from
Suresh and Guttag’s framework (summarised in the ethics page) lists sources of harm throughout the life cycle: historical bias in the world, sampling and representation bias, measurement and label bias, proxy features, evaluation bias, deployment bias and feedback loops. Three points matter most when you work on the model itself.
-
Removing the sensitive column does not remove the bias. Postcode, school, purchase history and device type correlate with sex, ethnicity and age. A model can reconstruct the attribute from proxies, and removing it only prevents you from measuring the damage. Keep the attribute for evaluation (where law and policy allow), even if it is not a model input.
-
Labels are measurements. If the label is "was arrested" or "was hired", the model learns the process that produced the label. Ask what the label really measures and for whom it is less accurate.
-
The evaluation set is a population. A single overall metric on a test set dominated by one group can hide poor performance on a smaller one. Always report metrics per group, with sample sizes.
Google’s Machine Learning Crash Course module on fairness names these categories in the same way (reporting bias, selection bias, group attribution bias, implicit bias) and is a short, readable starting point for a team.
Definitions of group fairness
The common criteria compare outputs of a classifier \( \hat{Y} \) across groups defined by a sensitive attribute \( A \), given the true outcome \( Y \) and, for scores, a probability \( S \).
| Criterion | Condition | Intuition |
|---|---|---|
Demographic parity |
\( P(\hat{Y}=1 \mid A=a) \) is equal for all \( a \) |
The same share of each group is selected, regardless of qualification |
Equalized odds |
\( P(\hat{Y}=1 \mid Y=y, A=a) \) is equal for \( y \in \{0,1\} \) |
Equal true-positive and false-positive rates: the model errs equally for qualified and for unqualified people in every group |
Equal opportunity |
\( P(\hat{Y}=1 \mid Y=1, A=a) \) is equal for all \( a \) |
Only the true-positive rate is equalised: qualified people have the same chance everywhere |
Predictive parity |
\( P(Y=1 \mid \hat{Y}=1, A=a) \) is equal for all \( a \) |
A positive prediction means the same precision in every group |
Calibration by group |
\( P(Y=1 \mid S=s, A=a) = s \) for all \( a \) |
A score of 0.7 means about 70 percent in every group |
Individual-level notions also exist: fairness through unawareness (do not use the attribute, which fails because of proxies), individual fairness (similar individuals get similar outcomes, which needs a task-specific similarity metric) and counterfactual fairness (the prediction would not change if the attribute were different in a causal model of the world, which needs the causal model).
Why the criteria conflict
Kleinberg, Mullainathan and Raghavan (2016) and Chouldechova (2017) showed that when the base rates of the outcome differ between groups and the classifier is not perfect, calibration by group, equal false-positive rates and equal false-negative rates cannot all hold at the same time. A concrete consequence: a risk score that is equally calibrated for two groups will have different error rates when the groups have different base rates. Choosing which criterion to give up is an ethical, legal and domain decision. State the choice, the reason and the people consulted in the model documentation instead of presenting one number as proof.
Criteria also carry different legal weight. In US employment practice the "four-fifths rule" compares selection rates (a ratio below 0.8 flags possible adverse impact), which is demographic-parity-like. In European contexts the discussion centres on indirect discrimination and proportionality. Neither is a technical definition of fairness, and a lawyer should confirm what applies to a given system.
Measuring: metrics per group
Fairlearn’s MetricFrame evaluates any scikit-learn-style metric overall and per group, and summarises the gaps. Report the table, not only a summary difference.
import numpy as np
import pandas as pd
from fairlearn.metrics import (
MetricFrame, selection_rate, true_positive_rate, false_positive_rate,
demographic_parity_difference, equalized_odds_difference,
)
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 20_000
group = rng.choice(["A", "B"], size=n, p=[0.7, 0.3])
skill = rng.normal(size=n)
score = skill + rng.normal(scale=0.8, size=n) # noisy measurement
proxy = (group == "B") + rng.normal(scale=0.7, size=n) # leaks group membership
# past decisions were harsher for group B at equal skill
approved = (skill - 0.6 * (group == "B") + rng.normal(scale=0.5, size=n) > 0).astype(int)
X = pd.DataFrame({"score": score, "proxy": proxy})
X_tr, X_te, y_tr, y_te, g_tr, g_te = train_test_split(X, approved, group, test_size=0.3, random_state=0)
clf = LogisticRegression().fit(X_tr, y_tr) # the group column is NOT an input
pred = clf.predict(X_te)
mf = MetricFrame(
metrics={"accuracy": accuracy_score, "selection_rate": selection_rate,
"TPR": true_positive_rate, "FPR": false_positive_rate},
y_true=y_te, y_pred=pred, sensitive_features=g_te,
)
print(mf.by_group.round(3))
print("demographic parity difference:", round(demographic_parity_difference(y_te, pred, sensitive_features=g_te), 3))
print("equalized odds difference: ", round(equalized_odds_difference(y_te, pred, sensitive_features=g_te), 3))
Source: Fairlearn: assessment and Fairlearn: MetricFrame
Even though group is not an input, the proxy feature carries it, so the selection rates differ between groups. A large difference is a signal to investigate, not a verdict. Look at the sample sizes (a gap measured on 30 people is mostly noise), compute confidence intervals with a bootstrap, and read the gap together with the base rates in each group.
Mitigation: before, during or after training
Fairlearn groups mitigation algorithms by where they intervene.
| Stage | Idea | Example in Fairlearn |
|---|---|---|
Pre-processing |
Change the data: reweigh examples, resample, or remove the component of the features that predicts the group |
|
In-processing |
Change the training objective to enforce a constraint |
|
Post-processing |
Keep the trained model and adjust its decisions per group |
|
Pre-processing is model-independent but cannot guarantee the final classifier is fair. In-processing is flexible and returns a randomised classifier. Post-processing needs no retraining but uses the sensitive attribute at prediction time, which may be unlawful or unacceptable in some applications. All three typically lower the overall accuracy slightly; the useful question is how large the trade-off is at the operating point you choose.
# continues the previous example (clf, X_tr, X_te, y_tr, y_te, g_tr, g_te)
from fairlearn.postprocessing import ThresholdOptimizer
from fairlearn.reductions import DemographicParity, ExponentiatedGradient
# In-processing: constrain the learning problem
mitigator = ExponentiatedGradient(LogisticRegression(), constraints=DemographicParity(), eps=0.01)
mitigator.fit(X_tr, y_tr, sensitive_features=g_tr)
pred_in = mitigator.predict(X_te)
# Post-processing: group-specific thresholds on a model that is already trained
post = ThresholdOptimizer(
estimator=clf, constraints="demographic_parity", objective="accuracy_score",
prefit=True, predict_method="predict_proba",
)
post.fit(X_tr, y_tr, sensitive_features=g_tr)
pred_post = post.predict(X_te, sensitive_features=g_te, random_state=0)
for name, p in [("baseline", pred), ("exponentiated gradient", pred_in), ("threshold optimizer", pred_post)]:
dp = demographic_parity_difference(y_te, p, sensitive_features=g_te)
print(f"{name:24s} accuracy={accuracy_score(y_te, p):.3f} parity gap={dp:.3f}")
Source: Fairlearn: mitigation and Fairlearn: API reference
Both mitigated predictions should show a smaller parity gap than the baseline at a modest accuracy cost. Enforcing demographic parity here moves decisions away from what the biased historical labels say, so evaluate with labels you trust or with other metrics before concluding the result is better. Enforcing one criterion can worsen another, so recompute the full MetricFrame after mitigation. Fairlearn’s own documentation notes that its tools are no substitute for judgement about the application.
Document what you built
Documentation is the part of fairness work most likely to survive staff changes.
-
A model card (Mitchell et al., 2019) records the intended use and out-of-scope uses, the training and evaluation data, metrics broken down by relevant groups, ethical considerations and caveats. Hugging Face model cards and Google’s Model Card Toolkit follow the same structure.
-
A datasheet for datasets (Gebru et al.) records motivation, composition, collection process, preprocessing, uses, distribution and maintenance.
-
Record the fairness criterion you chose and why, the groups you could and could not measure, the metrics before and after mitigation, and the open risks.
Store the card with the model artifact and the run record so they travel together, and update it at each retraining. Details on records and provenance are in Reproducibility & MLOps Basics and Experiment Tracking & MLOps.
After deployment
-
Monitor outcomes per group, not only input drift. A model can stay accurate overall while a subgroup degrades. See Drift and Regression Monitoring.
-
Watch feedback loops. Decisions change the data that the next model sees; use exploration, randomised audits or holdout groups to learn about people the model rejects.
-
Provide human review and a route to contest decisions where outcomes significantly affect people. Automated decision-making has specific protections under the GDPR (Article 22), covered in the ethics page.
-
Treat explanations as part of the process. Reasons given to affected people need accurate attributions; see Interpretability & Explainability.
-
Protect the pipeline. Poisoned training data, leaked attributes and exposed model internals are security problems with fairness consequences; see Supply Chain Security and Sensitive Information and Hidden Context.
Responsible-practice checklist
-
The purpose, the affected groups and the harm of a wrong answer (in each direction) are written down.
-
The label is examined as a measurement; its limitations per group are noted.
-
The sensitive attribute is available for evaluation even if it is not a feature, subject to legal advice.
-
Metrics are reported per group with sample sizes and intervals, and the fairness criterion is chosen and justified.
-
Mitigation, if applied, is evaluated with the full metric table and with labels you trust.
-
A model card and datasheet exist and are versioned with the model.
-
A human-review and appeal route exists, and monitoring covers outcomes per group.
-
The risk assessment is aligned with the applicable framework (NIST AI RMF, EU AI Act risk class) and reviewed on change.
Where older books and tutorials are outdated
| Older advice (checked 2026-10-30) | Current practice |
|---|---|
Drop the sensitive column to make a model fair |
Fairness through unawareness fails because of proxies; keep the attribute for measurement |
Rely on a toolkit without checking whether it is maintained |
Check the release history and supported Python and scikit-learn versions of any fairness toolkit before adopting it; this page uses Fairlearn 0.15, which integrates with scikit-learn estimators |
One number (accuracy, AUC) is enough to report |
Report metrics per group; a single overall score can hide group differences |
Pick the "best" fairness metric once |
Criteria conflict; record the choice as a documented judgement |