Bias detection and mitigation help make sure AI models treat everyone fairly. It stops models from making unfair decisions based on gender, race, or other traits.
Bias detection and mitigation in ML Python
1. Collect data and check for bias using fairness metrics. 2. Use techniques like re-sampling, re-weighting, or adversarial training to reduce bias. 3. Evaluate the model again to confirm bias is reduced.
Bias detection uses fairness metrics like demographic parity or equal opportunity.
Mitigation can happen before, during, or after training the model.
# Example: Checking bias with demographic parity from sklearn.metrics import confusion_matrix # Calculate positive rates for groups positive_rate_group1 = sum(predictions[group1]) / len(group1) positive_rate_group2 = sum(predictions[group2]) / len(group2)
# Example: Mitigation by re-weighting samples weights = [1.5 if x in underrepresented_group else 1.0 for x in data] model.fit(data, labels, sample_weight=weights)
This example shows how to detect bias by comparing positive prediction rates between two groups. Then it applies re-weighting to reduce bias and checks the results.
import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score # Sample data: features and labels X = np.array([[1, 20], [2, 22], [3, 21], [4, 23], [5, 24], [6, 25]]) y = np.array([0, 0, 1, 1, 1, 0]) # Sensitive attribute (e.g., group membership) groups = np.array([0, 0, 1, 1, 1, 0]) # Train model without mitigation model = LogisticRegression() model.fit(X, y) preds = model.predict(X) accuracy = accuracy_score(y, preds) # Calculate positive prediction rates per group pos_rate_group0 = preds[groups == 0].mean() pos_rate_group1 = preds[groups == 1].mean() # Mitigation: re-weight samples to balance groups weights = np.where(groups == 0, 1.0, 1.5) model_mitigated = LogisticRegression() model_mitigated.fit(X, y, sample_weight=weights) preds_mitigated = model_mitigated.predict(X) accuracy_mitigated = accuracy_score(y, preds_mitigated) pos_rate_group0_m = preds_mitigated[groups == 0].mean() pos_rate_group1_m = preds_mitigated[groups == 1].mean() print(f"Before mitigation accuracy: {accuracy:.2f}") print(f"Positive rate group 0 before: {pos_rate_group0:.2f}") print(f"Positive rate group 1 before: {pos_rate_group1:.2f}") print(f"After mitigation accuracy: {accuracy_mitigated:.2f}") print(f"Positive rate group 0 after: {pos_rate_group0_m:.2f}") print(f"Positive rate group 1 after: {pos_rate_group1_m:.2f}")
Bias detection is not just about accuracy; fairness metrics are key.
Mitigation may slightly reduce accuracy but improves fairness.
Always test models on diverse data to catch hidden biases.
Bias detection finds unfair treatment in AI models.
Mitigation techniques help models treat groups more equally.
Checking fairness is important for trustworthy AI.
Practice
Solution
Step 1: Understand bias detection purpose
Bias detection aims to identify if a model treats some groups unfairly compared to others.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.Final Answer:
To find unfair treatment of certain groups by the model -> Option AQuick Check:
Bias detection = find unfair treatment [OK]
- Confusing bias detection with improving accuracy
- Thinking bias detection speeds up training
- Mixing bias detection with data size reduction
Solution
Step 1: Identify bias mitigation methods
Oversampling underrepresented groups balances data, reducing bias.Step 2: Evaluate other options
Reducing features, increasing learning rate, and dropout affect model complexity or training, not bias directly.Final Answer:
Oversampling underrepresented groups -> Option AQuick Check:
Bias mitigation = oversampling minority data [OK]
- Confusing feature reduction with bias mitigation
- Thinking learning rate affects bias
- Mixing dropout with bias correction
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?
Solution
Step 1: Understand resample parameters
resample duplicates minority samples to reach n_samples=4, so output lists have length 4.Step 2: Check print output
Both X_upsampled and y_upsampled have length 4, so print outputs '4 4'.Final Answer:
4 4 -> Option BQuick Check:
Oversampling size = 4 [OK]
- Assuming output length stays original size
- Thinking resample doubles data always
- Expecting error from resample usage
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?Solution
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.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.Step 3: Correct approach
Both filtered_data and filtered_labels should be filtered using zip together to ensure matching lengths.Final Answer:
filtered_labels length does not match filtered_data length -> Option DQuick Check:
Separate filtering risks length mismatch [OK]
- Mistakenly thinking separate comprehensions cause length mismatch
- Believing zip and direct label filter select differently
- Assuming the code has a bug without tracing execution
Solution
Step 1: Understand bias mitigation strategies
Reweighting balances data impact; fairness constraints guide model to treat groups fairly.Step 2: Evaluate other options
Removing 'gender' may hide bias but not fix it; increasing complexity can worsen bias; oversampling majority increases imbalance.Final Answer:
Use reweighting to balance training samples and add fairness constraints during model training -> Option CQuick Check:
Combine reweighting + fairness constraints = best bias mitigation [OK]
- Removing sensitive attribute hides but does not fix bias
- Increasing complexity ignores bias issues
- Oversampling majority worsens bias
Ready to prove it?
Pass the test and this pattern moves unknown
