1. Understand the Goal: The user wants a program to detect and mitigate bias in machine learning models. This is a broad request, so I need to create a comprehensive yet accessible example that covers the key steps: data loading, bias detection, and bias mitigation.
-
Identify Key Components:
- Dataset: I need a dataset that is known to contain bias or is structured in a way that bias can be easily demonstrated (e.g., gender or race bias in income prediction). The "Adult" (Census Income) dataset is a classic example, but generating a synthetic dataset is safer and more self-contained for a code example. Let's use a synthetic dataset based on loan approval to make it intuitive.
- Model: A standard classifier (e.g., Logistic Regression or Random Forest) is sufficient to demonstrate the concepts.
- Detection Metric: How do we measure bias? Common metrics include Disparate Impact, Statistical Parity Difference, or Equal Opportunity Difference. I should implement at least one of these.
- Mitigation Strategy: How do we fix it?
- Pre-processing: Reweighting or resampling the data (e.g., AIF360's Reweighing).
- In-processing: Adding fairness constraints to the loss function (complex to implement from scratch).
- Post-processing: Adjusting thresholds for different groups (e.g., Calibrated Equalized Odds).
- Library: Writing all the math from scratch is error-prone and lengthy. Using IBM's
AIF360 (AI Fairness 360) is the industry standard for this, but it can be tricky to set up for a simple snippet. A pure scikit-learn + pandas approach is more portable and educational for understanding the logic, but AIF360 is better for "production" style code.
- Decision: I will provide a solution using standard libraries (
pandas, sklearn) to explain the concept clearly, and then mention AIF360 as the professional tool. Actually, writing a "program" implies something functional. Let's create a class-based structure that handles detection and a simple mitigation technique (Resampling/Reweighting).
-
Drafting the Logic (Mental or Scratchpad):
- Scenario: Loan Approval. Features: Income, Debt, Gender (Sensitive Attribute). Target: Approved (0/1).
- Step 1: Train a baseline model.
- Step 2: Detect Bias. Calculate selection rates for Male vs. Female. Calculate Disparate Impact (Ratio of rates).
- Step 3: Mitigate Bias. Let's use Reweighting. Give higher weights to instances from the unprivileged group that have favorable outcomes, and lower weights to privileged groups with favorable outcomes (or vice versa for unfavorable). This is easier to implement in standard sklearn than adversarial debiasing.
-
Refining the Code Structure:
- Imports:
numpy, pandas, sklearn.
- Data Generation: Create a synthetic dataset where one gender is favored (e.g., males have higher income on average, leading the model to prefer them).
- Class
BiasMitigator:
detect_bias: Computes metrics.
mitigate: Applies sample weights.
evaluate: Trains and reports results.
-
Writing the Code (Iterative refinement):
- Data: Let's make it simple.
- Group A (Privileged): 80% approval rate (inherent data bias).
- Group B (Unprivileged): 40% approval rate.
- Detection: Metric =
Privileged_Selection_Rate / Unprivileged_Selection_Rate. If < 0.8, it's generally considered biased (four-fifths rule).
- Mitigation: I'll implement Prejudice Remover via Reweighting logic conceptually.
- Logic: We want P(Y=1∣A=0)≈P(Y=.
-
Structuring the Output:
- Disclaimer: Start by stating that bias is a complex sociotechnical problem, not just a coding fix.
- The Approach: Explain "Disparate Impact" and "Reweighting".
- The Code:
- Generate synthetic biased data.
- Train a baseline model.
- Show bias metrics.
- Apply reweighting mitigation.
- Retrain and show improved metrics.
- Explanation: Walk through what the code did.
-
Refining the "Mitigation" Implementation (Self-Correction):
Implementing the exact statistical reweighting formula from scratch might be too dense for a quick example. A simpler, intuitive mitigation for a demo is Resampling (undersampling the privileged class or oversampling the unprivileged class) or just explaining the weights.
Actually, calculating weights is clean:
Weight = (Total count / (Group Count * Label Count)) ... roughly.
Let's stick to a clear, custom implementation of "Fairness Through Unawareness" (removing the column) vs "Reweighting".
Better approach: I will implement a Sample Weight calculation function. It's mathematically precise and looks professional.
Formula:
For a sample with sensitive attribute A=a and label Y=y:
... Wait, that's usually normalized.
The standard reweighting factor (from Kamiran & Calders) is:
Basically, if a group is underrepresented for a specific outcome (e.g., Females getting High Income), they get a higher weight.
-
Final Code Plan:
- Part 1: Setup synthetic data (Income prediction, biased against females).
- Part 2: Helper function to calculate Disparate Impact.
- Part 3: Train Baseline (Logistic Regression).
- Part 4: Compute Weights based on the formula above.
- Part 5: Train Mitigated Model with
sample_weight.
-
Review against constraints:
- Does it detect? Yes (Disparate Impact).
- Does it mitigate? Yes (Reweighting).
- Is it a program? Yes, a Python script.
-
Adding Context: Mention that in production, one would use IBM AIF360 or Fairlearn. I will write the code using standard sklearn/pandas to ensure it runs without installing niche libraries like aif360 (which can be heavy on dependencies), but I'll structure it logically.
(Self-Correction during drafting code): Ensure I clearly define what "Privileged" and "Unprivileged" means in the context of the code.
Let's write the solution.
- Step 1: Imports.
- Step 2: Synthetic Data Generator.
- Step 3: Metric Function (Disparate Impact).
- Step 4: Reweighting Function.
- Step 5: Main execution flow.
This looks solid. It addresses the prompt, is educational, and provides a working "from scratch" example while acknowledging industry tools.
This is a complex task because "bias" in machine learning can refer to data imbalance, measurement errors, or unfair outcomes regarding specific protected groups (gender, race, age).
Below is a complete Python program using scikit-learn and pandas. It demonstrates the end-to-end workflow of Detecting and Mitigating bias using the Reweighting technique (assigning weights to samples to neutralize statistical bias).
The Approach
- Dataset: We will generate a synthetic dataset representing loan applications.
- Detection: We will measure "Disparate Impact" (the ratio of favorable outcomes between unprivileged and privileged groups). A ratio of < 0.8 is generally considered biased (the "80% rule").
- Mitigation: We will calculate sample weights so that the data distribution appears "fair" regarding the protected attribute (e.g., Gender) without deleting any data rows.
- Comparison: We will train two models—one standard, one mitigated—and compare the fairness metrics.
Prerequisites
You will need pandas, numpy, and scikit-learn installed:
pip install pandas numpy scikit-learn
The Python Program
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder
# ==========================================
# 1. Data Simulation
# ==========================================
def generate_biased_data(n_samples=1000):
"""
Generates a synthetic dataset for loan approval.
Intentionally injects a bias where 'Male' applicants
have a much higher approval rate than 'Female' applicants,
even if their financial credentials (Income/Credit) are similar.
"""
np.random.seed(42)
# Features
income = np.random.normal(50000, 15000, n_samples)
credit_score = np.random.normal(700, 50, n_samples)
# Protected Attribute: Gender (0=Female, 1=Male)
# 50% split
gender = np.random.randint(0, 2, n_samples)
# Target: Loan Approved (1) or Denied (0)
# Logic: High income and credit score increases chance.
# BIAS INJECTION: Being Male (gender=1) adds a huge artificial boost to the probability.
approval_prob = (
0.3 * ((income - min(income)) / (max(income) - min(income))) +
0.3 * ((credit_score - min(credit_score)) / (max(credit_score) - min(credit_score))) +
0.3 * gender # <--- This is the bias source
)
# Add some noise and convert to binary
approval_prob += np.random.normal(0, 0.05, n_samples)
approved = (approval_prob > 0.6).astype(int)
df = pd.DataFrame({
'income': income,
'credit_score': credit_score,
'gender': gender,
'approved': approved
})
return df
# ==========================================
# 2. Bias Detection Metrics
# ==========================================
def calculate_disparate_impact(df, protected_attr, target_col, privileged_val, unprivileged_val):
"""
Calculates the ratio of the rate of favorable outcomes for
the unprivileged group to the privileged group.
"""
# Rate of approval for privileged group
priv_mask = df[protected_attr] == privileged_val
rate_priv = df.loc[priv_mask, target_col].mean()
# Rate of approval for unprivileged group
unpriv_mask = df[protected_attr] == unprivileged_val
rate_unpriv = df.loc[unpriv_mask, target_col].mean()
# Avoid division by zero
if rate_priv == 0:
return 0.0
di = rate_unpriv / rate_priv
print(f"--- Bias Metrics ---")
print(f"Approval Rate (Privileged): {rate_priv:.4f}")
print(f"Approval Rate (Unprivileged): {rate_unpriv:.4f}")
print(f"Disparate Impact (DI): {di:.4f}")
print(f"Status: {'BIASED (DI < 0.80)' if di < 0.80 else 'FAIR'}")
print("--------------------\n")
return di
# ==========================================
# 3. Bias Mitigation (Reweighting)
# ==========================================
def compute_fair_weights(df, protected_attr, target_col):
"""
Computes sample weights to ensure fairness.
Logic: Weight = (Total N) / (N_group * N_class)
This gives higher weight to underrepresented combinations
(e.g., Females with Approved loans if that is rare).
"""
n_total = len(df)
# Group statistics
grouped = df.groupby([protected_attr, target_col]).size().reset_index(name='count')
# Global probabilities
p_target = df[target_col].value_counts(normalize=True).to_dict()
p_protect = df[protected_attr].value_counts(normalize=True).to_dict()
weights = []
for _, row in df.iterrows():
g = row[protected_attr]
y = row[target_col]
# Find count for specific group (g) and outcome (y)
# In a simplified formula, weight is 1 / (P(Y|G) * P(G))
# We act as if we want P(Y|G) to be equal to P(Y)
# Empirical probability of this specific combination
p_combination = len(df[(df[protected_attr]==g) & (df[target_col]==y)]) / n_total
# Expected probability if independent (fair)
p_expected = p_target[y] * p_protect[g]
# Weight ratio
w = p_expected / p_combination
weights.append(w)
return np.array(weights)
# ==========================================
# 4. Main Execution
# ==========================================
if __name__ == "__main__":
# 1. Generate Data
data = generate_biased_data()
# Split features and target
X = data[['income', 'credit_score', 'gender']]
y = data['approved']
# Split Train/Test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Reconstruct training DF for easier weight calculation
train_df = X_train.copy()
train_df['approved'] = y_train
print("STEP 1: Analyzing Original Data Bias\n")
# We treat Gender=1 (Male) as Privileged based on our data generation logic
orig_di = calculate_disparate_impact(train_df, 'gender', 'approved', privileged_val=1, unprivileged_val=0)
# ------------------------------------------
# MODEL A: Standard Model (Biased)
# ------------------------------------------
model_standard = LogisticRegression(solver='liblinear')
model_standard.fit(X_train, y_train)
# Predict on test set
preds_standard = model_standard.predict(X_test)
# Reconstruct Test DF for metrics
test_df = X_test.copy()
test_df['pred_approved'] = preds_standard
print("STEP 2: Analyzing Standard Model Predictions\n")
standard_di = calculate_disparate_impact(test_df, 'gender', 'pred_approved', 1, 0)
# ------------------------------------------
# MODEL B: Mitigated Model (Reweighted)
# ------------------------------------------
print("STEP 3: Calculating Fairness Weights (Mitigation)...\n")
# We use weights to penalize the model if it relies on the biased correlation
sample_weights = compute_fair_weights(train_df, 'gender', 'approved')
model_fair = LogisticRegression(solver='liblinear')
model_fair.fit(X_train, y_train, sample_weight=sample_weights)
# Predict on test set
preds_fair = model_fair.predict(X_test)
test_df['pred_fair'] = preds_fair
print("STEP 4: Analyzing Fair Model Predictions\n")
fair_di = calculate_disparate_impact(test_df, 'gender', 'pred_fair', 1, 0)
# ------------------------------------------
# Summary
# ------------------------------------------
print("=== FINAL SUMMARY ===")
print(f"Standard Model Accuracy: {accuracy_score(y_test, preds_standard):.4f}")
print(f"Standard Model Disparate Impact: {standard_di:.4f}")
print("-" * 20)
print(f"Fair Model Accuracy: {accuracy_score(y_test, preds_fair):.4f}")
print(f"Fair Model Disparate Impact: {fair_di:.4f}")
print("\nINTERPRETATION:")
print("Notice that the Standard Model likely amplified the bias (DI is low).")
print("The Fair Model sacrificed a tiny bit of accuracy to significantly improve")
print("the Disparate Impact score (closer to 1.0).")
How it works
- Data Generation: The code creates a scenario where men are favored for loans simply for being men (
0.3 * gender), even though income and credit score should be the deciding factors.
- Detection (Disparate Impact): This measures selection rates. If 60% of Men get loans, but only 30% of Women get loans, the Disparate Impact is 0.30/0.60=0.5. A value below 0.8 indicates legal/ethical risk.
- Mitigation (Reweighting): Before training the second model, we calculate weights for every row in the dataset.
- If "Female + Approved" is a rare combination in the biased data, we assign it a high weight. This tells the model, "Pay extra attention to these cases; they are important."
- If "Male + Approved" is very common, we assign it a lower relative weight.
- Training: We train the
model_fair using these sample weights.
When to use this approach
- Preprocessing: This is a "preprocessing" mitigation technique. It fixes the data before the model sees it. This is useful if you want to use standard algorithms (like Logistic Regression or Random Forests) without modifying the algorithm's internal code.
- Trade-offs: Usually, there is a small trade-off between accuracy and fairness. The "Fair Model" might drop 0.5% accuracy to gain 30% fairness.