Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the Python 3.15, NumPy 2.5 and scikit-learn 1.9 documentation.
AI Bias Detection and Mitigation: Building Fair Machine Learning Systems
Bias in AI systems can perpetuate discrimination and cause significant harm. This guide covers practical techniques for detecting, measuring, and mitigating bias throughout the ML lifecycle to build fairer, more equitable systems.
Understanding AI Bias
AI bias manifests in multiple forms:
- Historical bias: Training data reflects past discrimination
- Representation bias: Underrepresentation of certain groups
- Measurement bias: Features that proxy for protected attributes
- Aggregation bias: One model for diverse subpopulations
- Evaluation bias: Benchmarks don't represent deployment context
Fairness Metrics Implementation
# fairness_metrics.py
"""
Comprehensive fairness metrics for ML model evaluation.
"""
import numpy as np
import pandas as pd
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from scipy import stats
@dataclass
class FairnessReport:
"""Complete fairness evaluation report."""
metric_name: str
overall_value: float
group_values: Dict[str, float]
disparities: Dict[str, float]
passes_threshold: bool
threshold: float
recommendations: List[str]
class FairnessEvaluator:
"""
Evaluate model fairness across protected groups.
"""
def __init__(
self,
protected_attribute: str,
favorable_label: int = 1,
unfavorable_label: int = 0
):
self.protected_attribute = protected_attribute
self.favorable_label = favorable_label
self.unfavorable_label = unfavorable_label
def demographic_parity(
self,
y_pred: np.ndarray,
protected_groups: np.ndarray,
threshold: float = 0.1
) -> FairnessReport:
"""
Demographic parity: P(Y_pred=1 | A=a) should be equal across groups.
Also known as statistical parity or group fairness.
"""
groups = np.unique(protected_groups)
selection_rates = {}
for group in groups:
mask = protected_groups == group
rate = np.mean(y_pred[mask] == self.favorable_label)
selection_rates[str(group)] = rate
overall_rate = np.mean(y_pred == self.favorable_label)
# Calculate disparities
disparities = {}
max_disparity = 0
for group, rate in selection_rates.items():
disparity = abs(rate - overall_rate)
disparities[group] = disparity
max_disparity = max(max_disparity, disparity)
recommendations = []
if max_disparity > threshold:
worst_group = max(disparities, key=disparities.get)
recommendations.append(
f"Group '{worst_group}' has highest disparity ({disparities[worst_group]:.3f})"
)
recommendations.append("Consider resampling or reweighting training data")
return FairnessReport(
metric_name="Demographic Parity",
overall_value=overall_rate,
group_values=selection_rates,
disparities=disparities,
passes_threshold=max_disparity <= threshold,
threshold=threshold,
recommendations=recommendations
)
def equalized_odds(
self,
y_true: np.ndarray,
y_pred: np.ndarray,
protected_groups: np.ndarray,
threshold: float = 0.1
) -> FairnessReport:
"""
Equalized odds: TPR and FPR should be equal across groups.
P(Y_pred=1 | Y=y, A=a) should be equal for all groups and y in {0,1}
"""
groups = np.unique(protected_groups)
tpr_values = {}
fpr_values = {}
for group in groups:
mask = protected_groups == group
# True Positive Rate
pos_mask = (y_true == self.favorable_label) & mask
if np.sum(pos_mask) > 0:
tpr = np.mean(y_pred[pos_mask] == self.favorable_label)
else:
tpr = 0
tpr_values[str(group)] = tpr
# False Positive Rate
neg_mask = (y_true == self.unfavorable_label) & mask
if np.sum(neg_mask) > 0:
fpr = np.mean(y_pred[neg_mask] == self.favorable_label)
else:
fpr = 0
fpr_values[str(group)] = fpr
# Calculate disparities
tpr_disparity = max(tpr_values.values()) - min(tpr_values.values())
fpr_disparity = max(fpr_values.values()) - min(fpr_values.values())
disparities = {
'tpr_disparity': tpr_disparity,
'fpr_disparity': fpr_disparity
}
max_disparity = max(tpr_disparity, fpr_disparity)
recommendations = []
if tpr_disparity > threshold:
recommendations.append(f"TPR disparity ({tpr_disparity:.3f}) exceeds threshold")
if fpr_disparity > threshold:
recommendations.append(f"FPR disparity ({fpr_disparity:.3f}) exceeds threshold")
return FairnessReport(
metric_name="Equalized Odds",
overall_value=max_disparity,
group_values={'tpr': tpr_values, 'fpr': fpr_values},
disparities=disparities,
passes_threshold=max_disparity <= threshold,
threshold=threshold,
recommendations=recommendations
)
def predictive_parity(
self,
y_true: np.ndarray,
y_pred: np.ndarray,
protected_groups: np.ndarray,
threshold: float = 0.1
) -> FairnessReport:
"""
Predictive parity: Precision should be equal across groups.
P(Y=1 | Y_pred=1, A=a) should be equal for all groups.
"""
groups = np.unique(protected_groups)
precision_values = {}
for group in groups:
mask = protected_groups == group
pred_pos = (y_pred == self.favorable_label) & mask
if np.sum(pred_pos) > 0:
precision = np.mean(y_true[pred_pos] == self.favorable_label)
else:
precision = 0
precision_values[str(group)] = precision
overall_precision = np.mean(
y_true[y_pred == self.favorable_label] == self.favorable_label
) if np.sum(y_pred == self.favorable_label) > 0 else 0
disparities = {
group: abs(prec - overall_precision)
for group, prec in precision_values.items()
}
max_disparity = max(disparities.values()) if disparities else 0
recommendations = []
if max_disparity > threshold:
recommendations.append("Precision varies significantly across groups")
recommendations.append("Consider calibration techniques")
return FairnessReport(
metric_name="Predictive Parity",
overall_value=overall_precision,
group_values=precision_values,
disparities=disparities,
passes_threshold=max_disparity <= threshold,
threshold=threshold,
recommendations=recommendations
)
def calibration_fairness(
self,
y_true: np.ndarray,
y_prob: np.ndarray,
protected_groups: np.ndarray,
n_bins: int = 10,
threshold: float = 0.1
) -> FairnessReport:
"""
Calibration fairness: For each probability bin, actual rate should match.
"""
groups = np.unique(protected_groups)
calibration_scores = {}
bin_edges = np.linspace(0, 1, n_bins + 1)
for group in groups:
mask = protected_groups == group
group_probs = y_prob[mask]
group_true = y_true[mask]
errors = []
for i in range(n_bins):
bin_mask = (group_probs >= bin_edges[i]) & (group_probs < bin_edges[i+1])
if np.sum(bin_mask) > 0:
expected = np.mean(group_probs[bin_mask])
actual = np.mean(group_true[bin_mask])
errors.append(abs(expected - actual))
calibration_scores[str(group)] = np.mean(errors) if errors else 0
overall_calibration = np.mean(list(calibration_scores.values()))
disparities = {
group: abs(score - overall_calibration)
for group, score in calibration_scores.items()
}
max_disparity = max(disparities.values()) if disparities else 0
recommendations = []
if max_disparity > threshold:
recommendations.append("Model is not equally well-calibrated across groups")
recommendations.append("Consider group-specific calibration")
return FairnessReport(
metric_name="Calibration Fairness",
overall_value=overall_calibration,
group_values=calibration_scores,
disparities=disparities,
passes_threshold=max_disparity <= threshold,
threshold=threshold,
recommendations=recommendations
)
def individual_fairness(
self,
features: np.ndarray,
y_pred: np.ndarray,
similarity_threshold: float = 0.1,
prediction_threshold: float = 0.1
) -> FairnessReport:
"""
Individual fairness: Similar individuals should receive similar predictions.
"""
n_samples = len(features)
# Normalize features
features_norm = (features - features.mean(axis=0)) / (features.std(axis=0) + 1e-10)
violations = 0
total_pairs = 0
# Sample pairs for efficiency
n_pairs = min(10000, n_samples * (n_samples - 1) // 2)
indices = np.random.choice(n_samples, size=(n_pairs, 2), replace=True)
for i, j in indices:
if i == j:
continue
# Calculate feature distance
feature_dist = np.linalg.norm(features_norm[i] - features_norm[j])
# Calculate prediction distance
pred_dist = abs(y_pred[i] - y_pred[j])
# Check violation
if feature_dist < similarity_threshold and pred_dist > prediction_threshold:
violations += 1
total_pairs += 1
violation_rate = violations / total_pairs if total_pairs > 0 else 0
recommendations = []
if violation_rate > 0.05:
recommendations.append(f"Individual fairness violation rate: {violation_rate:.1%}")
recommendations.append("Consider adding consistency regularization")
return FairnessReport(
metric_name="Individual Fairness",
overall_value=violation_rate,
group_values={'violation_rate': violation_rate},
disparities={'violations': violations, 'total_pairs': total_pairs},
passes_threshold=violation_rate <= 0.05,
threshold=0.05,
recommendations=recommendations
)
def comprehensive_evaluation(
self,
y_true: np.ndarray,
y_pred: np.ndarray,
y_prob: np.ndarray,
protected_groups: np.ndarray,
features: Optional[np.ndarray] = None
) -> Dict[str, FairnessReport]:
"""Run all fairness metrics."""
reports = {}
reports['demographic_parity'] = self.demographic_parity(y_pred, protected_groups)
reports['equalized_odds'] = self.equalized_odds(y_true, y_pred, protected_groups)
reports['predictive_parity'] = self.predictive_parity(y_true, y_pred, protected_groups)
reports['calibration'] = self.calibration_fairness(y_true, y_prob, protected_groups)
if features is not None:
reports['individual_fairness'] = self.individual_fairness(features, y_prob)
return reportsBias Mitigation Techniques
# bias_mitigation.py
"""
Bias mitigation techniques for ML models.
"""
import numpy as np
from typing import Optional
from sklearn.base import BaseEstimator, TransformerMixin, ClassifierMixin
from sklearn.utils.validation import has_fit_parameter
class Reweighing(BaseEstimator, TransformerMixin):
"""
Pre-processing technique that assigns weights to training examples.
Adjusts weights so that group membership and label look independent
in the weighted training data.
"""
def __init__(self, protected_attribute_idx: int):
self.protected_attribute_idx = protected_attribute_idx
self.weights_ = None
def fit(self, X: np.ndarray, y: np.ndarray) -> 'Reweighing':
"""Calculate reweighing weights."""
protected = X[:, self.protected_attribute_idx]
groups = np.unique(protected)
n = len(y)
weights = np.ones(n)
for group in groups:
group_mask = protected == group
for label in [0, 1]:
label_mask = y == label
p_group = np.sum(group_mask) / n # P(A=a)
p_label = np.sum(label_mask) / n # P(Y=y)
p_joint = np.sum(group_mask & label_mask) / n # P(A=a, Y=y)
# Expected under independence: P(A=a) * P(Y=y)
expected = p_group * p_label
weight = expected / p_joint if p_joint > 0 else 1.0
weights[group_mask & label_mask] = weight
self.weights_ = weights
return self
def transform(self, X: np.ndarray) -> np.ndarray:
"""Return the features unchanged (weights stored separately)."""
return X
def get_weights(self) -> np.ndarray:
"""Get the calculated weights."""
return self.weights_
class DisparateImpactRemover(BaseEstimator, TransformerMixin):
"""
Pre-processing technique that shifts each feature so that group medians
match the overall median (a simplified repair: it aligns medians, not
whole distributions).
"""
def __init__(self, protected_attribute_idx: int, repair_level: float = 1.0):
self.protected_attribute_idx = protected_attribute_idx
self.repair_level = repair_level
self.median_values_ = {}
def fit(self, X: np.ndarray, y: np.ndarray = None) -> 'DisparateImpactRemover':
"""Learn median values for each group."""
protected = X[:, self.protected_attribute_idx]
groups = np.unique(protected)
for feature_idx in range(X.shape[1]):
if feature_idx == self.protected_attribute_idx:
continue
self.median_values_[feature_idx] = {}
overall_median = np.median(X[:, feature_idx])
for group in groups:
group_mask = protected == group
self.median_values_[feature_idx][group] = {
'group_median': np.median(X[group_mask, feature_idx]),
'overall_median': overall_median
}
return self
def transform(self, X: np.ndarray) -> np.ndarray:
"""Transform features to reduce disparate impact."""
X_transformed = X.copy().astype(float)
protected = X[:, self.protected_attribute_idx]
for feature_idx, medians in self.median_values_.items():
for group, values in medians.items():
group_mask = protected == group
shift = values['overall_median'] - values['group_median']
X_transformed[group_mask, feature_idx] += self.repair_level * shift
return X_transformed
class CalibratedEqualizedOdds(BaseEstimator, ClassifierMixin):
"""
Post-processing with one decision threshold per group, chosen so that
true positive rates match across groups (equal opportunity).
Despite the class name, it does not equalize false positive rates, so it
is not full equalized odds; for that, use fairlearn's ThresholdOptimizer
with constraints="equalized_odds".
"""
def __init__(self, base_estimator, protected_attribute_idx: int):
self.base_estimator = base_estimator
self.protected_attribute_idx = protected_attribute_idx
self.thresholds_ = {}
def fit(
self,
X: np.ndarray,
y: np.ndarray,
X_val: Optional[np.ndarray] = None,
y_val: Optional[np.ndarray] = None
) -> 'CalibratedEqualizedOdds':
"""Fit the base estimator on (X, y) and the thresholds on a held-out set.
Thresholds fitted on training data inherit the model's overfitting,
so pass X_val / y_val whenever you have them.
"""
self.base_estimator.fit(X, y)
X_thr, y_thr = (X_val, y_val) if X_val is not None else (X, y)
y_prob = self.base_estimator.predict_proba(X_thr)[:, 1]
protected = X_thr[:, self.protected_attribute_idx]
# Target: the overall TPR at the default 0.5 threshold
positives = y_thr == 1
target_tpr = float(np.mean(y_prob[positives] >= 0.5)) if np.any(positives) else 0.5
for group in np.unique(protected):
group_mask = protected == group
self.thresholds_[group] = self._find_threshold_for_tpr(
y_thr[group_mask], y_prob[group_mask], target_tpr
)
return self
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predict with group-specific thresholds (0.5 for groups not seen in fit)."""
y_prob = self.base_estimator.predict_proba(X)[:, 1]
protected = X[:, self.protected_attribute_idx]
predictions = (y_prob >= 0.5).astype(int)
for group, threshold in self.thresholds_.items():
group_mask = protected == group
predictions[group_mask] = (y_prob[group_mask] >= threshold).astype(int)
return predictions
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Return probabilities from base estimator."""
return self.base_estimator.predict_proba(X)
def _find_threshold_for_tpr(self, y: np.ndarray, y_prob: np.ndarray, target_tpr: float) -> float:
"""Grid search for the threshold whose TPR is closest to target_tpr."""
pos_probs = y_prob[y == 1]
if len(pos_probs) == 0:
return 0.5
best_threshold = 0.5
best_diff = float('inf')
for threshold in np.linspace(0, 1, 101):
diff = abs(np.mean(pos_probs >= threshold) - target_tpr)
if diff < best_diff:
best_diff = diff
best_threshold = threshold
return best_threshold
class FairConstrainedClassifier(BaseEstimator, ClassifierMixin):
"""
In-processing via sample weights that give every protected group the same
total weight. Despite the class name, this is plain reweighting, not
adversarial debiasing or a constrained optimizer.
"""
def __init__(self, base_estimator, protected_attribute_idx: int):
self.base_estimator = base_estimator
self.protected_attribute_idx = protected_attribute_idx
def fit(self, X: np.ndarray, y: np.ndarray) -> 'FairConstrainedClassifier':
"""Fit with group-balancing weights; fails loudly if the estimator can't take them."""
if not has_fit_parameter(self.base_estimator, "sample_weight"):
raise TypeError(
f"{type(self.base_estimator).__name__}.fit does not accept sample_weight"
)
protected = X[:, self.protected_attribute_idx]
weights = self._calculate_debiasing_weights(protected)
self.base_estimator.fit(X, y, sample_weight=weights)
return self
def predict(self, X: np.ndarray) -> np.ndarray:
return self.base_estimator.predict(X)
def predict_proba(self, X: np.ndarray) -> np.ndarray:
return self.base_estimator.predict_proba(X)
def _calculate_debiasing_weights(self, protected: np.ndarray) -> np.ndarray:
"""Weights that balance group sizes, normalized to sum to n."""
n = len(protected)
weights = np.ones(n)
groups = np.unique(protected)
for group in groups:
group_mask = protected == group
weights[group_mask] *= n / (len(groups) * np.sum(group_mask))
return weights / weights.sum() * nContinuous Fairness Monitoring
# fairness_monitoring.py
"""
Production fairness monitoring system.
"""
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional
from datetime import datetime, timedelta, timezone
import numpy as np
@dataclass
class FairnessAlert:
"""Alert for fairness violation."""
alert_id: str
timestamp: datetime
metric_name: str
current_value: float
threshold: float
affected_groups: List[str]
severity: str
description: str
@dataclass
class FairnessSnapshot:
"""Point-in-time fairness snapshot."""
timestamp: datetime
metrics: Dict[str, float]
group_metrics: Dict[str, Dict[str, float]]
sample_size: int
class FairnessMonitor:
"""
Monitor model fairness in production. All timestamps are timezone-aware UTC.
"""
def __init__(
self,
protected_attribute: str,
metrics_config: Dict[str, float], # metric_name -> threshold
alert_callback: Optional[Callable[[FairnessAlert], None]] = None
):
self.protected_attribute = protected_attribute
self.metrics_config = metrics_config
self.alert_callback = alert_callback
self.history: List[FairnessSnapshot] = []
self.alerts: List[FairnessAlert] = []
self.baseline_metrics: Optional[Dict] = None
def set_baseline(self, snapshot: FairnessSnapshot):
"""Set baseline metrics from validation/test set."""
self.baseline_metrics = snapshot.metrics
def record_predictions(
self,
y_true: np.ndarray,
y_pred: np.ndarray,
protected_groups: np.ndarray,
timestamp: Optional[datetime] = None
) -> FairnessSnapshot:
"""Record predictions and calculate fairness metrics."""
if timestamp is None:
timestamp = datetime.now(timezone.utc)
metrics = {}
group_metrics = {}
groups = np.unique(protected_groups)
# Demographic parity
selection_rates = {}
for group in groups:
mask = protected_groups == group
selection_rates[str(group)] = np.mean(y_pred[mask] == 1)
overall_rate = np.mean(y_pred == 1)
metrics['demographic_parity_disparity'] = max(
abs(r - overall_rate) for r in selection_rates.values()
)
group_metrics['selection_rate'] = selection_rates
# Equalized odds
tpr_values = {}
fpr_values = {}
for group in groups:
mask = protected_groups == group
pos_mask = y_true == 1
neg_mask = y_true == 0
if np.sum(pos_mask & mask) > 0:
tpr_values[str(group)] = np.mean(y_pred[pos_mask & mask] == 1)
if np.sum(neg_mask & mask) > 0:
fpr_values[str(group)] = np.mean(y_pred[neg_mask & mask] == 1)
if tpr_values:
metrics['tpr_disparity'] = max(tpr_values.values()) - min(tpr_values.values())
if fpr_values:
metrics['fpr_disparity'] = max(fpr_values.values()) - min(fpr_values.values())
group_metrics['tpr'] = tpr_values
group_metrics['fpr'] = fpr_values
snapshot = FairnessSnapshot(
timestamp=timestamp,
metrics=metrics,
group_metrics=group_metrics,
sample_size=len(y_true)
)
self.history.append(snapshot)
self._check_alerts(snapshot)
return snapshot
def _check_alerts(self, snapshot: FairnessSnapshot):
"""Check if any metrics exceed thresholds."""
for metric_name, threshold in self.metrics_config.items():
if metric_name not in snapshot.metrics:
continue
current_value = snapshot.metrics[metric_name]
if current_value > threshold:
baseline_value = self.baseline_metrics.get(metric_name, 0) if self.baseline_metrics else 0
drift = abs(current_value - baseline_value)
severity = 'critical' if drift > threshold * 2 else 'warning'
alert = FairnessAlert(
alert_id=f"FA-{len(self.alerts)}",
timestamp=snapshot.timestamp,
metric_name=metric_name,
current_value=current_value,
threshold=threshold,
affected_groups=list(snapshot.group_metrics.get('selection_rate', {}).keys()),
severity=severity,
description=f"{metric_name} ({current_value:.3f}) exceeds threshold ({threshold:.3f})"
)
self.alerts.append(alert)
if self.alert_callback:
self.alert_callback(alert)
def get_trend(self, metric_name: str, window_days: int = 7) -> Dict[str, List]:
"""Get metric trend over time."""
cutoff = datetime.now(timezone.utc) - timedelta(days=window_days)
timestamps = []
values = []
for snapshot in self.history:
if snapshot.timestamp >= cutoff and metric_name in snapshot.metrics:
timestamps.append(snapshot.timestamp)
values.append(snapshot.metrics[metric_name])
return {
'timestamps': timestamps,
'values': values,
'trend': self._calculate_trend(values) if len(values) > 1 else 'stable'
}
def _calculate_trend(self, values: List[float]) -> str:
"""Calculate trend direction."""
if len(values) < 2:
return 'stable'
recent = np.mean(values[-5:]) if len(values) >= 5 else values[-1]
older = np.mean(values[:5]) if len(values) >= 5 else values[0]
diff = recent - older
if abs(diff) < 0.01:
return 'stable'
return 'increasing' if diff > 0 else 'decreasing'
def generate_report(self) -> Dict:
"""Generate fairness monitoring report."""
if not self.history:
return {'error': 'No data recorded'}
now = datetime.now(timezone.utc)
latest = self.history[-1]
recent_alerts = [a for a in self.alerts if a.timestamp >= now - timedelta(days=7)]
return {
'report_timestamp': now.isoformat(),
'monitoring_period': {
'start': self.history[0].timestamp.isoformat(),
'end': latest.timestamp.isoformat(),
'total_snapshots': len(self.history)
},
'current_metrics': latest.metrics,
'group_breakdown': latest.group_metrics,
'thresholds': self.metrics_config,
'alerts_summary': {
'total': len(self.alerts),
'recent_7_days': len(recent_alerts),
'by_severity': {
'critical': len([a for a in recent_alerts if a.severity == 'critical']),
'warning': len([a for a in recent_alerts if a.severity == 'warning'])
}
},
'trends': {
metric: self.get_trend(metric)['trend']
for metric in self.metrics_config.keys()
},
# Status against your own thresholds; it is not a legal compliance verdict
'threshold_status': 'WITHIN_THRESHOLDS' if not recent_alerts else 'THRESHOLD_EXCEEDED'
}Conclusion
Building fair AI systems requires:
- Comprehensive measurement using multiple fairness metrics
- Pre-processing techniques like reweighing and disparate impact removal
- In-processing constraints during model training
- Post-processing calibration for equalized outcomes
- Continuous monitoring to detect fairness drift in production
No single metric or technique is sufficient - organizations should adopt a multi-faceted approach based on their specific context and the nature of potential harms.
Official references
- sklearn.utils.validation.has_fit_parameter - scikit-learn 1.9.1 documentation
- Postprocessing - Fairlearn user guide
- datetime - Basic date and time types - Python documentation
Related on this site: Every AI Security Startup Got Acquired. Now What?, Your AI Agent Framework Is Probably Compromised Right Now, AI API Security: Auth, Authorization & Rate Limiting. More articles in the AI Security category, and the engineering work behind them is on the services page.
Need an AI system built and running in production, with the scope agreed in writing and a delivery guarantee? See how a DeviDevs Sprint works →