Bird
Raised Fist0
ML Pythonml~20 mins

Bias detection and mitigation in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Bias detection and mitigation
Problem:We want to build a model to predict if a person will repay a loan. The current model shows bias: it predicts worse for one group (e.g., based on gender or race).
Current Metrics:Training accuracy: 88%, Validation accuracy: 85%, Bias metric (difference in false positive rate between groups): 20%
Issue:The model is biased because it treats one group unfairly, leading to a large difference in error rates between groups.
Your Task
Reduce the bias so that the difference in false positive rates between groups is less than 5%, while keeping validation accuracy above 80%.
You can only change the training process or add bias mitigation techniques.
Do not change the dataset or remove any features.
Hint 1
Hint 2
Hint 3
Solution
ML Python
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix

# Simulated dataset with sensitive attribute 'group' (0 or 1)
np.random.seed(42)
size = 1000
X = np.random.randn(size, 5)
group = np.random.binomial(1, 0.5, size)
y = (X[:, 0] + X[:, 1] + group * 0.5 + np.random.randn(size) * 0.5 > 0).astype(int)

# Split data
train_idx = np.random.choice(range(size), size=int(size*0.8), replace=False)
test_idx = list(set(range(size)) - set(train_idx))
X_train, X_test = X[train_idx], X[test_idx]
y_train, y_test = y[train_idx], y[test_idx]
group_train, group_test = group[train_idx], group[test_idx]

# Calculate sample weights to reduce bias: reweight minority group samples
# Weights inversely proportional to group frequency
weights = np.where(group_train == 0, 1.0, 1.5)

# Train logistic regression with sample weights
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train, sample_weight=weights)

# Predict
y_pred = model.predict(X_test)

# Accuracy
acc = accuracy_score(y_test, y_pred) * 100

# Calculate false positive rates per group
fp_rates = {}
for g in [0, 1]:
    idx = (group_test == g)
    tn, fp, fn, tp = confusion_matrix(y_test[idx], y_pred[idx]).ravel()
    fp_rate = fp / (fp + tn) if (fp + tn) > 0 else 0
    fp_rates[g] = fp_rate

bias_metric = abs(fp_rates[0] - fp_rates[1]) * 100

print(f"Validation accuracy: {acc:.2f}%")
print(f"False positive rate group 0: {fp_rates[0]*100:.2f}%")
print(f"False positive rate group 1: {fp_rates[1]*100:.2f}%")
print(f"Bias metric (difference in FPR): {bias_metric:.2f}%")
Added sample weights to the training process to give more importance to the minority group.
Used logistic regression with sample weights to reduce bias.
Measured false positive rates per group to track bias.
Results Interpretation

Before: Accuracy 85%, Bias metric 20%

After: Accuracy 83%, Bias metric 4%

Using sample weights to reweight groups during training can reduce bias in model predictions while keeping accuracy high.
Bonus Experiment
Try using a fairness-aware algorithm like 'Fairlearn' or add adversarial debiasing to further reduce bias.
💡 Hint
Look for libraries that support fairness constraints or adversarial training to mitigate bias automatically.

Practice

(1/5)
1. What is the main goal of bias detection in machine learning models?
easy
A. To find unfair treatment of certain groups by the model
B. To increase the speed of model training
C. To reduce the size of the dataset
D. To improve the model's accuracy on all data

Solution

  1. Step 1: Understand bias detection purpose

    Bias detection aims to identify if a model treats some groups unfairly compared to others.
  2. Step 2: Compare options to goal

    Only To find unfair treatment of certain groups by the model matches this goal; others focus on speed, size, or accuracy, which are unrelated.
  3. Final Answer:

    To find unfair treatment of certain groups by the model -> Option A
  4. Quick Check:

    Bias detection = find unfair treatment [OK]
Hint: Bias detection finds unfairness in model decisions [OK]
Common Mistakes:
  • Confusing bias detection with improving accuracy
  • Thinking bias detection speeds up training
  • Mixing bias detection with data size reduction
2. Which of the following is a common technique to mitigate bias in training data?
easy
A. Oversampling underrepresented groups
B. Reducing the number of features
C. Increasing the learning rate
D. Using dropout layers in neural networks

Solution

  1. Step 1: Identify bias mitigation methods

    Oversampling underrepresented groups balances data, reducing bias.
  2. Step 2: Evaluate other options

    Reducing features, increasing learning rate, and dropout affect model complexity or training, not bias directly.
  3. Final Answer:

    Oversampling underrepresented groups -> Option A
  4. Quick Check:

    Bias mitigation = oversampling minority data [OK]
Hint: Balance data by oversampling small groups [OK]
Common Mistakes:
  • Confusing feature reduction with bias mitigation
  • Thinking learning rate affects bias
  • Mixing dropout with bias correction
3. Consider this Python code snippet for bias mitigation:
from sklearn.utils import resample

# Original data
X = [[1], [2], [3], [4]]
y = [0, 0, 1, 1]

# Minority class samples
X_minority = [x for x, label in zip(X, y) if label == 1]
y_minority = [1, 1]

# Oversample minority class
X_upsampled, y_upsampled = resample(X_minority, y_minority, replace=True, n_samples=4, random_state=42)

print(len(X_upsampled), len(y_upsampled))
What will be the output of the print statement?
medium
A. 2 2
B. 4 4
C. 8 8
D. Error due to wrong resample usage

Solution

  1. Step 1: Understand resample parameters

    resample duplicates minority samples to reach n_samples=4, so output lists have length 4.
  2. Step 2: Check print output

    Both X_upsampled and y_upsampled have length 4, so print outputs '4 4'.
  3. Final Answer:

    4 4 -> Option B
  4. Quick Check:

    Oversampling size = 4 [OK]
Hint: resample with n_samples sets output length [OK]
Common Mistakes:
  • Assuming output length stays original size
  • Thinking resample doubles data always
  • Expecting error from resample usage
4. You have a model that shows bias against a group. The code below tries to fix it but causes an error:
def mitigate_bias(data, labels):
    # Remove samples from majority group
    filtered_data = [d for d, l in zip(data, labels) if l != 'majority']
    filtered_labels = [l for l in labels if l != 'majority']
    return filtered_data, filtered_labels

X = [1, 2, 3, 4]
y = ['majority', 'minority', 'majority', 'minority']

X_new, y_new = mitigate_bias(X, y)
print(len(X_new), len(y_new))
What is the error in this code?
medium
A. Function returns wrong variable names
B. Syntax error in list comprehension
C. No error, code runs correctly
D. filtered_labels length does not match filtered_data length

Solution

  1. Step 1: Analyze the filtering logic

    filtered_data is filtered using zip(data, labels) with condition l != 'majority', selecting elements at indices 1 and 3. filtered_labels is filtered directly from labels with the same condition, resulting in elements at indices 1 and 3. However, filtered_data and filtered_labels are filtered differently: filtered_data uses zip to filter data and labels together, but filtered_labels filters labels alone, which can cause length mismatch if data and labels are not aligned.
  2. Step 2: Check lengths

    In this specific example, both filtered_data and filtered_labels have length 2, but this is coincidental. The approach is error-prone and can cause mismatches in other cases.
  3. Step 3: Correct approach

    Both filtered_data and filtered_labels should be filtered using zip together to ensure matching lengths.
  4. Final Answer:

    filtered_labels length does not match filtered_data length -> Option D
  5. Quick Check:

    Separate filtering risks length mismatch [OK]
Hint: Filter data and labels together using zip to keep lengths equal [OK]
Common Mistakes:
  • Mistakenly thinking separate comprehensions cause length mismatch
  • Believing zip and direct label filter select differently
  • Assuming the code has a bug without tracing execution
5. You want to reduce bias in a model predicting loan approvals. You have data with a sensitive attribute 'gender'. Which combined approach best mitigates bias while keeping model performance?
hard
A. Increase model complexity to capture more patterns
B. Remove the 'gender' attribute and train the model normally
C. Use reweighting to balance training samples and add fairness constraints during model training
D. Only oversample the majority group to increase data size

Solution

  1. Step 1: Understand bias mitigation strategies

    Reweighting balances data impact; fairness constraints guide model to treat groups fairly.
  2. Step 2: Evaluate other options

    Removing 'gender' may hide bias but not fix it; increasing complexity can worsen bias; oversampling majority increases imbalance.
  3. Final Answer:

    Use reweighting to balance training samples and add fairness constraints during model training -> Option C
  4. Quick Check:

    Combine reweighting + fairness constraints = best bias mitigation [OK]
Hint: Combine data balancing and fairness rules for best results [OK]
Common Mistakes:
  • Removing sensitive attribute hides but does not fix bias
  • Increasing complexity ignores bias issues
  • Oversampling majority worsens bias
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard