KLAR / experiments /stats_utils.py
nicofirst1's picture
Publish KLAR reproducibility bundle (v1): text-free score bundles + analysis code for the 'Alles klar?' KlarText paper
f45e98c verified
Raw
History Blame Contribute Delete
3.12 kB
"""Statistical primitives for the evaluation experiments.
Inferential layer: paired significance (Wilcoxon signed-rank), cluster-aware bootstrap
CIs, Benjamini-Hochberg FDR, and AUC (+ bootstrap CI on AUC differences for the ablation).
"""
from __future__ import annotations
from collections import defaultdict
from collections.abc import Callable, Sequence
import numpy as np
from scipy import stats as sps
def auc(pos: Sequence[float], neg: Sequence[float]) -> float:
"""AUC = P(random pos > random neg), via Mann-Whitney U (ties = 0.5)."""
pos = np.asarray(pos, float)
neg = np.asarray(neg, float)
if len(pos) == 0 or len(neg) == 0:
return float("nan")
ranks = sps.rankdata(np.concatenate([pos, neg]))
u = ranks[: len(pos)].sum() - len(pos) * (len(pos) + 1) / 2
return float(u / (len(pos) * len(neg)))
def wilcoxon_p(deltas: Sequence[float], alternative: str = "greater") -> float:
"""Wilcoxon signed-rank p-value on paired deltas (drops zeros)."""
d = np.asarray(deltas, float)
d = d[d != 0]
if len(d) < 1:
return float("nan")
try:
return float(sps.wilcoxon(d, alternative=alternative).pvalue)
except ValueError:
return float("nan")
def cohens_d_paired(deltas: Sequence[float]) -> float:
d = np.asarray(deltas, float)
sd = d.std(ddof=0)
return float(d.mean() / sd) if sd > 0 else float("nan")
def bh_fdr(pvals: Sequence[float]) -> np.ndarray:
"""Benjamini-Hochberg adjusted p-values."""
p = np.asarray(pvals, float)
n = len(p)
order = np.argsort(p)
ranked = p[order] * n / np.arange(1, n + 1)
ranked = np.minimum.accumulate(ranked[::-1])[::-1]
adj = np.empty(n)
adj[order] = np.clip(ranked, 0, 1)
return adj
def cluster_bootstrap_ci(
records: Sequence[dict],
statfn: Callable[[list[dict]], float],
cluster_key: Callable[[dict], str] | None = None,
n: int = 2000,
seed: int = 0,
alpha: float = 0.05,
) -> tuple[float, float]:
"""Percentile CI for `statfn`. If cluster_key is given, resample whole clusters
(accounts for non-independence within a subcorpus); else resample records."""
rng = np.random.default_rng(seed)
recs = list(records)
boot: list[float] = []
keys: list[str] = []
if cluster_key is not None:
groups: dict[str, list[dict]] = defaultdict(list)
for r in recs:
groups[cluster_key(r)].append(r)
keys = list(groups)
if len(keys) < 2: # single cluster → cluster bootstrap is degenerate
cluster_key = None
if cluster_key is not None:
for _ in range(n):
chosen = rng.integers(0, len(keys), size=len(keys))
sample: list[dict] = []
for ci in chosen:
sample.extend(groups[keys[ci]])
boot.append(statfn(sample))
else:
m = len(recs)
for _ in range(n):
idx = rng.integers(0, m, size=m)
boot.append(statfn([recs[i] for i in idx]))
lo, hi = np.nanpercentile(boot, [100 * alpha / 2, 100 * (1 - alpha / 2)])
return float(lo), float(hi)