"""Statistical analysis of cross-validation results. Aggregates per-(seed,fold) metrics into mean±std, computes bootstrap 95% CIs from pooled out-of-fold (OOF) predictions, and runs a paired test comparing the proposed model against the best baseline across the 15 evaluations. """ from __future__ import annotations import numpy as np import pandas as pd from sklearn.metrics import f1_score from .metrics import compute_metrics def aggregate_runs(run_metrics: list[dict]) -> dict[str, tuple[float, float]]: """[{metric: value}, ...] over runs -> {metric: (mean, std)}.""" keys = run_metrics[0].keys() out = {} for k in keys: vals = np.array([m[k] for m in run_metrics if not np.isnan(m[k])]) if len(vals): out[k] = (float(vals.mean()), float(vals.std())) return out def bootstrap_ci(oof: pd.DataFrame, metric: str = "macro_f1", n_boot: int = 2000, seed: int = 0) -> tuple[float, float, float]: """Bootstrap 95% CI for a metric over pooled OOF predictions. oof: columns subject_id, y_true, y_pred (+ prob_0..2). Resamples subjects. Returns (point_estimate, lo, hi). """ rng = np.random.default_rng(seed) y_true = oof["y_true"].to_numpy() y_pred = oof["y_pred"].to_numpy() n = len(oof) point = f1_score(y_true, y_pred, labels=[0, 1, 2], average="macro", zero_division=0) stats = np.empty(n_boot) for b in range(n_boot): idx = rng.integers(0, n, n) stats[b] = f1_score(y_true[idx], y_pred[idx], labels=[0, 1, 2], average="macro", zero_division=0) lo, hi = np.percentile(stats, [2.5, 97.5]) return float(point), float(lo), float(hi) def paired_permutation_test(scores_a: list[float], scores_b: list[float], n_perm: int = 10000, seed: int = 0) -> float: """Two-sided paired permutation test on per-run metric differences. scores_a, scores_b: paired per-(seed,fold) metric values (same order). Returns p-value for H0: mean(a-b)=0. """ rng = np.random.default_rng(seed) a, b = np.asarray(scores_a), np.asarray(scores_b) diff = a - b obs = abs(diff.mean()) count = 0 for _ in range(n_perm): signs = rng.choice([-1, 1], size=len(diff)) if abs((diff * signs).mean()) >= obs - 1e-12: count += 1 return (count + 1) / (n_perm + 1) def oof_metrics(oof: pd.DataFrame) -> dict: """Compute the full metric dict on pooled OOF predictions.""" prob_cols = [c for c in oof.columns if c.startswith("prob_")] prob = oof[sorted(prob_cols)].to_numpy() if prob_cols else None return compute_metrics(oof["y_true"].to_numpy(), oof["y_pred"].to_numpy(), prob)