"""Paired statistics against Laya on identical rows. * ``mcnemar``: exact two-sided McNemar test (binomial on the discordant pairs). * ``paired_bootstrap``: case-cluster bootstrap (resample ``group_id`` clusters with replacement; every decision of a resampled case comes along) of metric(A) - metric(B), percentile CI. Metrics: accuracy, nll, brier, ece (15-bin), soft_accuracy, score_mae. Rows are aligned by ``id``; only ids that are ``ok`` in both files are compared, and the number of rows dropped for that reason is reported. """ from __future__ import annotations import math import numpy as np from .metrics import ece, per_row METRICS = ("accuracy", "nll", "brier", "ece", "soft_accuracy", "score_mae") def mcnemar(a_correct, b_correct) -> dict: a, b = np.asarray(a_correct, bool), np.asarray(b_correct, bool) b01 = int((~a & b).sum()) # A wrong, B right b10 = int((a & ~b).sum()) # A right, B wrong n = b01 + b10 if n == 0: p = 1.0 else: k = min(b01, b10) tail = sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n p = min(1.0, 2 * tail) return {"n": int(len(a)), "a_only_correct": b10, "b_only_correct": b01, "p_value": float(p)} def align(rows_a: list[dict], rows_b: list[dict], temps_a=None, temps_b=None): pa = {d["id"]: d for d in per_row(rows_a, temps_a)} pb = {d["id"]: d for d in per_row(rows_b, temps_b)} ids = [i for i in pa if i in pb] all_ids = {r["id"] for r in rows_a} | {r["id"] for r in rows_b} return [pa[i] for i in ids], [pb[i] for i in ids], len(all_ids) - len(ids) def _metric_arrays(d: list[dict]) -> dict: out = {"correct": np.array([x["correct"] for x in d]), "conf": np.array([x["conf"] for x in d]), "nll": np.array([x["nll"] for x in d]), "brier": np.array([x["brier"] for x in d])} if d and all("soft_acc" in x for x in d): out["soft_accuracy"] = np.array([x["soft_acc"] for x in d]) score = [x.get("abs_err_score") for x in d] out["score_mask"] = np.array([s is not None for s in score]) out["score_mae"] = np.array([s if s is not None else 0.0 for s in score]) return out def _weighted(arr: dict, w: np.ndarray, metric: str) -> float: if metric == "accuracy": return float((w * arr["correct"]).sum() / w.sum()) if metric in ("nll", "brier", "soft_accuracy"): return float((w * arr[metric]).sum() / w.sum()) if metric == "ece": return ece(arr["conf"], arr["correct"], weights=w) if metric == "score_mae": ww = w * arr["score_mask"] return float((ww * arr["score_mae"]).sum() / ww.sum()) if ww.sum() > 0 else float("nan") raise KeyError(metric) def paired_bootstrap(rows_a: list[dict], rows_b: list[dict], metrics=METRICS, n_boot: int = 2000, seed: int = 0, temps_a=None, temps_b=None, alpha: float = 0.05) -> dict: da, db, dropped = align(rows_a, rows_b, temps_a, temps_b) if not da: return {"n": 0, "dropped_unpaired": dropped} A, B = _metric_arrays(da), _metric_arrays(db) clusters = {} cl = np.array([clusters.setdefault(x["group_id"], len(clusters)) for x in da]) n_cl = len(clusters) rng = np.random.default_rng(seed) out = {"n": len(da), "n_clusters": n_cl, "dropped_unpaired": dropped, "n_boot": n_boot, "mcnemar": mcnemar(A["correct"], B["correct"])} ones = np.ones(len(da)) def available(m): if m in ("accuracy", "nll", "brier", "ece"): return True if m == "score_mae": return bool(A["score_mask"].any() and B["score_mask"].any()) return m in A and m in B reps = {m: [] for m in metrics if available(m)} for _ in range(n_boot): counts = np.bincount(rng.integers(0, n_cl, n_cl), minlength=n_cl) w = counts[cl].astype(float) for m in reps: reps[m].append(_weighted(A, w, m) - _weighted(B, w, m)) for m, vals in reps.items(): vals = np.asarray(vals) vals = vals[~np.isnan(vals)] a, b = _weighted(A, ones, m), _weighted(B, ones, m) out[m] = {"a": a, "b": b, "diff": a - b, "ci": [float(np.quantile(vals, alpha / 2)), float(np.quantile(vals, 1 - alpha / 2))] if len(vals) else [float("nan"), float("nan")]} return out