File size: 7,559 Bytes
fb47aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""Bootstrap confidence intervals and paired model comparisons.

Reads the per-query JSON written by `eval_clap_tf.py --per-query`, so every
number carries an interval derived from the actual queries rather than a single
point estimate.

    python analysis.py results_final            # writes analysis.json + prints
    python analysis.py results_final --paired clotho

Bootstrap: 2000 resamples over queries, fixed seed. The paired comparison uses
the shared fixture fingerprint to guarantee both checkpoints scored the same
clip/caption sequence, then resamples queries *together* (paired bootstrap) and
reports a McNemar exact test on the discordant pairs.
"""
from __future__ import annotations

import argparse
import json
import math
from pathlib import Path

import numpy as np

SEED = 12345
N_BOOT = 2000


def _ci(values: np.ndarray, stat, n_boot: int = N_BOOT, seed: int = SEED):
    """Percentile bootstrap. Returns (low, high, standard error)."""
    rng = np.random.default_rng(seed)
    n = len(values)
    draws = np.empty(n_boot, dtype=np.float64)
    for i in range(n_boot):
        idx = rng.integers(0, n, n)
        draws[i] = stat(values[idx])
    return (float(np.percentile(draws, 2.5)), float(np.percentile(draws, 97.5)),
            float(draws.std(ddof=1)))


def cell_stats(d: dict) -> dict:
    """Recompute headline metrics from per-query arrays and bootstrap them."""
    t2a, a2t = d["metrics"]["t2a"], d["metrics"]["a2t"]
    tr = np.asarray(t2a["first_hit_rank"], dtype=np.int64)
    ar = np.asarray(a2t["first_hit_rank"], dtype=np.int64)
    aap = np.asarray(a2t["ap"], dtype=np.float64)

    out = {"model": d["model"], "dataset": d["dataset"], "tag": d.get("tag"),
           "audio_batch": d["protocol"]["audio_batch"],
           "trim_seconds": d["protocol"]["trim_seconds"],
           "fixture_fingerprint": d.get("fixture_fingerprint"),
           "counts": d["counts"], "metrics": {}}

    specs = [
        ("t2a_r1", tr, lambda v: float((v == 1).mean()), t2a["r@1"]),
        ("t2a_r5", tr, lambda v: float((v <= 5).mean()), t2a["r@5"]),
        ("t2a_r10", tr, lambda v: float((v <= 10).mean()), t2a["r@10"]),
        ("t2a_mrr", tr, lambda v: float((1.0 / v).mean()), t2a["map"]),
        ("a2t_r1", ar, lambda v: float((v == 1).mean()), a2t["r@1"]),
        ("a2t_r5", ar, lambda v: float((v <= 5).mean()), a2t["r@5"]),
        ("a2t_r10", ar, lambda v: float((v <= 10).mean()), a2t["r@10"]),
        ("a2t_map", aap, lambda v: float(v.mean()), a2t["map"]),
    ]
    for name, arr, stat, reported in specs:
        point = stat(arr)
        lo, hi, se = _ci(arr, stat)
        # the bootstrap point must reproduce the harness's own number
        assert abs(point - reported) < 1e-6, (name, point, reported)
        out["metrics"][name] = {"value": point, "ci95": [lo, hi], "se": se}
    out["metrics"]["n_queries"] = {"t2a": int(len(tr)), "a2t": int(len(ar))}
    # kept in memory for the paired tests; stripped before the JSON is written
    out["_pq"] = {"t2a": tr, "a2t": ar, "a2t_ap": aap}
    return out


def paired(a: dict, b: dict, metric: str = "r@1") -> dict:
    """Paired bootstrap on two cells of the same fixture, plus McNemar for hits."""
    assert a["fixture_fingerprint"] == b["fixture_fingerprint"], (
        "fixtures differ; paired comparison is not legitimate")

    if metric.endswith("map"):
        va = a["_pq"]["a2t_ap"].astype(np.float64)
        vb = b["_pq"]["a2t_ap"].astype(np.float64)
        n = len(va)
        diff = float(vb.mean() - va.mean())
        rng = np.random.default_rng(SEED)
        deltas = np.empty(N_BOOT)
        for i in range(N_BOOT):
            idx = rng.integers(0, n, n)
            deltas[i] = vb[idx].mean() - va[idx].mean()
        return {"a": a["model"], "b": b["model"], "metric": metric,
                "delta": diff,
                "ci95": [float(np.percentile(deltas, 2.5)),
                         float(np.percentile(deltas, 97.5))],
                "n": n, "discordant_a_only": None, "discordant_b_only": None,
                "mcnemar_exact_p": None}

    if metric.startswith("t2a"):
        xa, xb = a["_pq"]["t2a"], b["_pq"]["t2a"]
    else:
        xa, xb = a["_pq"]["a2t"], b["_pq"]["a2t"]
    k = int(metric.split("r@")[1])
    ha, hb = xa <= k, xb <= k
    n = len(ha)
    diff = float(hb.mean() - ha.mean())

    rng = np.random.default_rng(SEED)
    deltas = np.empty(N_BOOT)
    for i in range(N_BOOT):
        idx = rng.integers(0, n, n)
        deltas[i] = hb[idx].mean() - ha[idx].mean()
    lo, hi = float(np.percentile(deltas, 2.5)), float(np.percentile(deltas, 97.5))

    n01 = int((~ha & hb).sum())   # a misses, b hits
    n10 = int((ha & ~hb).sum())   # a hits, b misses
    m = n01 + n10
    # exact two-sided binomial under p=0.5
    if m == 0:
        p = 1.0
    else:
        tail = sum(math.comb(m, i) for i in range(0, min(n01, n10) + 1)) / 2 ** m
        p = min(1.0, 2 * tail)

    return {"a": a["model"], "b": b["model"], "metric": metric,
            "delta": diff, "ci95": [lo, hi], "n": n,
            "discordant_a_only": n10, "discordant_b_only": n01,
            "mcnemar_exact_p": p}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("dir", nargs="?", default="results_final")
    ap.add_argument("--out", default="analysis.json")
    args = ap.parse_args()

    files = sorted(Path(args.dir).glob("*.json"))
    files = [f for f in files if "summary" not in f.name]
    if not files:
        print(f"no result JSONs in {args.dir}")
        return 1
    cells = []
    for f in files:
        d = json.loads(f.read_text(encoding="utf-8"))
        if "first_hit_rank" not in d["metrics"]["t2a"]:
            print(f"skip {f.name}: no per-query arrays (rerun with --per-query)")
            continue
        cells.append(cell_stats(d))

    pairs = []
    by_key = {}
    for c in cells:
        if c["audio_batch"] == 1 and c["trim_seconds"] == 10.0:
            by_key.setdefault(c["dataset"], {})[c["model"]] = c
    for ds, models in by_key.items():
        ids = sorted(models)
        if len(ids) == 2 and "clap-htsat-fused" in ids[0] + ids[1]:
            a, b = models[ids[0]], models[ids[1]]
            for metric in ("t2a r@1", "a2t r@1", "a2t map"):
                pairs.append(paired(a, b, metric))

    print(f"{'model':<28}{'ds':<10}{'metric':<10}{'value':>8}  95% CI")
    for c in cells:
        for k, v in c["metrics"].items():
            if k == "n_queries":
                continue
            print(f"{c['model']:<28}{c['dataset']:<10}{k:<10}{v['value']:>8.3f}  "
                  f"[{v['ci95'][0]:.3f}, {v['ci95'][1]:.3f}]")
    if pairs:
        print("\npaired comparisons (same fixture, resampled together)")
        for p in pairs:
            mcn = ("n/a" if p["mcnemar_exact_p"] is None
                   else f"{p['mcnemar_exact_p']:.3g}")
            disc = ("n/a" if p["discordant_a_only"] is None
                    else f"{p['discordant_a_only']}/{p['discordant_b_only']}")
            print(f"{p['a']} -> {p['b']} | {p['metric']}: delta {p['delta']:+.3f} "
                  f"[{p['ci95'][0]:+.3f}, {p['ci95'][1]:+.3f}], "
                  f"discordant {disc}, McNemar p={mcn}")

    # per-query arrays are large and only needed in memory
    slim = [{k: v for k, v in c.items() if k != "_pq"} for c in cells]
    Path(args.out).write_text(
        json.dumps({"cells": slim, "paired": pairs}, indent=2), encoding="utf-8")
    print(f"\nwrote {args.out}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())