Sub topic 14
Mitigation: pre-, in-, and post-processing
This chapter assumes you can compute per-group selection rate, TPR, FPR, and precision, and that you know the group fairness criteria from the earlier chapters (demographic parity, equalized odds, predictive parity). It also assumes you have run a fairness audit. You need working Python with NumPy, scikit-learn, and Fairlearn.
What mitigation is for
Mitigation changes a system so that a measured gap between groups shrinks. It follows the audit and does not replace it. Mitigation comes with three caveats:
- It targets one criterion that you chose on purpose. Because the criteria conflict (see the impossibility chapter), improving one often worsens another.
- It usually costs some overall accuracy, though sometimes very little.
- It cannot fix a problem in the data collection or in how the model is deployed. If the labels themselves encode past discrimination, a mitigation that matches those labels only matches the bias.
Treat mitigation as a trade-off you must justify and record, not as a switch that makes a model "fair".
Three places to intervene
Mitigation methods are grouped by where they act in the pipeline.
| Family | What changes | Needs model access? | Needs group label at prediction time? | Main risk |
|---|---|---|---|---|
| Pre-processing | Training data or sample weights | No, any learner works | No | Downstream model can still reintroduce the gap |
| In-processing | The training objective or constraints | Yes, you control training | No | Slower, tied to specific learners, tuning is harder |
| Post-processing | Scores or decisions after training | No, works on a trained model | Usually yes | Treats groups differently at decision time |
Pre-processing
Pre-processing edits the data before any model sees it. Common techniques are:
- Reweighing. Give each (group, label) combination a weight so that group and label look statistically independent in the training set.
- Resampling. Oversample under-represented (group, label) cells or undersample over-represented ones.
- Relabeling or repair. Change suspect labels or transform features to remove group information. This is the most aggressive option, and it needs strong evidence that the labels are wrong.
Reweighing assigns each row the weight
w(g, y) = P(group = g) · P(label = y) / P(group = g, label = y)
If a cell such as (group B, positive) is rarer than independence would predict, its rows get a weight above 1. This pushes the model toward demographic parity in its training signal. It does not guarantee parity in predictions, because the model can still learn group information from correlated features (proxies).
In-processing
In-processing builds the fairness goal into training. Fairlearn's reductions approach, ExponentiatedGradient, wraps an ordinary scikit-learn estimator. It trains it repeatedly with adjusted sample weights until the predictor satisfies a constraint such as DemographicParity or EqualizedOdds, within a tolerance. The result is a randomized mixture of several classifiers, so two calls to predict can in principle differ unless you account for that.
Other in-processing methods add a fairness penalty to the loss, or train an adversary that tries to guess the group from the model's output while the main model learns to prevent it. These give finer control, but they depend on the learner and need more tuning.
Post-processing
Post-processing takes a trained model as fixed and adjusts its outputs. Fairlearn's ThresholdOptimizer learns a decision threshold per group, possibly with randomization between two thresholds, so that the chosen criterion holds on the training data. Its main advantages are that you can apply it to a model you cannot retrain and that the effect is easy to inspect.
Its main drawback is that it usually needs the sensitive attribute at prediction time. That can be legally or ethically problematic: in some jurisdictions and domains, explicitly different treatment by group is restricted even when the aim is to reduce a disparity. Confirm with legal and policy owners before using it.
A worked comparison
The script below builds synthetic data where group B's main feature is shifted, trains a baseline, and applies one method from each family. It then compares the gaps. It runs as written with NumPy, scikit-learn, and Fairlearn installed.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from fairlearn.metrics import (
demographic_parity_difference,
equalized_odds_difference,
)
from fairlearn.postprocessing import ThresholdOptimizer
from fairlearn.reductions import EqualizedOdds, ExponentiatedGradient
rng = np.random.default_rng(0)
n = 6000
group = rng.choice(["A", "B"], size=n, p=[0.65, 0.35])
x1 = rng.normal(size=n) - 0.6 * (group == "B")
x2 = rng.normal(size=n)
y = (x1 + 0.5 * x2 + rng.normal(scale=1.0, size=n) > 0).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
)
def reweigh(y, g):
"""Weight each (group, label) cell so group and label look independent."""
w = np.empty(len(y))
for gv in np.unique(g):
for yv in (0, 1):
cell = (g == gv) & (y == yv)
w[cell] = (g == gv).mean() * (y == yv).mean() / cell.mean()
return w
def report(name, y_pred):
dp = demographic_parity_difference(y_te, y_pred, sensitive_features=g_te)
eo = equalized_odds_difference(y_te, y_pred, sensitive_features=g_te)
acc = accuracy_score(y_te, y_pred)
print(f"{name:14s} acc={acc:.3f} DP gap={dp:.3f} EO gap={eo:.3f}")
# Baseline
base = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
report("baseline", base.predict(X_te))
# Pre-processing: reweighing
pre = LogisticRegression(max_iter=1000)
pre.fit(X_tr, y_tr, sample_weight=reweigh(y_tr, g_tr))
report("reweighing", pre.predict(X_te))
# In-processing: constrained training
inp = ExponentiatedGradient(
LogisticRegression(max_iter=1000), constraints=EqualizedOdds()
)
inp.fit(X_tr, y_tr, sensitive_features=g_tr)
report("in-processing", inp.predict(X_te))
# Post-processing: group-specific thresholds
post = ThresholdOptimizer(
estimator=LogisticRegression(max_iter=1000),
constraints="equalized_odds",
predict_method="predict_proba",
)
post.fit(X_tr, y_tr, sensitive_features=g_tr)
report("post-processing", post.predict(X_te, sensitive_features=g_te, random_state=0))When you run it, read the output as a table of trade-offs. Look for these patterns:
- Reweighing targets demographic parity, so it tends to move the DP gap more than the EO gap.
- The in-processing and post-processing methods target equalized odds, so the EO gap should fall most for them.
- Accuracy usually changes slightly. Here, the true base rates differ by group, so forcing equal selection rates and equalized odds cannot both be achieved at no cost.
Your exact numbers depend on the library versions and the random seed. Do not compare them from a single run.
Choosing a method
Work through these questions in order:
- Which criterion matters in this context? Pick it before picking a method. A screening tool that must not miss qualified people points to equal opportunity. A resource allocation tool may point to demographic parity.
- Can you retrain the model? If not, post-processing is the only option.
- Can you use the group label at decision time? If not, rule out group-specific thresholds. Pre- and in-processing use the group only during training.
- Is the label trustworthy? If the labels are biased, criteria built on them (equalized odds, equal opportunity) can lock in that bias. Consider fixing the labels or the data collection first.
- How much data does each group have? Methods that tune per-group parameters overfit when a group is small. Use the uncertainty tools from the earlier chapter.
Common errors
- Reporting only the targeted metric. After mitigation, re-run the full audit. Check accuracy, calibration by group, the other fairness gaps, and intersectional subgroups.
- Dropping the sensitive column and calling it done. Removing the attribute ("fairness through unawareness") leaves proxies such as postal code, so it rarely closes gaps. It also stops you from measuring them.
- Ignoring randomization.
ThresholdOptimizerandExponentiatedGradientcan give randomized predictions. Fix the seed for reproducible audits, and explain to stakeholders that identical applicants may receive different outcomes. - Treating a smaller gap as success. A gap going from 0.12 to 0.04 may still be inside the noise for a small group. Compare against a confidence interval.
- Forgetting drift. Thresholds and weights fitted today assume today's base rates. Monitor group metrics after deployment and re-fit under change control.
Exercise
A hiring-screen model is already deployed from a vendor. You can read its scores but cannot retrain it, and policy forbids using the applicant's group at decision time. Which mitigation family can you use, and what would you do instead of group-specific thresholds?
Show answer
Pre-processing and in-processing both require retraining, which the vendor model does not allow, so they are out. Post-processing is the only family that works on a fixed model, but group-specific thresholds need the group label at prediction time, which policy forbids. The remaining option is a post-processing adjustment that does not use the group, such as one shared threshold chosen to reduce the gap as far as possible, combined with a request to the vendor for retraining or a replacement. Whatever you choose, record the residual gap and its uncertainty in the model documentation.
Exercise
After reweighing, the demographic parity gap drops from 0.15 to 0.03, but the equalized odds gap rises from 0.05 to 0.09. Explain why this can happen and what you should do next.
Show answer
Reweighing pushes the training signal toward independence between group and label, which targets selection rates (demographic parity). If the true base rates differ between groups, equal selection rates force the model to accept more false positives in one group or miss more true positives in the other, which raises the TPR or FPR gap. This is the conflict between criteria. Next, decide which criterion fits the deployment context, then use a method that targets it, such as an equalized-odds constraint. Re-run the full audit and report both gaps with confidence intervals.