Sub topic 6
Equal opportunity and equalized odds
This chapter assumes you can read a confusion matrix and know that true positive rate (TPR) is recall and false positive rate (FPR) is FP / (FP + TN). It also assumes you have used NumPy and scikit-learn. The previous chapters covered per-group rates and demographic parity. Here you will use the label-conditioned criteria.
Why condition on the true label
Demographic parity compares selection rates and ignores the true outcome. If the groups differ in how many people are truly positive, a perfect classifier fails demographic parity. Equal opportunity and equalized odds avoid this by comparing error rates among people with the same true label.
- Equal opportunity asks that people who truly have the positive outcome are found at the same rate in every group. Formally, TPR is equal across groups:
P(Ŷ=1 | Y=1, A=a)is the same for every groupa. - Equalized odds adds the negative side. TPR and FPR must both be equal across groups:
P(Ŷ=1 | Y=y, A=a)is the same for every groupa, for bothy=1andy=0.
Equal opportunity is therefore a relaxation of equalized odds. It constrains one row of the confusion matrix (the actual positives), and equalized odds constrains both rows.
| Criterion | Rates that must match across groups | Cost it targets |
|---|---|---|
| Equal opportunity | TPR | Qualified people being missed (false negatives) |
| Equalized odds | TPR and FPR | Missed positives and wrongly flagged negatives |
Choosing between them
The choice depends on who bears the harm. Take a loan model where approval is the benefit. Missing creditworthy applicants in one group is the main harm, so equal opportunity fits. Now take a fraud or risk-flagging model where being flagged is the burden. FPR is the harm to people who did nothing wrong, so you need the FPR side as well, and equalized odds fits better.
Computing the gaps
The helper below computes TPR and FPR per group. It then reports the largest gap between any two groups. That works for more than two groups, where comparing only "A" and "B" would not.
import numpy as np
def tpr_fpr_by_group(y_true, y_pred, group):
y_true, y_pred, group = map(np.asarray, (y_true, y_pred, group))
rates = {}
for g in np.unique(group):
m = group == g
yt, yp = y_true[m], y_pred[m]
rates[g] = {
"tpr": yp[yt == 1].mean() if (yt == 1).any() else float("nan"),
"fpr": yp[yt == 0].mean() if (yt == 0).any() else float("nan"),
}
return rates
def max_gap(rates, key):
vals = [r[key] for r in rates.values()]
return np.nanmax(vals) - np.nanmin(vals)
# Group A: 10 positives, 10 negatives. TPR = 8/10, FPR = 2/10.
y_true_a = np.array([1] * 10 + [0] * 10)
y_pred_a = np.array([1] * 8 + [0] * 2 + [1] * 2 + [0] * 8)
# Group B: 10 positives, 10 negatives. TPR = 5/10, FPR = 1/10.
y_true_b = np.array([1] * 10 + [0] * 10)
y_pred_b = np.array([1] * 5 + [0] * 5 + [1] * 1 + [0] * 9)
y_true = np.concatenate([y_true_a, y_true_b])
y_pred = np.concatenate([y_pred_a, y_pred_b])
group = np.array(["A"] * 20 + ["B"] * 20)
rates = tpr_fpr_by_group(y_true, y_pred, group)
for g, r in rates.items():
print(g, f"TPR={r['tpr']:.2f}", f"FPR={r['fpr']:.2f}")
tpr_gap = max_gap(rates, "tpr")
fpr_gap = max_gap(rates, "fpr")
print(f"equal opportunity gap: {tpr_gap:.2f}")
print(f"equalized odds gap: {max(tpr_gap, fpr_gap):.2f}")The output is:
A TPR=0.80 FPR=0.20
B TPR=0.50 FPR=0.10
equal opportunity gap: 0.30
equalized odds gap: 0.30Group B's qualified members are found 30 percentage points less often. Group B also has a lower FPR, so the model is stricter for B in both directions. This is the typical pattern when B's scores sit lower and a single threshold is applied to everyone.
How thresholds create these gaps
A classifier that outputs scores turns them into decisions with a threshold. If the score distributions for qualified people differ by group, one shared threshold gives different TPRs. Moving the threshold for one group trades TPR against FPR along that group's ROC curve.
Equalized odds asks for a point where both groups' ROC curves meet at the same (FPR, TPR) coordinates. That point may not exist for deterministic thresholds. If the groups' ROC curves differ, the only shared achievable points can be worse than what either group could reach alone. Randomizing between two thresholds fills in the region below the curve, which is why post-processing methods use randomization.
Mitigating with threshold optimization
Fairlearn's ThresholdOptimizer learns group-specific thresholds on top of a trained model to satisfy equalized odds. This example is self-contained. It builds synthetic data in which group B's first feature is shifted, then compares the plain model with the adjusted one.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from fairlearn.metrics import equalized_odds_difference
from fairlearn.postprocessing import ThresholdOptimizer
rng = np.random.default_rng(0)
X, y = make_classification(n_samples=4000, n_features=6, random_state=0)
group = rng.choice(["A", "B"], size=len(y), p=[0.7, 0.3])
X[group == "B", 0] += 1.0 # 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.4, random_state=0, stratify=y
)
base = LogisticRegression(max_iter=1000).fit(X_train, y_train)
before = equalized_odds_difference(
y_test, base.predict(X_test), sensitive_features=g_test
)
mitigator = ThresholdOptimizer(
estimator=LogisticRegression(max_iter=1000),
constraints="equalized_odds",
predict_method="predict_proba",
)
mitigator.fit(X_train, y_train, sensitive_features=g_train)
y_adj = mitigator.predict(X_test, sensitive_features=g_test, random_state=0)
after = equalized_odds_difference(y_test, y_adj, sensitive_features=g_test)
print(f"equalized odds difference before: {before:.3f}")
print(f"equalized odds difference after: {after:.3f}")The exact numbers depend on your library versions. The "after" value should usually be smaller. Fairlearn's equalized_odds_difference returns the larger of the TPR and FPR gaps, matching the definition used above. Afterwards, re-run your full audit. Equalizing error rates can change accuracy, selection rates, and precision per group.
Post-processing also needs the sensitive attribute at prediction time. If you cannot use it when deciding, this method is not available to you.
Edge cases and common errors
- Trusting the label. Both criteria treat
Yas ground truth. IfYis "was arrested" or "was hired" and those outcomes were shaped by biased decisions, equal TPR can reproduce the bias. State what the label really measures. - Empty or tiny positive classes. TPR for a group is computed only from its positives. With 12 positives, one extra miss moves TPR by about 8 points. Report the count of positives and negatives per group, and add confidence intervals (see the chapter on uncertainty and small subgroups).
- Undefined rates. A group with no positives has no TPR. The helper above returns
nanandmax_gapskips it. Do not silently report a gap of zero. - Equal gaps from the wrong side. A model can have a small TPR gap and a large FPR gap. Reporting only equal opportunity would hide it, so say which criterion you checked.
- Different base rates. If the groups' base rates differ and the classifier is imperfect, equalized odds usually conflicts with predictive parity. The impossibility chapter covers this.
- Choosing a tolerance. Exact equality is rare. Set an acceptable gap (for example 0.05) before looking at results, and justify it by the decision context and by sampling noise.
- Evaluating on training data. Compute gaps on held-out data. Training-set rates are optimistic and can show smaller gaps than users will see.
Interpreting what you found
Equal opportunity says nothing about whether the positives were chosen well. It also says nothing about how many people outside the positive class are flagged. A model can satisfy it and still have a much higher FPR for one group. Equalized odds says nothing about individual fairness or about whether a group's real need is met. Treat each criterion as a measurement that answers one question, and record the others you did not satisfy.
Exercise
A hiring model has these test results. Group X: 40 qualified applicants, 30 selected; 160 unqualified, 16 selected. Group Y: 20 qualified, 10 selected; 80 unqualified, 8 selected. Compute the TPR and FPR for each group, then state the equal opportunity gap and the equalized odds gap (using the larger of the two gaps). Does the model satisfy equal opportunity at a tolerance of 0.05?
Show answer
Group X: TPR = 30/40 = 0.75, FPR = 16/160 = 0.10. Group Y: TPR = 10/20 = 0.50, FPR = 8/80 = 0.10. The equal opportunity gap is 0.75 - 0.50 = 0.25. The FPR gap is 0.00, so the equalized odds gap is max(0.25, 0.00) = 0.25. The model fails equal opportunity at a tolerance of 0.05. Group Y has only 20 qualified applicants, so a 0.25 gap should still be reported with a confidence interval before drawing a conclusion.
Exercise
Why can a perfect classifier satisfy equalized odds but fail demographic parity?
Show answer
A perfect classifier has TPR = 1 and FPR = 0 in every group, so equalized odds holds. Its selection rate equals each group's base rate of positives. If the base rates differ between groups, the selection rates differ, so demographic parity fails.