Datasets:
Download tests/test_stats.py from b4ph/clap-retrieval-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 6.11 kB
-
https://huggingface.co/datasets/b4ph/clap-retrieval-benchmark/resolve/main/tests/test_stats.py
- Command line
-
hf download hf://datasets/b4ph/clap-retrieval-benchmark/tests/test_stats.py
-
curl -L -o test_stats.py https://huggingface.co/datasets/b4ph/clap-retrieval-benchmark/resolve/main/tests/test_stats.py
6.11 kB
| """Known-answer tests for the v2 statistics. | |
| Every expected value below is derivable by hand or by construction, so a bug in | |
| the bootstrap, the correction, or the equivalence test fails loudly instead of | |
| quietly widening or narrowing a published interval. | |
| python tests/test_stats.py | |
| """ | |
| from __future__ import annotations | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| import analysis_v2 as A # noqa: E402 | |
| FAILS: list[str] = [] | |
| def check(name: str, cond: bool, detail: str = "") -> None: | |
| print(f"{'PASS' if cond else 'FAIL'} {name:<52}{detail}") | |
| if not cond: | |
| FAILS.append(name) | |
| def test_holm() -> None: | |
| print("\n[holm] hand-computed family p = 0.001, 0.02, 0.03, 0.2") | |
| adj = A.holm({"a": 0.001, "b": 0.02, "c": 0.03, "d": 0.2}) | |
| want = {"a": 0.004, "b": 0.06, "c": 0.06, "d": 0.2} | |
| for k, v in want.items(): | |
| check(f"holm {k}", abs(adj[k] - v) < 1e-12, f"got {adj[k]:.6f} want {v}") | |
| check("holm monotone", all(adj[a] <= adj[b] for a, b in | |
| [("a", "b"), ("b", "c"), ("c", "d")])) | |
| check("holm only the smallest survives", adj["a"] < 0.05 and adj["b"] >= 0.05) | |
| def test_tost() -> None: | |
| print("\n[tost] equivalence decisions at margin 0.03") | |
| eq = A.tost(delta=0.000, se=0.008) | |
| check("delta 0.000, se 0.008 -> equivalent", eq["equivalent"], f"p={eq['p']:.2g}") | |
| same = A.tost(delta=0.022, se=0.004) | |
| check("delta 0.022, se 0.004 -> equivalent", same["equivalent"], | |
| f"p={same['p']:.2g} ci90={same['ci90']}") | |
| big = A.tost(delta=0.100, se=0.008) | |
| check("delta 0.100 -> not equivalent", not big["equivalent"], f"p={big['p']:.2g}") | |
| wide = A.tost(delta=0.000, se=0.400) | |
| check("delta 0.000 but se 0.400 -> not equivalent", not wide["equivalent"], | |
| "wide CI cannot prove equivalence") | |
| def test_cluster_bootstrap() -> None: | |
| print("\n[cluster bootstrap] duplicated captions must widen the interval") | |
| n_clips, caps = 100, 5 | |
| rng = np.random.default_rng(0) | |
| clip_hits = (rng.random(n_clips) < 0.5).astype(float) | |
| values = np.repeat(clip_hits, caps) # all captions of a clip agree | |
| clusters = np.repeat(np.arange(n_clips), caps) | |
| lo, hi, se_cluster = A.cluster_bootstrap_mean(values, clusters, lambda v: v.mean()) | |
| naive_se = float(np.sqrt(values.mean() * (1 - values.mean()) / len(values))) | |
| check("cluster SE exceeds naive SE by >1.5x", se_cluster > 1.5 * naive_se, | |
| f"cluster={se_cluster:.4f} naive={naive_se:.4f}") | |
| check("point estimate unchanged", abs(values.mean() - clip_hits.mean()) < 1e-12) | |
| def test_paired_delta() -> None: | |
| # b gains a hit on 20% of the clips where a missed, so the expected delta is | |
| # 0.20 * P(a=0) = 0.20 * 0.70 = 0.14, not 0.20. | |
| print("\n[paired delta] a real +0.14 gap must be detected") | |
| n_clips, caps = 400, 5 | |
| rng = np.random.default_rng(1) | |
| a_clip = (rng.random(n_clips) < 0.30).astype(float) | |
| # b hits wherever a hits, plus 20 points more: correlated arms | |
| b_clip = np.clip(a_clip + (rng.random(n_clips) < 0.20), 0, 1) | |
| a = np.repeat(a_clip, caps) | |
| b = np.repeat(b_clip, caps) | |
| clusters = np.repeat(np.arange(n_clips), caps) | |
| lo, hi, se = A.cluster_bootstrap_delta(a, b, clusters) | |
| delta = float(b.mean() - a.mean()) | |
| check("delta near the constructed 0.14", 0.10 < delta < 0.18, f"delta={delta:+.3f}") | |
| check("CI excludes zero", lo > 0, f"[{lo:+.3f}, {hi:+.3f}]") | |
| check("points to the same delta as the cluster means", | |
| abs(delta - (b_clip.mean() - a_clip.mean())) < 1e-12) | |
| zero = A.cluster_bootstrap_delta(a, a, clusters) | |
| check("identical arms give delta 0 with CI containing 0", | |
| abs(zero[0]) < 1e-9 and zero[0] <= 0 <= zero[1]) | |
| def test_mcnemar() -> None: | |
| print("\n[mcnemar] hand-computed: 1 discordant one way, 9 the other") | |
| a = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 0], dtype=bool) # a right 9x | |
| b = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1], dtype=bool) # b right 1x | |
| p, n01, n10 = A.mcnemar_exact(a, b) | |
| want = 2 * (1 + 10) / 1024 | |
| check("mcnemar p matches exact binomial", abs(p - want) < 1e-12, | |
| f"got {p:.6f} want {want:.6f}") | |
| check("discordant counts", (n01, n10) == (1, 9), f"({n01}, {n10})") | |
| check("identical arms give p=1", A.mcnemar_exact(a, a)[0] == 1.0) | |
| def test_cluster_sign_flip() -> None: | |
| """10 clips favour b, 2 favour a: the exact two-sided sign-flip p is 2*(1+12+66)/4096.""" | |
| print("\n[cluster sign-flip] 12 clips, 10 favour b") | |
| a = np.zeros(12) | |
| b = np.zeros(12) | |
| for i in range(10): | |
| b[i] = 1.0 | |
| for i in range(10, 12): | |
| a[i] = 1.0 | |
| out = A.cluster_sign_flip(a, b, np.arange(12), n_perm=20000) | |
| want = 2 * (1 + 12 + 66) / 4096 | |
| check("delta = 8/12", abs(out["delta"] - 8 / 12) < 1e-12, f"delta={out['delta']:.6f}") | |
| check("p near the exact sign-flip value", abs(out["p_cluster_perm"] - want) < 0.01, | |
| f"got {out['p_cluster_perm']:.4f} want {want:.4f}") | |
| check("n_clusters counted", out["n_clusters"] == 12, f"n={out['n_clusters']}") | |
| def test_cluster_zero_effect() -> None: | |
| print("\n[cluster sign-flip] identical arms give p = 1") | |
| a = np.array([1.0, 0.0, 1.0, 0.0]) | |
| out = A.cluster_sign_flip(a, a, np.arange(4), n_perm=1000) | |
| check("identical arms p = 1", abs(out["p_cluster_perm"] - 1.0) < 1e-12, | |
| f"p={out['p_cluster_perm']:.4f}") | |
| def test_mdd() -> None: | |
| print("\n[mdd] minimum detectable difference shrinks with sample size") | |
| small = A.mdd(0.05) | |
| large = A.mdd(0.01) | |
| check("mdd(0.01) < mdd(0.05)", large < small, f"{large:.3f} vs {small:.3f}") | |
| check("mdd matches 2.80 * se", abs(small - 2.8016 * 0.05) < 1e-3, f"{small:.4f}") | |
| if __name__ == "__main__": | |
| test_holm() | |
| test_tost() | |
| test_cluster_bootstrap() | |
| test_paired_delta() | |
| test_mcnemar() | |
| test_cluster_sign_flip() | |
| test_cluster_zero_effect() | |
| test_mdd() | |
| print("\n" + ("ALL STATS CHECKS PASSED" if not FAILS else f"FAILURES: {FAILS}")) | |
| raise SystemExit(0 if not FAILS else 1) | |