File size: 6,703 Bytes
f8c91b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Class-wise metrics and confidence-resolution analysis (camera-ready additions).

Derives, offline from the shipped per-trial data:
  1. Per-model confusion matrices (yes = positive class), per-class precision /
     recall / F1, macro-F1, and balanced accuracy under the validated protocol,
     plus pooled rows for the validated and naive protocols
     -> writes ../tables/tcb_classwise.tex (Table: class-wise decomposition).
  2. Confidence-resolution statistics: accuracy on trials with stated
     confidence below 100 versus exactly 100 (pooled and per model), and the
     pooled AUROC of stated confidence for predicting correctness.
  3. Spearman rank correlation between panel accuracy and panel ECE.

Stdlib only; no endpoint, no network.
"""
import json
import pathlib
import statistics

HERE = pathlib.Path(__file__).resolve().parent
DATA = HERE.parent / "data"
TABLES = HERE.parent / "tables"

# Table 1 display order and short names.
ORDER = [
    ("glm-5.1-fp8", "glm"),
    ("deepseek-v4-pro", "deepseek"),
    ("gemma-4-31b", "gemma"),
    ("gptoss-120b", "gptoss"),
    ("leanstral-2603", "leanstral"),
    ("qwen3-omni-30b-a3b", "qwen-omni"),
    ("qwen3.6-35b-a3b-fp8", "qwen3.6-35b"),
    ("qwen3.6-27b-fp8", "qwen3.6-27b"),
    ("qwen3.5-9b", "qwen3.5-9b"),
]


def confusion(trials):
    tp = fn = fp = tn = 0
    for t in trials:
        a = t.get("answer")
        if a not in ("Yes", "No"):
            continue
        if t["truth"] == "Yes":
            tp += a == "Yes"
            fn += a == "No"
        else:
            fp += a == "Yes"
            tn += a == "No"
    return tp, fn, fp, tn


def classwise(tp, fn, fp, tn):
    p_yes = tp / (tp + fp) if tp + fp else float("nan")
    r_yes = tp / (tp + fn) if tp + fn else float("nan")
    f_yes = 2 * p_yes * r_yes / (p_yes + r_yes) if p_yes + r_yes else 0.0
    p_no = tn / (tn + fn) if tn + fn else float("nan")
    r_no = tn / (tn + fp) if tn + fp else float("nan")
    f_no = 2 * p_no * r_no / (p_no + r_no) if p_no + r_no else 0.0
    return dict(p_yes=p_yes, r_yes=r_yes, f_yes=f_yes, p_no=p_no, r_no=r_no,
                f_no=f_no, macro_f1=(f_yes + f_no) / 2, bal_acc=(r_yes + r_no) / 2)


def spearman(x, y):
    def rank(v):
        s = sorted(v)
        return [(sum(1 for u in s if u < a) + (sum(1 for u in s if u == a) + 1) / 2)
                for a in v]
    rx, ry = rank(x), rank(y)
    mx, my = statistics.mean(rx), statistics.mean(ry)
    num = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
    den = (sum((a - mx) ** 2 for a in rx) * sum((b - my) ** 2 for b in ry)) ** 0.5
    return num / den


def main():
    trials = json.load(open(DATA / "tcb_v03_trials.json"))
    naive = json.load(open(DATA / "tcb_v03_trials_naive.json"))

    lines = [
        "\\setlength{\\tabcolsep}{3.0pt}",
        "\\begin{tabular}{lrrrrrrrrrrrr}",
        "\\toprule",
        " & \\multicolumn{4}{c}{Confusion} & \\multicolumn{3}{c}{Yes class}"
        " & \\multicolumn{3}{c}{No class} & & \\\\",
        "\\cmidrule(lr){2-5}\\cmidrule(lr){6-8}\\cmidrule(lr){9-11}",
        "Model & TP & FN & FP & TN & Prec & Rec & F1 & Prec & Rec & F1"
        " & Macro-F1 & Bal.\\ acc. \\\\",
        "\\midrule",
    ]
    pooled_tp = pooled_fn = pooled_fp = pooled_tn = 0
    for model, short in ORDER:
        tp, fn, fp, tn = confusion([t for t in trials if t["model"] == model])
        pooled_tp += tp; pooled_fn += fn; pooled_fp += fp; pooled_tn += tn
        m = classwise(tp, fn, fp, tn)
        lines.append(
            f"{short} & {tp} & {fn} & {fp} & {tn}"
            f" & {m['p_yes']:.3f} & {m['r_yes']:.3f} & {m['f_yes']:.3f}"
            f" & {m['p_no']:.3f} & {m['r_no']:.3f} & {m['f_no']:.3f}"
            f" & {m['macro_f1']:.3f} & {m['bal_acc']:.3f} \\\\")
    lines.append("\\midrule")
    for label, (tp, fn, fp, tn) in (
            ("Pooled (validated)", (pooled_tp, pooled_fn, pooled_fp, pooled_tn)),
            ("Pooled (naive)", confusion(naive))):
        m = classwise(tp, fn, fp, tn)
        lines.append(
            f"{label} & {tp} & {fn} & {fp} & {tn}"
            f" & {m['p_yes']:.3f} & {m['r_yes']:.3f} & {m['f_yes']:.3f}"
            f" & {m['p_no']:.3f} & {m['r_no']:.3f} & {m['f_no']:.3f}"
            f" & {m['macro_f1']:.3f} & {m['bal_acc']:.3f} \\\\")
    lines += ["\\bottomrule", "\\end{tabular}"]
    out = TABLES / "tcb_classwise.tex"
    out.write_text("\n".join(lines) + "\n")
    print(f"wrote {out}")

    # Confidence resolution: does below-ceiling stated confidence predict error?
    stated = [t for t in trials
              if t.get("conf_stated") and t.get("answer") in ("Yes", "No")]
    at100 = [t for t in stated if t["conf"] == 100]
    below = [t for t in stated if t["conf"] < 100]
    acc = lambda ts: sum(t["correct"] for t in ts) / len(ts)
    print(f"stated-confidence trials: {len(stated)}"
          f" (of {sum(1 for t in trials if t.get('answer') in ('Yes','No'))} parseable)")
    print(f"conf = 100: n={len(at100)} acc={acc(at100):.3f}")
    print(f"conf < 100: n={len(below)} acc={acc(below):.3f}")
    for model, short in ORDER:
        lo = [t for t in below if t["model"] == model]
        hi = [t for t in at100 if t["model"] == model]
        if len(lo) >= 10:
            print(f"  {short}: conf<100 n={len(lo)} acc={acc(lo):.3f}"
                  f" vs conf=100 acc={acc(hi):.3f}")
    correct = [t["conf"] for t in stated if t["correct"]]
    wrong = [t["conf"] for t in stated if not t["correct"]]
    wins = sum(1 for a in correct for b in wrong if a > b)
    ties = sum(1 for a in correct for b in wrong if a == b)
    auroc = (wins + 0.5 * ties) / (len(correct) * len(wrong))
    print(f"pooled AUROC(stated conf -> correct) = {auroc:.3f}"
          f" (n_correct={len(correct)}, n_incorrect={len(wrong)})")

    # Accuracy vs ECE rank correlation across the panel (Table 1 values are
    # re-derivable via analyze_panel.py; recomputed here from the trials).
    accs, eces = [], []
    for model, short in ORDER:
        ts = [t for t in trials if t["model"] == model
              and t.get("answer") in ("Yes", "No")]
        accs.append(acc(ts))
        confs = [(t["conf"] if t.get("conf_stated") else 50) / 100 for t in ts]
        bins = [[] for _ in range(5)]
        for c, t in zip(confs, ts):
            bins[min(4, int(c * 5))].append((c, t["correct"]))
        ece = sum(len(b) / len(ts) *
                  abs(statistics.mean(c for c, _ in b) -
                      statistics.mean(k for _, k in b))
                  for b in bins if b)
        eces.append(ece)
    print(f"Spearman(accuracy, ECE) across the panel: {spearman(accs, eces):.3f}")


if __name__ == "__main__":
    main()