Phase 2: Bias Detection & Fairness Metrics · 45 min · Python · pandas · scikit-learn
The Problem
In Lesson 1, you identified where bias comes from. Now you need to measure it. But here's the hard part: there is no single "fairness score." There are at least 4 metrics that measure different things, and they can disagree. A model that looks fair by one metric can look biased by another — and both can be mathematically correct.
This is what made the COMPAS debate so contentious. ProPublica said COMPAS was biased because it had unequal false positive rates across races (an equalized odds problem). Northpointe said COMPAS was fair because it had equal positive predictive values across races (a predictive parity argument). Both were right. The disagreement wasn't about the math — it was about which definition of fairness matters for a criminal justice context.
The 4 core fairness metrics
1. Demographic Parity (Statistical Parity)
Definition: The model's positive prediction rate should be equal across groups.
Formula: P(ŷ = 1 | A = group_a) = P(ŷ = 1 | A = group_b)
When it matters: When the base rate of the outcome should be equal across groups — e.g., hiring, where you believe qualified candidates exist at equal rates across groups.
When it fails: When base rates legitimately differ — e.g., a medical model predicting pregnancy should not have demographic parity across sexes.
2. Equalized Odds
Definition: The model's true positive rate AND false positive rate should be equal across groups.
Formula: TPR(A = a) = TPR(A = b) AND FPR(A = a) = FPR(A = b)
When it matters: When the model's errors should be distributed equally across groups — e.g., criminal justice, where a false positive means someone is wrongly denied freedom.
3. Equal Opportunity
Definition: A relaxed version of equalized odds — only the true positive rate needs to be equal.
Formula: TPR(A = a) = TPR(A = b)
When it matters: When you care about equal access to positive outcomes but are less concerned about false positives — e.g., loan approval where you want equal opportunity to get a loan.
4. Disparate Impact Ratio (The 80% Rule)
Definition: The ratio of the positive prediction rate for the disadvantaged group to the advantaged group should be ≥ 0.80.
Formula: P(ŷ = 1 | A = disadvantaged) / P(ŷ = 1 | A = advantaged) ≥ 0.80
When it matters: This is the legal standard in the U.S. — the EEOC's "80% rule" used in employment discrimination cases. If your model's selection rate for a protected group is less than 80% of the rate for the advantaged group, it creates a presumption of disparate impact.
The 80% rule is law, not theory
The EEOC's 80% rule (formally the "four-fifths rule") is codified in the Uniform Guidelines on Employee Selection Procedures (29 CFR § 1607.4(D)). It's used in employment discrimination cases. If your hiring model selects women at a rate less than 80% of the rate for men, you have a prima facie case of disparate impact. This is not an academic metric — it's a legal standard.
The Concept
Chouldechova's theorem: why you can't have it all
Alex Chouldechova proved in 2017 that when base rates differ across groups (and they always do in real data), you cannot simultaneously satisfy:
- Equalized odds (equal TPR and FPR across groups)
- Predictive parity (equal PPV across groups)
- Calibration (equal predicted probabilities across groups)
Any two of these can be satisfied, but not all three. This means:
- You must choose which fairness definition matters for your use case
- Someone else can choose a different definition and show your model is unfair
- The choice of fairness metric is a policy decision, not a technical one
For a criminal justice tool like COMPAS, the debate was:
- ProPublica chose equalized odds → COMPAS is biased
- Northpointe chose predictive parity → COMPAS is fair
- The Wisconsin Supreme Court upheld COMPAS, effectively choosing predictive parity
You're building a loan approval model. The base rate of loan repayment is 85% for Group A and 70% for Group B. You compute both demographic parity and equalized odds. Demographic parity says the model is biased (Group A gets approved 80% of the time, Group B 60%). Equalized odds says the model is fair (TPR and FPR are equal across groups). Which metric should you use for this use case, and why?
When base rates legitimately differ, demographic parity is the wrong metric — it would force the model to approve Group B applicants at the same rate as Group A, even though Group B has a lower repayment rate. This would mean approving more risky loans in Group B, which is both financially unsound and arguably patronizing (it assumes Group B can't be held to the same standard). Equalized odds is the right choice: it says "the model should be equally accurate for both groups" — same true positive rate (qualified applicants approved at the same rate) and same false positive rate (unqualified applicants rejected at the same rate). The disparate impact ratio is still worth computing for legal compliance, but the fairness judgment should be based on equalized odds when base rates differ.
Building a fairness metrics calculator
Let's build the metrics calculator from scratch — no libraries, just the math. This ensures you understand exactly what each metric measures before we use Fairlearn in the next lesson.
"""
lesson_01_02_fairness_metrics_calculator.py
Computes 4 core fairness metrics from scratch (no Fairlearn/AIF360).
"""
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
def compute_confusion_matrix(y_true, y_pred):
"""Compute confusion matrix components."""
tp = int(((y_pred == 1) & (y_true == 1)).sum())
fp = int(((y_pred == 1) & (y_true == 0)).sum())
fn = int(((y_pred == 0) & (y_true == 1)).sum())
tn = int(((y_pred == 0) & (y_true == 0)).sum())
return {"tp": tp, "fp": fp, "fn": fn, "tn": tn}
def demographic_parity(y_pred, groups):
"""
Demographic parity: positive prediction rate should be equal across groups.
Returns: dict with per-group selection rates and the difference.
"""
rates = {}
for group in sorted(groups.unique()):
mask = groups == group
rates[group] = round(y_pred[mask].mean(), 4)
max_rate = max(rates.values())
min_rate = min(rates.values())
difference = round(max_rate - min_rate, 4)
return {
"selection_rates": rates,
"demographic_parity_difference": difference,
"passes": difference < 0.05, # threshold: 5pp difference
}
def equalized_odds(y_true, y_pred, groups):
"""
Equalized odds: TPR and FPR should be equal across groups.
Returns: dict with per-group TPR, FPR, and the differences.
"""
tpr_by_group = {}
fpr_by_group = {}
for group in sorted(groups.unique()):
mask = groups == group
cm = compute_confusion_matrix(y_true[mask], y_pred[mask])
tpr = cm["tp"] / (cm["tp"] + cm["fn"]) if (cm["tp"] + cm["fn"]) > 0 else 0
fpr = cm["fp"] / (cm["fp"] + cm["tn"]) if (cm["fp"] + cm["tn"]) > 0 else 0
tpr_by_group[group] = round(tpr, 4)
fpr_by_group[group] = round(fpr, 4)
tpr_diff = round(max(tpr_by_group.values()) - min(tpr_by_group.values()), 4)
fpr_diff = round(max(fpr_by_group.values()) - min(fpr_by_group.values()), 4)
return {
"tpr_by_group": tpr_by_group,
"fpr_by_group": fpr_by_group,
"equalized_odds_difference": max(tpr_diff, fpr_diff),
"tpr_difference": tpr_diff,
"fpr_difference": fpr_diff,
"passes": tpr_diff < 0.05 and fpr_diff < 0.05,
}
def equal_opportunity(y_true, y_pred, groups):
"""
Equal opportunity: TPR should be equal across groups.
Relaxed version of equalized odds (only TPR, not FPR).
"""
tpr_by_group = {}
for group in sorted(groups.unique()):
mask = groups == group
cm = compute_confusion_matrix(y_true[mask], y_pred[mask])
tpr = cm["tp"] / (cm["tp"] + cm["fn"]) if (cm["tp"] + cm["fn"]) > 0 else 0
tpr_by_group[group] = round(tpr, 4)
tpr_diff = round(max(tpr_by_group.values()) - min(tpr_by_group.values()), 4)
return {
"tpr_by_group": tpr_by_group,
"equal_opportunity_difference": tpr_diff,
"passes": tpr_diff < 0.05,
}
def disparate_impact_ratio(y_pred, groups):
"""
Disparate impact ratio: ratio of selection rates.
EEOC 80% rule: ratio >= 0.80 for compliance.
"""
rates = {}
for group in sorted(groups.unique()):
mask = groups == group
rates[group] = y_pred[mask].mean()
max_rate = max(rates.values())
min_rate = min(rates.values())
ratio = round(min_rate / max_rate, 4) if max_rate > 0 else 0
return {
"selection_rates": {k: round(v, 4) for k, v in rates.items()},
"disparate_impact_ratio": ratio,
"passes_80_percent_rule": ratio >= 0.80,
}
def compute_all_metrics(y_true, y_pred, groups, protected_attribute_name="group"):
"""Compute all 4 fairness metrics and return a combined report."""
dp = demographic_parity(y_pred, groups)
eo = equalized_odds(y_true, y_pred, groups)
eop = equal_opportunity(y_true, y_pred, groups)
di = disparate_impact_ratio(y_pred, groups)
return {
"protected_attribute": protected_attribute_name,
"demographic_parity": dp,
"equalized_odds": eo,
"equal_opportunity": eop,
"disparate_impact": di,
"overall_pass": all([dp["passes"], eo["passes"], di["passes_80_percent_rule"]]),
}
def generate_metrics_report(metrics, model_accuracy=None):
"""Generate a formatted fairness metrics report."""
lines = []
lines.append("# Fairness Metrics Report\n")
if model_accuracy:
lines.append(f"**Model accuracy:** {model_accuracy:.2%}\n")
pa = metrics["protected_attribute"]
lines.append(f"**Protected attribute:** {pa}\n")
# Demographic Parity
dp = metrics["demographic_parity"]
lines.append("## Demographic Parity\n")
lines.append("| Group | Selection Rate |")
lines.append("|---|---|")
for group, rate in dp["selection_rates"].items():
lines.append(f"| {group} | {rate:.2%} |")
lines.append(f"\n**Difference:** {dp['demographic_parity_difference']:.4f}")
lines.append(f"**Passes (≤0.05):** {'✅' if dp['passes'] else '❌'}\n")
# Equalized Odds
eo = metrics["equalized_odds"]
lines.append("## Equalized Odds\n")
lines.append("| Group | TPR | FPR |")
lines.append("|---|---|---|")
for group in eo["tpr_by_group"]:
lines.append(f"| {group} | {eo['tpr_by_group'][group]:.4f} | {eo['fpr_by_group'][group]:.4f} |")
lines.append(f"\n**TPR difference:** {eo['tpr_difference']:.4f}")
lines.append(f"**FPR difference:** {eo['fpr_difference']:.4f}")
lines.append(f"**Passes (both ≤0.05):** {'✅' if eo['passes'] else '❌'}\n")
# Disparate Impact
di = metrics["disparate_impact"]
lines.append("## Disparate Impact Ratio (80% Rule)\n")
lines.append("| Group | Selection Rate |")
lines.append("|---|---|")
for group, rate in di["selection_rates"].items():
lines.append(f"| {group} | {rate:.2%} |")
lines.append(f"\n**DI ratio:** {di['disparate_impact_ratio']:.4f}")
lines.append(f"**Passes (≥0.80):** {'✅' if di['passes_80_percent_rule'] else '❌'}\n")
# Overall
lines.append("## Overall Assessment\n")
lines.append(f"**All metrics pass:** {'✅' if metrics['overall_pass'] else '❌'}")
if not metrics["overall_pass"]:
lines.append("\n### Failed metrics:")
if not dp["passes"]:
lines.append("- Demographic parity: selection rates differ by more than 5pp")
if not eo["passes"]:
lines.append("- Equalized odds: TPR or FPR differs by more than 5pp across groups")
if not di["passes_80_percent_rule"]:
lines.append("- Disparate impact: ratio below 0.80 (EEOC violation)")
lines.append("\n## Note on Metric Conflicts")
lines.append("If metrics disagree (e.g., equalized odds passes but demographic parity fails), "
"this is expected — Chouldechova's theorem proves that when base rates differ, "
"not all fairness definitions can be satisfied simultaneously. The choice of which "
"metric matters is a policy decision, not a technical one.")
return "\n".join(lines)
if __name__ == "__main__":
# Generate a synthetic loan approval dataset
np.random.seed(42)
n = 3000
race = np.random.choice(["Group_A", "Group_B"], n, p=[0.6, 0.4])
income = np.where(race == "Group_A", np.random.normal(65000, 20000, n),
np.random.normal(48000, 18000, n))
credit_score = np.where(race == "Group_A", np.random.normal(720, 80, n),
np.random.normal(680, 90, n))
# Base rate of repayment differs (85% vs 70%)
repaid = np.where(
race == "Group_A",
np.random.binomial(1, 0.85, n),
np.random.binomial(1, 0.70, n),
)
df = pd.DataFrame({
"race": race,
"income": income.clip(15000, 200000).astype(int),
"credit_score": credit_score.clip(300, 850).astype(int),
"repaid": repaid,
})
# Train a model
X = df[["income", "credit_score"]]
y = df["repaid"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = (y_pred == y_test).mean()
# Get test set groups
test_groups = df.loc[X_test.index, "race"]
# Compute all metrics
metrics = compute_all_metrics(
y_test.values, y_pred, test_groups,
protected_attribute_name="race"
)
report = generate_metrics_report(metrics, model_accuracy=accuracy)
with open("fairness_metrics_report.md", "w") as f:
f.write(report)
print(f"Model accuracy: {accuracy:.2%}")
print(f"Demographic parity diff: {metrics['demographic_parity']['demographic_parity_difference']}")
print(f"Equalized odds diff: {metrics['equalized_odds']['equalized_odds_difference']}")
print(f"Disparate impact ratio: {metrics['disparate_impact']['disparate_impact_ratio']}")
print(f"Overall pass: {metrics['overall_pass']}")
print("\nReport saved to fairness_metrics_report.md")
Common error — dividing by zero
When computing TPR or FPR, if a group has no positive (or negative) examples in the test set, you'll get a division by zero. The code above handles this with a conditional (if denominator > 0 else 0), but in practice you should check group sample sizes before computing metrics. A group with fewer than 30 samples in the test set will produce unreliable fairness metrics — always report sample sizes alongside the metrics.