Phase 2: Bias Detection & Fairness Metrics · 40 min · Python · pandas · scikit-learn
The Problem
In 2018, Amazon scrapped an AI recruiting tool they'd been building for four years. The system was supposed to rate job candidates from 1 to 5 stars. Instead, it systematically downgraded resumes that included the word "women's" — as in "captain of the women's chess club" — and penalized graduates of two all-women's colleges. The model had been trained on 10 years of Amazon's own hiring data, which was overwhelmingly male. It learned a simple lesson: men get hired, so male-looking resumes are better.
Amazon's engineers hadn't told the model to discriminate against women. They hadn't included gender as a feature. The model found gender anyway — through proxy variables like school names, sports teams, word choices, and resume formatting. This is the fundamental challenge of bias in ML: the bias is in the data, and the data reflects the world.
The 5 sources of bias
Bias in ML systems comes from 5 distinct sources. Understanding which source you're dealing with determines what mitigation strategy will work.
| Source | Where It Enters | Example | Mitigation Point |
|---|
| Historical | Training data reflects past discrimination | Amazon's hiring AI: 10 years of male-dominated hiring data taught it to prefer men | Pre-processing (reweighing) or in-processing (constraints) |
| Representation | Training data under-samples or over-samples certain groups | Facial recognition trained primarily on lighter-skinned faces fails on darker-skinned faces | Collect more representative data (pre-processing) |
| Measurement | The measurement process itself is biased | COMPAS uses arrest data, but arrest rates reflect policing patterns, not actual crime rates | Change the target variable or use proxy-corrected labels |
| Aggregation | A single model serves groups with different data distributions | A medical diagnosis model trained on adult data applied to children | Group-specific models or conditional models |
| Deployment | The model behaves differently in production than in testing | A loan model tested on historical data faces a different economic context in production | Post-deployment monitoring and drift detection |
Proxy variables are the core problem
Amazon removed gender from the training data. The model still discriminated against women. Why? Because gender is encoded in dozens of other features: school names, sports teams, resume length, word choice, gap years. These are "proxy variables" — features that correlate with the protected attribute without being the attribute itself. You cannot remove all proxies without removing most of the signal in your data. This is why bias detection requires measuring outcomes across protected groups, not just removing protected attributes from the input.
The Concept
The COMPAS case: identifying bias sources
Let's work through the COMPAS dataset to identify each bias source with evidence from the data.
"""
lesson_01_01_bias_source_identifier.py
Identifies the 5 sources of bias in the COMPAS recidivism dataset.
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
def load_compas_data():
"""
Load the COMPAS dataset. In a real lab, this would download from
https://github.com/propublica/compas-analysis/raw/master/compas-scores-two-years.csv
Here we use a synthetic version that preserves the key statistical properties.
"""
np.random.seed(42)
n = 6000
# Generate synthetic data matching COMPAS demographics
race = np.random.choice(
["African-American", "Caucasian", "Hispanic", "Other"],
n,
p=[0.51, 0.34, 0.09, 0.06],
)
sex = np.random.choice(["Male", "Female"], n, p=[0.81, 0.19])
age = np.random.normal(35, 11, n).clip(18, 80).astype(int)
# Historical bias: African-Americans have higher prior counts due to
# differential policing, not higher actual crime rates
priors_count = np.where(
race == "African-American",
np.random.poisson(2.5, n),
np.random.poisson(1.2, n),
)
# Measurement bias: COMPAS uses arrest data, which reflects policing patterns
# not actual recidivism
juv_fel_count = np.where(
race == "African-American",
np.random.poisson(0.15, n),
np.random.poisson(0.05, n),
)
# The actual recidivism (ground truth) — less skewed than the features
actual_recidivism = np.random.binomial(
1, np.clip(0.40 + priors_count * 0.03, 0, 0.85), n
)
# COMPAS predicted risk score (has historical bias baked in)
compas_score = np.clip(
np.random.normal(
np.where(race == "African-American", 5.5, 3.5) + priors_count * 0.5,
1.8,
n,
),
1, 10,
).astype(int)
# COMPAS binary prediction (high risk if score >= 7)
compas_prediction = (compas_score >= 7).astype(int)
df = pd.DataFrame({
"race": race,
"sex": sex,
"age": age,
"priors_count": priors_count,
"juv_fel_count": juv_fel_count,
"compas_score": compas_score,
"compas_prediction": compas_prediction,
"two_year_recid": actual_recidivism,
})
return df
def identify_bias_sources(df):
"""Identify and document each source of bias with evidence from the data."""
findings = []
# 1. Historical bias: prior counts differ by race
priors_by_race = df.groupby("race")["priors_count"].mean()
findings.append({
"source": "Historical",
"evidence": f"Average prior counts: {priors_by_race.to_dict()}",
"explanation": "African-Americans have higher average prior counts due to differential policing patterns, not higher actual crime rates. The training data encodes this historical inequality.",
"affected_feature": "priors_count",
})
# 2. Representation bias: sample sizes by race
counts_by_race = df["race"].value_counts()
findings.append({
"source": "Representation",
"evidence": f"Sample sizes: {counts_by_race.to_dict()}",
"explanation": f"Hispanic and Other groups are under-represented ({counts_by_race.get('Hispanic', 0)} and {counts_by_race.get('Other', 0)} samples vs. {counts_by_race.get('African-American', 0)} for African-American). The model will be less reliable for under-represented groups.",
"affected_feature": "race (distribution)",
})
# 3. Measurement bias: juv_fel_count reflects policing, not behavior
juv_by_race = df.groupby("race")["juv_fel_count"].mean()
findings.append({
"source": "Measurement",
"evidence": f"Average juvenile felony counts: {juv_by_race.to_dict()}",
"explanation": "Juvenile felony counts reflect arrest rates, which are influenced by policing patterns. Using arrest data as a proxy for actual behavior introduces measurement bias.",
"affected_feature": "juv_fel_count",
})
# 4. Aggregation bias: check if age distributions differ
age_by_race = df.groupby("race")["age"].mean()
findings.append({
"source": "Aggregation",
"evidence": f"Average ages: {age_by_race.to_dict()}",
"explanation": "If age distributions differ significantly across groups, a single model may not capture group-specific patterns. Check whether a single model serves all subgroups equally.",
"affected_feature": "age",
})
# 5. Deployment bias: COMPAS predictions vs actual recidivism
fpr_by_race = {}
fnr_by_race = {}
for r in df["race"].unique():
subset = df[df["race"] == r]
tp = ((subset["compas_prediction"] == 1) & (subset["two_year_recid"] == 1)).sum()
fp = ((subset["compas_prediction"] == 1) & (subset["two_year_recid"] == 0)).sum()
fn = ((subset["compas_prediction"] == 0) & (subset["two_year_recid"] == 1)).sum()
tn = ((subset["compas_prediction"] == 0) & (subset["two_year_recid"] == 0)).sum()
fpr_by_race[r] = round(fp / (fp + tn), 3) if (fp + tn) > 0 else 0
fnr_by_race[r] = round(fn / (fn + tp), 3) if (fn + tp) > 0 else 0
findings.append({
"source": "Deployment",
"evidence": f"False positive rates by race: {fpr_by_race}",
"explanation": f"COMPAS falsely flags African-Americans as high risk at a rate of {fpr_by_race.get('African-American', 0)} vs. {fpr_by_race.get('Caucasian', 0)} for Caucasians. This disparity emerges when the model is applied in practice.",
"affected_feature": "compas_prediction",
})
return findings
def generate_bias_report(findings, df):
"""Generate a structured bias source identification report."""
lines = []
lines.append("# Bias Source Identification Report — COMPAS Dataset\n")
lines.append(f"Total records analyzed: {len(df)}\n")
lines.append("## Identified Bias Sources\n")
for f in findings:
lines.append(f"### {f['source']} Bias")
lines.append(f"**Affected feature:** {f['affected_feature']}")
lines.append(f"**Evidence:** {f['evidence']}")
lines.append(f"**Explanation:** {f['explanation']}\n")
lines.append("## Summary\n")
sources_found = [f["source"] for f in findings]
lines.append(f"Bias sources identified: {', '.join(sources_found)}")
lines.append(f"Total sources found: {len(sources_found)} out of 5\n")
lines.append("## Recommended Next Steps")
lines.append("- Proceed to Lesson 2: Compute fairness metrics to quantify the bias")
lines.append("- Proceed to Lesson 3: Build a Fairlearn audit to produce structured evidence")
lines.append("- Proceed to Lesson 5: Apply mitigation techniques based on the identified sources")
return "\n".join(lines)
if __name__ == "__main__":
print("Loading COMPAS dataset...")
df = load_compas_data()
print(f"Loaded {len(df)} records")
print("\nIdentifying bias sources...")
findings = identify_bias_sources(df)
report = generate_bias_report(findings, df)
with open("bias_source_report.md", "w") as f:
f.write(report)
print(f"\nFound {len(findings)} bias sources:")
for finding in findings:
print(f" - {finding['source']}: {finding['evidence'][:80]}...")
print("\nReport saved to bias_source_report.md")
You're auditing a hiring model and find that the training data contains "years of experience" which correlates strongly with gender (women in this industry have fewer years on average due to historical exclusion from the field). What type of bias is this, and what would you do about it?
Historical bias is the correct diagnosis because the feature (years of experience) accurately measures what it claims to measure — the problem is that the underlying reality is shaped by historical discrimination. Women have fewer years of experience because they were historically excluded from the industry, not because they are less capable. The model learns "fewer years = lower hire probability" which perpetuates the historical pattern. This is exactly the Amazon case: the data reflected past discrimination, and the model learned to continue it. The mitigation is to either reweigh the data (pre-processing), add fairness constraints (in-processing), or adjust thresholds (post-processing) — all of which you'll build in Lesson 5.