Lab: Measuring Fairness Across Groups and Counterfactual Prompts
Audit predictive models for disparate impact using Fairlearn MetricFrames, quantify demographic parity and equalized odds differences across sensitive groups, and evaluate generative models using paired counterfactual prompt probing.
Contentsand lesson path
On this page
Lessons of Responsible ML
- Where Bias Enters an ML System Concept · 20 min
- Lab: Measuring Fairness Across Groups and Counterfactual Prompts Lab · 30 min
- Worked Example: Closing a Gap and Paying the Price Worked example · 20 min
- Lab: Explaining Predictions Globally and Locally Lab · 25 min
- Model Cards and Risk Documentation Concept · 15 min
- Check: Release Review Knowledge check · 10 questions
What you will learn
- Measure group fairness metrics (demographic parity difference, equalized odds and per-group error rates), report group sizes and uncertainty, and explain how differing base rates and imperfect predictions can make chosen fairness criteria conflict under stated assumptions.
- Apply one mitigation (reweighting, per-group thresholds or constrained training) and report its effect on both fairness and accuracy.
- Test a text-generating model for bias with counterfactual prompt pairs that differ only in a demographic attribute, score the outputs with a rubric or classifier, and report the gap with an uncertainty interval.
01. Disaggregated Fairness Auditing and Counterfactual Evaluation
A machine learning model can exhibit impressive global performance—such as an overall ROC-AUC of 0.88 or an accuracy of 91%—while harboring severe, localized performance disparities across demographic subgroups. To detect disparate impact, responsible ML practitioners move beyond aggregate evaluation benchmarks and compute disaggregated group fairness metrics across protected slices. Furthermore, in generative natural language models, fairness auditing requires counterfactual probing to measure whether altering demographic markers induces systematic shifts in generated text sentiment or capability assessment.
- Group Fairness Metric Definitions:
- Demographic Parity Difference (DPD): Measures whether positive decision rates are equal across groups, regardless of ground-truth outcome distributions:
$$\text{DPD} = \max_a P(\hat{Y}=1 \mid A=a) - \min_a P(\hat{Y}=1 \mid A=a)$$
A demographic parity difference of zero implies that all groups receive approval or selection at identical rates ($P(\hat{Y}=1 \mid A=0) = P(\hat{Y}=1 \mid A=1)$). While intuitive, demographic parity ignores underlying differences in qualification distributions and base rates.
- Equalized Odds Difference (EOD): Conditions on the true outcome $Y$, requiring that both True Positive Rates (TPR) and False Positive Rates (FPR) match across groups simultaneously:
$$P(\hat{Y}=1 \mid A=a, Y=y) = P(\hat{Y}=1 \mid A=b, Y=y), \quad \forall y \in {0, 1}$$
The Equalized Odds Difference is calculated as $\max(\Delta_{\text{TPR}}, \Delta_{\text{FPR}})$. A relaxed criterion, Equal Opportunity, requires only that True Positive Rates be equal across groups ($P(\hat{Y}=1 \mid A=0, Y=1) = P(\hat{Y}=1 \mid A=1, Y=1)$), ensuring that qualified candidates across all demographic slices enjoy an equal likelihood of selection.
-
The Fairlearn
MetricFrameAbstraction: In Python ecosystems, the open-source libraryfairlearnprovides the standardMetricFramecontainer. AMetricFrameevaluates arbitrary performance metrics (accuracy, precision, recall, selection rate, false positive rate) across user-specified sensitive demographic features. It automatically computes disaggregated per-group values, group-level differences (maximum minus minimum), and group-level ratios (minimum divided by maximum), while keeping group sample counts transparent. -
Small Group Uncertainty and Minimum Reporting Counts: When evaluating sub-populations with small sample sizes (e.g., indigenous populations or rare intersectional groups), empirical error rates exhibit massive statistical uncertainty. Reporting an error rate of 50% based on $N = 4$ observations produces misleading alarms. Best practices mandate establishing minimum reporting counts (e.g., $N \ge 50$) and publishing standard errors or paired bootstrap confidence intervals alongside all reported fairness metrics.
-
Counterfactual Prompt Probing for Generative Models: Evaluating fairness in generative large language models (such as automated resume summarizers, job recommendation assistants, or medical chatbots) cannot be accomplished via traditional classification confusion matrices. Instead, teams employ counterfactual prompt probing:
- Construct Paired Test Fixtures: Create pairs of input prompts that are mathematically identical in qualifications, professional achievements, and sentence structure, differing exclusively in one demographic marker (e.g., changing "James" to "Emily", or "he was born in Mexico" to "he was born in Canada").
- Blind Standardized Scoring: Pass the model outputs to a deterministic scoring rubric or an independent classification judge operating blind to the demographic attribute.
- Statistical Gap Quantification with Bootstrap Intervals: Measure the sentiment or recommendation score gap across $M$ pairs (e.g., $M = 500$) and compute a paired bootstrap confidence interval. If the confidence interval excludes zero, statistically significant counterfactual bias exists.
-
Selection Rate Ratio and the Four-Fifths Rule: In addition to absolute demographic parity differences, regulatory bodies (such as the US Equal Employment Opportunity Commission) evaluate relative selection ratios: $\text{Selection Ratio} = \frac{\min_a P(\hat{Y}=1 \mid A=a)}{\max_a P(\hat{Y}=1 \mid A=a)}$. Under the four-fifths rule, a selection rate for any protected group that is less than 80% ($0.80$) of the rate for the group with the highest selection rate is treated as prima facie evidence of adverse impact.
-
Mechanics of Paired Bootstrap Resampling: When evaluating $M$ counterfactual prompt pairs, output score differences $\delta_i = S(x_i^{(A)}) - S(x_i^{(B)})$ are inherently paired. Calculating standard independent two-sample $t$-tests overestimates variance by ignoring the shared context within each pair. Practitioners generate $B = 1,000$ paired bootstrap replicates: drawing $M$ pairs with replacement, computing mean difference $\bar{\delta}_b$, and establishing the 2.5th and 97.5th percentiles to construct an empirical 95% confidence interval.
-
Mitigating Evaluation Contamination in Prompt Judges: When using automated language models to score generated counterfactual outputs, the evaluator model may harbor its own demographic preconceptions. To guarantee evaluation integrity, prompts are stripped of all demographic tokens and named entities before scoring, presenting the judge model with strictly sanitized, unbranded text.
-
The Tension Between Group and Individual Fairness: Group fairness metrics enforce parity across aggregate population cohorts, but can inadvertently treat similarly situated individuals differently across group boundaries—violating individual fairness formulations which state that similar individuals should receive similar outcomes. In automated credit scoring or risk prioritization, achieving demographic parity when historical features diverge necessitates setting group-specific threshold adjustments. ML teams must document these trade-offs transparently in compliance reviews.
-
Intersectional Slicing and Compounding Disparities: Single-attribute evaluations (auditing gender or age independently) frequently mask severe compounded disparities experienced by intersectional subgroups, such as young minority applicants or elderly rural residents.
MetricFramesupports multi-dimensional sensitive feature tuples (sensitive_features=[df['gender'], df['race']]), exposing sub-segment error rate spikes that aggregate marginals conceal. Production audits require multi-attribute slicing whenever cell counts satisfy minimum statistical power criteria.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from fairlearn.metrics import (
MetricFrame,
selection_rate,
demographic_parity_difference,
)
np.random.seed(42)
n = 2000
group = np.random.binomial(1, 0.4, n)
credit = np.random.normal(650, 50, n)
income = np.random.normal(50000, 15000, n)
# True label with subtle disparity
prob = 1 / (1 + np.exp(-((credit - 630)/40 + (income - 45000)/20000 + 0.3 * group)))
y = (np.random.rand(n) < prob).astype(int)
X = pd.DataFrame({"credit": credit, "income": income})
clf = RandomForestClassifier(n_estimators=30, max_depth=4, random_state=42)
clf.fit(X, y)
y_pred = clf.predict(X)
mf = MetricFrame(
metrics=selection_rate,
y_true=y,
y_pred=y_pred,
sensitive_features=group,
)
dpd = demographic_parity_difference(y, y_pred, sensitive_features=group)
print("=== FAIRLEARN AUDIT REPORT ===")
print(f"Overall Selection Rate: {selection_rate(y, y_pred):.4f}")
print(f"Group 0 Selection Rate: {mf.by_group[0]:.4f} (N={np.sum(group == 0)})")
print(f"Group 1 Selection Rate: {mf.by_group[1]:.4f} (N={np.sum(group == 1)})")
print(f"Demographic Parity Diff: {dpd:.4f}")=== FAIRLEARN AUDIT REPORT ===
Overall Selection Rate: 0.7290
Group 0 Selection Rate: 0.7117 (N=1183)
Group 1 Selection Rate: 0.7540 (N=817)
Demographic Parity Diff: 0.042202. Practice check
03. Apply it
When evaluating fairness across machine learning models:
- Disaggregate Beyond Overall Accuracy: Always compute metrics (selection rate, precision, recall, false positive rate) across relevant protected groups using
fairlearn.metrics.MetricFrame. - Report Group Sample Counts and Confidence Intervals: Never publish raw point estimates for small sub-populations without sample sizes ($N$) and standard errors or bootstrap intervals.
- Isolate Variables in Generative Testing: When probing generative text models, construct paired counterfactual prompts where qualifications, work history, and formatting are strictly identical.
- Score Counterfactuals with Group-Blind Judges: Apply deterministic rubrics or automated classifiers that are blind to the candidate demographic attribute to avoid introducing judge bias.
04. Review prompt
Differentiate mathematically between demographic parity difference and equalized odds difference. Why does demographic parity not require ground-truth labels while equalized odds does? How do you construct and score a counterfactual prompt evaluation for generative AI systems?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.