The user wants a program to detect and mitigate bias in machine learning models.
1. Understanding the Request:
Goal: Detect and mitigate bias.
Context: Machine Learning (ML).
Output: A program (code).
Implicit Needs:
Needs to handle different types of bias (e.g., classification, fairness metrics).
Needs to show how to detect (metrics).
Needs to show how to mitigate (algorithms).
Needs a concrete example to be runnable and understandable.
Python is the standard language for this.
Key libraries: pandas, scikit-learn, and specifically fairlearn or aif360 (I'll use fairlearn as it integrates well with sklearn).
2. Structuring the Solution:
Introduction: Briefly explain that bias mitigation is a complex field, but the code will focus on a standard workflow: Load Data -> Train Baseline -> Detect Bias -> Mitigate Bias -> Re-evaluate.
Prerequisites: List necessary libraries (pip install...).
Step 1: Setup & Data: Create a synthetic dataset. Why synthetic? Because real datasets with sensitive attributes (gender, race) can be controversial or hard to access quickly in a code snippet. Using sklearn.make_classification and adding a random sensitive feature is a safe and reproducible approach.
Step 2: Baseline Model: Train a standard classifier (e.g., Logistic Regression) to show the "before" state.
Metric: Demographic Parity Difference or Equalized Odds Difference.
Tool:fairlearn.metrics.
Step 4: Mitigation (Algorithm): Apply a mitigation technique.
Technique: Exponentiated Gradient (reduction) or Grid Search are powerful. Or, for simplicity, a post-processing method like ThresholdOptimizer. Let's go with ExponentiatedGradient with DemographicParity constraint because it demonstrates in-processing mitigation well.
Step 5: Evaluation: Compare the metrics before and after.
Conclusion: Wrap up with ethical considerations (code isn't a magic bullet).
3. Drafting the Code (Mental or Scratchpad):
Imports:pandas, numpy, sklearn, fairlearn.
Data:
python
X, y = make_classification(...)
# Add a sensitive feature (e.g., 'gender': 0 or 1)
sensitive = np.random.randint(0, 2, size=len(y))
X['gender'] = sensitive
Split:train_test_split.
Model:LogisticRegression.
Detection:
python
from fairlearn.metrics import MetricFrame
# Need selection rate, accuracy, etc.
The prompt is broad ("Write a program"). I shouldn't just dump code. I need to explain what the code is doing.
I must explicitly mention that "bias" in ML usually refers to statistical bias towards specific groups (protected attributes).
I will use the fairlearn library. It's Microsoft-backed and very pythonic for this specific task.
5. Writing the Code (Iterative refinement):
Self-Correction during drafting: A full dataset is better than synthetic if I want to show realistic bias, but synthetic guarantees the code runs without downloading external files. I will stick to synthetic but make the "bias" intentional. Actually, making the label correlated with the sensitive feature in the synthetic data makes the problem more obvious. Let's do that.
Wait, if I just make random data, I might not see bias. To ensure the example works pedagogically, I'll simulate a hiring scenario where Group 1 is favored over Group 0.
6. Final Code Structure:
Install: Instructions for fairlearn.
Data Gen: Create X and y. Create sensitive_feature. Ensure y depends on sensitive_feature slightly to create bias.
Baseline: Train simple model.
Metric: Calculate MetricFrame.
Mitigation: Use ExponentiatedGradient.
Comparison: Print results.
7. Adding Explanations:
Explain Demographic Parity (the selection rate should be similar across groups).
Explain the difference between "Blind" models (ignoring the feature) and "Aware" models (fairness constraints). The code will use the "Aware" approach (mitigation).
8. Review against Safety Guidelines:
Does this promote discrimination? No, it creates a tool to fight discrimination.
Is the code harmful? No.
9. Final Polish: Ensure comments are clear, variable names are descriptive, and the output formatting is readable.
(Self-Correction during final polish): Using ThresholdOptimizer might be simpler to explain than ExponentiatedGradient for a general audience, but ExponentiatedGradient is often more robust. I'll stick with ExponentiatedGradient or GridSearch as they are common "in-processing" techniques. Let's stick to ExponentiatedGradient for a robust example.
Let's write the actual response now.
Writing a complete bias detection and mitigation program requires a specific context (e.g., gender bias in hiring, racial bias in lending).
Below is a comprehensive Python program using the Fairlearn library (a standard industry tool) and Scikit-Learn. This program generates a synthetic dataset simulating a hiring scenario, trains a model, detects bias, and then applies mitigation techniques.
Prerequisites
You will need to install the following libraries:
bash
pip install pandas numpy scikit-learn fairlearn
The Python Program
python
Explanation of the Code
1. Data Generation
We create a dataset with two legitimate features (experience, technical_score) and one sensitive feature (gender).
The Injection: In lines 39-40, we artificially add +15 points to the "internal score" for males. This means a male with the exact same qualifications as a female is more likely to be hired in the training data. This mimics "historical bias."
2. Detection (MetricFrame)
We use fairlearn.metrics.MetricFrame. This is a powerful tool that calculates any standard metric (Accuracy, Precision, etc.) but splits the results by your sensitive feature (Gender).
Selection Rate: The most critical metric here. If the selection rate for Group 1 is 0.60 and Group 0 is 0.30, the model is biased.
Disparity: We print metric_frame.difference(), which calculates the mathematical gap between the groups.
3. Mitigation (ExponentiatedGradient)
This is an "In-Processing" mitigation technique.
The Constraint: We use DemographicParity. This tells the algorithm: "Find a model that predicts well, but ensures the probability of being hired is roughly equal for both genders."
The Trade-off: Usually, when you apply bias mitigation, the overall Accuracy will drop slightly. This is the cost of fairness.
How to Interpret the Output
When you run this, you will see output similar to this (numbers will vary):
Before Mitigation:
Group 0 Selection Rate: ~0.30
Group 1 Selection Rate: ~0.70
Conclusion: Huge bias detected.
After Mitigation:
Group 0 Selection Rate: ~0.45
Group 1 Selection Rate: ~0.45
Overall Accuracy: Dropped slightly.
Conclusion: The model is now fair regarding selection rates.
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# Fairlearn imports for metrics and mitigation
from fairlearn.metrics import MetricFrame, selection_rate, false_positive_rate, true_positive_rate
from fairlearn.reductions import ExponentiatedGradient, DemographicParity
# ==========================================
# 1. Data Generation (Synthetic Hiring Data)
# ==========================================
def generate_data(n_samples=1000):
np.random.seed(42)
# Feature: Years of Experience (Gaussian distribution)
experience = np.random.normal(5, 2, n_samples)
# Feature: Technical Score (Exam result)
technical_score = np.random.normal(70, 10, n_samples)
# Sensitive Feature: Gender (0: Female, 1: Male)
# We generate 50/50 split
gender = np.random.randint(0, 2, n_samples)
# TARGET VARIABLE: Hired (1) or Not Hired (0)
# LOGIC: Ideally based on experience + score.
# BIAS INJECTION: We add a bias where Males (1) get a "bonus" to the decision logic.
# This simulates historical bias in hiring.
score = (0.4 * experience) + (0.6 * technical_score) + np.random.normal(0, 5, n_samples)
# Add bias: Males get +15 points added to their internal score
score[gender == 1] += 15
# Threshold for hiring
hired = (score > 55).astype(int)
df = pd.DataFrame({
'experience': experience,
'technical_score': technical_score,
'gender': gender,
'hired': hired
})
return df
# ==========================================
# 2. Bias Detection Function
# ==========================================
def detect_bias(X_test, y_test, y_pred, sensitive_features):
print("\n--- BIAS DETECTION REPORT ---")
# We analyze metrics across groups (Group 0 vs Group 1)
metrics = {
'accuracy': accuracy_score,
'selection_rate': selection_rate, # How many people were hired?
'false_positive_rate': false_positive_rate,
'true_positive_rate': true_positive_rate
}
metric_frame = MetricFrame(
metrics=metrics,
y_true=y_test,
y_pred=y_pred,
sensitive_features=sensitive_features
)
print(metric_frame.by_group)
print("\nGlobal Metrics:")
print(f"Overall Accuracy: {accuracy_score(y_test, y_pred):.4f}")
# Calculate the Difference (Gap) between groups
diff = metric_frame.difference()
print(f"\nDisparity (Difference between groups):")
print(diff)
return metric_frame
# ==========================================
# 3. Main Execution
# ==========================================
def main():
# --- Step 1: Prepare Data ---
df = generate_data(2000)
# Split features and target
X = df[['experience', 'technical_score']]
y = df['hired']
sensitive = df['gender'] # We need this separate for fairness analysis
# Encode and Scale
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_train, X_test, y_train, y_test, sens_train, sens_test = train_test_split(
X_scaled, y, sensitive, test_size=0.3, random_state=42
)
# --- Step 2: Train Biased Model (Baseline) ---
print("Training Baseline (Unmitigated) Model...")
baseline_model = LogisticRegression(solver='liblinear')
baseline_model.fit(X_train, y_train)
y_pred_baseline = baseline_model.predict(X_test)
# --- Step 3: Detect Bias in Baseline ---
# We expect Group 1 (Males) to have a much higher selection rate due to injected bias
detect_bias(X_test, y_test, y_pred_baseline, sens_test)
# --- Step 4: Mitigation (Applying Constraints) ---
print("\n\n--- STARTING MITIGATION ---")
print("Applying Exponentiated Gradient with Demographic Parity constraint...")
# Constraint: Demographic Parity
# This forces the model to have similar selection rates across groups.
constraint = DemographicParity()
# We use ExponentiatedGradient, a wrapper that takes a standard estimator
# and optimizes it for the fairness constraint.
mitigator = ExponentiatedGradient(
LogisticRegression(solver='liblinear'),
constraints=constraint
)
# Note: We pass the sensitive features (gender) during training here
mitigator.fit(X_train, y_train, sensitive_features=sens_train)
y_pred_mitigated = mitigator.predict(X_test)
# --- Step 5: Re-evaluate ---
detect_bias(X_test, y_test, y_pred_mitigated, sens_test)
if __name__ == "__main__":
main()