import numpy as np
from sklearn.metrics import classification_report
from scipy import stats
class BiasDetector:
def __init__(self, protected_attributes):
self.protected_attributes = protected_attributes
def calculate_statistical_parity(self, y_true, y_pred, protected_groups):
"""计算统计奇偶性差异"""
disparities = {}
for group_name, group_mask in protected_groups.items():
group_rate = np.mean(y_pred[group_mask])
overall_rate = np.mean(y_pred)
disparities[group_name] = group_rate - overall_rate
return disparities
def calculate_equalized_odds(self, y_true, y_pred, protected_groups):
"""计算均等化赔率"""
odds_ratios = {}
for group_name, group_mask in protected_groups.items():
group_tpr = np.sum((y_true == 1) & (y_pred == 1) & group_mask) / np.sum((y_true == 1) & group_mask)
group_fpr = np.sum((y_true == 0) & (y_pred == 1) & group_mask) / np.sum((y_true == 0) & group_mask)
odds_ratios[group_name] = {'TPR': group_tpr, 'FPR': group_fpr}
return odds_ratios