"""Evaluation metrics, 10,000-bootstrap confidence intervals, and exact McNemar test.""" from __future__ import annotations import numpy as np from scipy.stats import binomtest, chi2, rankdata from sklearn.metrics import ( accuracy_score, average_precision_score, confusion_matrix, f1_score, precision_score, recall_score, roc_auc_score, ) def compute_classification_metrics( labels: np.ndarray, probs_pos: np.ndarray, threshold: float = 0.50 ) -> dict[str, float | int]: """Compute binary & macro clinical metrics strictly at fixed probability `threshold`.""" labels = np.asarray(labels, dtype=np.int64) probs_pos = np.asarray(probs_pos, dtype=np.float64) preds = (probs_pos >= threshold).astype(np.int64) tn, fp, fn, tp = confusion_matrix(labels, preds, labels=[0, 1]).ravel() specificity = float(tn / (tn + fp)) if (tn + fp) > 0 else 0.0 roc_auc = float(roc_auc_score(labels, probs_pos)) if len(np.unique(labels)) > 1 else 0.0 pr_auc = ( float(average_precision_score(labels, probs_pos)) if len(np.unique(labels)) > 1 else 0.0 ) brier_score = float(np.mean((probs_pos - labels) ** 2)) # Top-label Expected Calibration Error (Guo et al., 2017) with 10 uniform bins confidences = np.where(preds == 1, probs_pos, 1.0 - probs_pos) accuracies = (preds == labels).astype(np.float64) ece = 0.0 bin_edges = np.linspace(0.0, 1.0, 11) for b_idx in range(10): lo, hi = bin_edges[b_idx], bin_edges[b_idx + 1] if b_idx == 0: mask = (confidences >= lo) & (confidences <= hi) else: mask = (confidences > lo) & (confidences <= hi) if np.any(mask): ece += float(np.mean(mask)) * abs(float(np.mean(accuracies[mask])) - float(np.mean(confidences[mask]))) return { "threshold": float(threshold), "n": int(len(labels)), "accuracy": float(accuracy_score(labels, preds)), "precision": float(precision_score(labels, preds, pos_label=1, zero_division=0)), "recall": float(recall_score(labels, preds, pos_label=1, zero_division=0)), "specificity": specificity, "f1": float(f1_score(labels, preds, pos_label=1, zero_division=0)), "macro_f1": float(f1_score(labels, preds, average="macro", zero_division=0)), "roc_auc": roc_auc, "pr_auc": pr_auc, "brier_score": brier_score, "ece": float(ece), "tn": int(tn), "fp": int(fp), "fn": int(fn), "tp": int(tp), "unique_preds": int(len(np.unique(preds))), } def bootstrap_confidence_intervals( labels: np.ndarray, probs_pos: np.ndarray, threshold: float = 0.50, n_boot: int = 10000, seed: int = 42, ) -> dict[str, tuple[float, float]]: """Compute non-parametric stratified-free 95% percentile bootstrap CIs.""" labels = np.asarray(labels, dtype=np.int64) probs_pos = np.asarray(probs_pos, dtype=np.float64) preds = (probs_pos >= threshold).astype(np.int64) n = len(labels) rng = np.random.default_rng(seed) accs = np.empty(n_boot, dtype=np.float64) f1s = np.empty(n_boot, dtype=np.float64) sens = np.empty(n_boot, dtype=np.float64) specs = np.empty(n_boot, dtype=np.float64) aucs = np.empty(n_boot, dtype=np.float64) for i in range(n_boot): idx = rng.integers(0, n, size=n) yb = labels[idx] pb = preds[idx] qb = probs_pos[idx] tp = np.sum((yb == 1) & (pb == 1)) tn = np.sum((yb == 0) & (pb == 0)) fp = np.sum((yb == 0) & (pb == 1)) fn = np.sum((yb == 1) & (pb == 0)) accs[i] = (tp + tn) / n denom_f1 = 2 * tp + fp + fn f1s[i] = (2 * tp / denom_f1) if denom_f1 > 0 else 0.0 sens[i] = (tp / (tp + fn)) if (tp + fn) > 0 else 0.0 specs[i] = (tn / (tn + fp)) if (tn + fp) > 0 else 0.0 n_pos = tp + fn n_neg = tn + fp if n_pos > 0 and n_neg > 0: ranks = rankdata(qb, method="average") aucs[i] = (ranks[yb == 1].sum() - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg) else: aucs[i] = np.nan def _ci(arr: np.ndarray) -> tuple[float, float]: clean = arr[~np.isnan(arr)] return float(np.percentile(clean, 2.5)), float(np.percentile(clean, 97.5)) return { "accuracy_ci95": _ci(accs), "f1_ci95": _ci(f1s), "recall_ci95": _ci(sens), "specificity_ci95": _ci(specs), "roc_auc_ci95": _ci(aucs), } def exact_mcnemar_test( labels: np.ndarray, preds_a: np.ndarray, preds_b: np.ndarray, n_boot: int = 10000, seed: int = 42, ) -> dict[str, float | int]: """Compare paired classifiers A vs B via exact McNemar binomial test + continuity chi2.""" labels = np.asarray(labels, dtype=np.int64) correct_a = np.asarray(preds_a, dtype=np.int64) == labels correct_b = np.asarray(preds_b, dtype=np.int64) == labels n11 = int(np.sum(correct_a & correct_b)) n10 = int(np.sum(correct_a & ~correct_b)) # A right, B wrong n01 = int(np.sum(~correct_a & correct_b)) # A wrong, B right n00 = int(np.sum(~correct_a & ~correct_b)) discordant = n10 + n01 exact_p = float(binomtest(min(n10, n01), discordant, 0.5, alternative="two-sided").pvalue) if discordant > 0 else 1.0 if discordant > 0: stat_cc = ((abs(n10 - n01) - 1.0) ** 2) / discordant if abs(n10 - n01) >= 1 else 0.0 chi2_p = float(chi2.sf(stat_cc, df=1)) else: stat_cc, chi2_p = 0.0, 1.0 rng = np.random.default_rng(seed) n = len(labels) deltas = np.empty(n_boot, dtype=np.float64) diff_vec = correct_a.astype(np.float64) - correct_b.astype(np.float64) for i in range(n_boot): idx = rng.integers(0, n, size=n) deltas[i] = diff_vec[idx].mean() return { "n_total": int(n), "both_correct": n11, "a_only_correct": n10, "b_only_correct": n01, "both_wrong": n00, "acc_diff_a_minus_b": float(diff_vec.mean()), "acc_diff_ci95_low": float(np.percentile(deltas, 2.5)), "acc_diff_ci95_high": float(np.percentile(deltas, 97.5)), "mcnemar_exact_p": exact_p, "mcnemar_chi2_cc": float(stat_cc), "mcnemar_chi2_cc_p": chi2_p, }