Worked Example: Closing a Gap and Paying the Price
Evaluate algorithmic fairness mitigation strategies across the ML lifecycle, apply constrained optimization and post-processing threshold adjustments, and analyze Pareto trade-offs between group equity and aggregate accuracy.
Contentsand lesson path
On this page
- Mitigating Disparate Impact: The Pareto Frontier of Fairness and Accuracy
- Practice check
- Apply it
- Review prompt
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
- Apply one mitigation (reweighting, per-group thresholds or constrained training) and report its effect on both fairness and accuracy.
01. Mitigating Disparate Impact: The Pareto Frontier of Fairness and Accuracy
When a responsible ML audit identifies unacceptable performance or selection gaps across demographic subgroups, engineering teams must evaluate algorithmic mitigation techniques. However, algorithmic fairness is rarely a free lunch: reducing group disparities almost always involves navigating an empirical trade-off along a Pareto frontier between group fairness metrics and overall aggregate accuracy. Understanding where and how to intervene across the machine learning pipeline is essential for choosing an effective, operationally viable mitigation strategy.
-
The Lifecycle Taxonomy of Fairness Mitigation:
- 1. Pre-Processing Mitigations (Data-Level): Applied directly to the training dataset before model fitting. Techniques include sample reweighting (assigning higher loss weights to underrepresented group-label pairs, e.g., $(A=0, Y=1)$) or distribution transformation (e.g., Fairlearn's
CorrelationRemover, which projects numeric features onto the orthogonal complement of sensitive attributes). Pre-processing is model-agnostic and allows downstream teams to train arbitrary estimators, but it cannot guarantee exact fairness constraints on the final fitted decision boundary. - 2. In-Processing Mitigations (Optimization-Level): Incorporated directly into the model training objective as mathematical constraints. Algorithms such as Agarwal et al.'s Exponentiated Gradient Reduction frame fair training as a two-player game between an unconstrained learner and an adversary maximizing fairness violations under specified constraints (e.g., Demographic Parity or Equalized Odds). The algorithm iteratively yields a randomized ensemble or reweighted sequence of estimators that provably satisfies the fairness constraint while maximizing accuracy. In-processing produces high-performing models along the Pareto frontier but requires full model retraining and access to the training pipeline.
- 3. Post-Processing Mitigations (Decision-Level): Applied to the continuous probability scores or risk rankings emitted by an already trained, immutable model. Using tools like Fairlearn's
ThresholdOptimizer, practitioners learn group-specific classification thresholds (e.g., approving Group A candidates with scores above $0.48$ and Group B candidates with scores above $0.52$). Post-processing is uniquely powerful when the underlying model is a black-box third-party API or when retraining compute is prohibitively expensive, because it modifies decision thresholds without touching model weights.
- 1. Pre-Processing Mitigations (Data-Level): Applied directly to the training dataset before model fitting. Techniques include sample reweighting (assigning higher loss weights to underrepresented group-label pairs, e.g., $(A=0, Y=1)$) or distribution transformation (e.g., Fairlearn's
-
Analyzing the Pareto Frontier: In an unconstrained model, an optimization algorithm minimizes cross-entropy loss or squared error across the global population. Imposing an additional fairness constraint (e.g., bounding demographic parity difference to $\text{DPD} \le 0.03$) strictly restricts the hypothesis space. Consequently, empirical training accuracy will either remain flat or decrease. For example, applying constrained training may reduce demographic parity difference from $0.18$ down to $0.02$, while overall accuracy drops from $86%$ to $84%$. Deciding whether a 2-point accuracy sacrifice is an acceptable price for eliminating a 16-point selection disparity is an ethical, legal, and business governance decision, not a purely statistical calculation.
-
Reporting Fairness Interventions with Integrity: When publishing the results of an algorithmic mitigation, engineers must report comprehensive before-and-after evaluations on held-out test data. A compliant mitigation report includes: (1) Baseline accuracy and fairness metrics across all groups; (2) Post-mitigation accuracy and fairness metrics across all groups; (3) Confusion matrices per demographic slice; and (4) Stated legal and operational justifications for the selected threshold trade-off.
-
Legal and Regulatory Constraints on Group Thresholds: In certain jurisdictions and application domains, using explicit group membership $A$ at decision time is legally restricted or prohibited. Under Title VII of the US Civil Rights Act, applying explicitly different numerical cutoffs to job applicants based on protected traits can be challenged as intentional disparate treatment, even if designed to mitigate disparate impact. In such regulated settings, in-processing mitigations (such as adversarial training or representation disentanglement) that learn group-invariant internal representations without requiring sensitive attributes at test inference time are legally preferred.
-
Comparing Reduction Techniques (GridSearch vs ExponentiatedGradient): Fairlearn implements two primary reduction algorithms for in-processing constraints:
GridSearchevaluates an exhaustive sweep over candidate Lagrange multiplier weights, suitable for simple linear models with 1–2 constraints;ExponentiatedGradientdynamically adjusts dual multipliers using online no-regret learning, converging efficiently even for complex deep neural networks and multi-group intersectional constraints. -
Long-Term Dynamics and Feedback Loops: Fairness interventions designed as static one-shot optimizations can produce unexpected downstream equilibria over extended operational horizons. In consumer credit or educational admissions, altering selection thresholds alters qualification incentives and default dynamics among applicant cohorts. If credit is expanded without complementary financial support, elevated default rates can degrade subgroup credit histories over subsequent years, aggravating the very disparity the intervention sought to remedy. Responsible ML governance mandates tracking longitudinal cohort outcomes rather than relying solely on immediate one-step approval parity.
-
Operationalizing Constrained Inference in Production Serving: Deploying a
ThresholdOptimizeror a randomized ensemble produced byExponentiatedGradientintroduces operational latency and infrastructure dependencies. Ensembles produced by reduction algorithms require loading multiple sub-estimator checkpoints and executing weighted stochastic evaluations per incoming prediction. In microservices with strict sub-10ms SLAs, engineering teams frequently distill the constrained ensemble into a single compact student model or deploy pre-computed monotonic score calibration tables to preserve group thresholds without incurring runtime latency overhead.
import numpy as np
from sklearn.linear_model import LogisticRegression
from fairlearn.postprocessing import ThresholdOptimizer
from fairlearn.metrics import selection_rate, demographic_parity_difference
np.random.seed(42)
n = 2000
group = np.random.binomial(1, 0.4, n)
score = np.random.normal(0.5, 0.15, n) + 0.1 * group
X = score.reshape(-1, 1)
y = (np.random.rand(n) < score).astype(int)
# 1. Unconstrained baseline
base_clf = LogisticRegression()
base_clf.fit(X, y)
base_preds = base_clf.predict(X)
base_dpd = demographic_parity_difference(y, base_preds, sensitive_features=group)
base_acc = float(np.mean(base_preds == y))
# 2. Post-processing threshold optimization for demographic parity
post_opt = ThresholdOptimizer(
estimator=base_clf,
constraints="demographic_parity",
prefit=True,
)
post_opt.fit(X, y, sensitive_features=group)
post_preds = post_opt.predict(X, sensitive_features=group)
post_dpd = demographic_parity_difference(y, post_preds, sensitive_features=group)
post_acc = float(np.mean(post_preds == y))
print("=== MITIGATION PARETO AUDIT ===")
print(f"Baseline: DPD={base_dpd:.4f}, Accuracy={base_acc:.4f}")
print(f"Mitigated: DPD={post_dpd:.4f}, Accuracy={post_acc:.4f}")=== MITIGATION PARETO AUDIT ===
Baseline: DPD=0.1837, Accuracy=0.6935
Mitigated: DPD=0.0125, Accuracy=0.672002. Practice check
03. Apply it
When implementing fairness mitigation in production ML pipelines:
- Select the Appropriate Lifecycle Hook: Use pre-processing (reweighting) when you control data; use in-processing (exponentiated gradient) for maximum flexibility on trainable models; and use post-processing (threshold optimization) for fixed third-party estimators.
- Map the Full Pareto Frontier: Train models across multiple constraint tolerance levels ($\epsilon$) to plot accuracy versus parity difference, presenting stakeholders with transparent decision frontiers.
- Evaluate on Held-Out Validation Partitions: Always calibrate mitigation thresholds on training or validation splits and evaluate before-and-after metrics on held-out test splits to prevent overfitting to fairness constraints.
- Document Harms of False Positives vs False Negatives: Work with product and legal teams to analyze the real-world consequences of both error types for each demographic group when establishing acceptable thresholds.
04. Review prompt
Compare pre-processing, in-processing, and post-processing fairness mitigations across implementation complexity and operational constraints. Why does imposing a fairness constraint restrict the hypothesis space and move models along a Pareto frontier? How do you report mitigation trade-offs responsibly?
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.