| """Detection + fairness metrics following the paper's definitions.""" |
| from __future__ import annotations |
|
|
| from typing import Dict, List, Sequence |
|
|
| import numpy as np |
| from sklearn.metrics import roc_auc_score, accuracy_score, roc_curve |
|
|
|
|
| def _tpr_at_fpr(y_true: np.ndarray, y_score: np.ndarray, fpr_target: float) -> float: |
| fpr, tpr, _ = roc_curve(y_true, y_score) |
| if (fpr <= fpr_target).any(): |
| return float(tpr[fpr <= fpr_target].max()) |
| return 0.0 |
|
|
|
|
| def compute_detection_metrics(y_true, y_score) -> Dict[str, float]: |
| y_true = np.asarray(y_true); y_score = np.asarray(y_score) |
| try: |
| auc = roc_auc_score(y_true, y_score) |
| except ValueError: |
| auc = float("nan") |
| acc = accuracy_score(y_true, (y_score > 0.5).astype(int)) |
| t1 = _tpr_at_fpr(y_true, y_score, 0.01) |
| t01 = _tpr_at_fpr(y_true, y_score, 0.001) |
| return {"auc": auc, "acc": acc, "tpr@fpr=1%": t1, "tpr@fpr=0.1%": t01} |
|
|
|
|
| def compute_fairness_metrics( |
| y_true: Sequence[int], |
| y_score: Sequence[float], |
| groups: Sequence[str], |
| ) -> Dict[str, float]: |
| """F_FPR, F_MEO, F_DP, F_OAE — stdev-type measures across groups.""" |
| y_true = np.asarray(y_true); y_score = np.asarray(y_score) |
| groups = np.asarray(groups) |
|
|
| def _group_fpr(g): |
| m = (groups == g) & (y_true == 0) |
| if m.sum() == 0: return 0.0 |
| return float(((y_score > 0.5)[m]).mean()) |
|
|
| def _group_tpr(g): |
| m = (groups == g) & (y_true == 1) |
| if m.sum() == 0: return 0.0 |
| return float(((y_score > 0.5)[m]).mean()) |
|
|
| def _group_acc(g): |
| m = (groups == g) |
| if m.sum() == 0: return 0.0 |
| return float(((y_score > 0.5)[m] == y_true[m]).mean()) |
|
|
| def _group_dp(g): |
| m = (groups == g) |
| if m.sum() == 0: return 0.0 |
| return float((y_score > 0.5)[m].mean()) |
|
|
| uniq = sorted(set(groups.tolist())) |
| fprs = [_group_fpr(g) for g in uniq] |
| tprs = [_group_tpr(g) for g in uniq] |
| accs = [_group_acc(g) for g in uniq] |
| dps = [_group_dp(g) for g in uniq] |
|
|
| def _std(xs): return float(np.std(xs)) * 100 |
|
|
| return { |
| "F_FPR": _std(fprs), |
| "F_MEO": max(max(fprs) - min(fprs), max(tprs) - min(tprs)) * 100, |
| "F_DP": _std(dps), |
| "F_OAE": _std(accs), |
| "group_fprs": {g: v for g, v in zip(uniq, fprs)}, |
| "group_accs": {g: v for g, v in zip(uniq, accs)}, |
| } |
|
|