Download code/analyze_tcb.py from ai4he/trust-calibration-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 8.66 kB
-
https://huggingface.co/datasets/ai4he/trust-calibration-benchmark/resolve/main/code/analyze_tcb.py
- Command line
-
hf download hf://datasets/ai4he/trust-calibration-benchmark/code/analyze_tcb.py
-
curl -L -o analyze_tcb.py https://huggingface.co/datasets/ai4he/trust-calibration-benchmark/resolve/main/code/analyze_tcb.py
8.66 kB
| """TCB-v0.2 analysis: recompute calibration metrics with confidence intervals and make figures. | |
| Reads the per-trial experiment file, applies any gold-label corrections (LABEL_FIXES), recomputes | |
| correctness against the corrected gold, and reports per-model accuracy (Wilson CI), Brier | |
| (bootstrap CI), ECE at 5 and 10 equal-width bins (bootstrap CI), and per-tier accuracy. | |
| Confidence comes from each model's self-reported CONF (0-100); the predicted probability that a | |
| model's own answer is correct is CONF/100, so Brier and ECE are computed on (CONF/100, correct). | |
| """ | |
| import json, math, random, sys, pathlib | |
| import matplotlib; matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from collections import defaultdict | |
| HERE = pathlib.Path(__file__).resolve().parent | |
| EXP = HERE / ".." / "data" / "tcb_v02_trials.json" | |
| OUT = HERE / ".." / "data" / "tcb_v02_results.json" | |
| FIG = HERE / ".." / "figures" | |
| # Gold-label corrections from the independent fact-check audit (id -> corrected truth). | |
| LABEL_FIXES = {"g7": "Yes"} # independent fact-check: Astana IS the capital of Kazakhstan (was mislabeled "No") | |
| MODELS = ["glm-5.1-fp8", "gptoss-120b", "gemma-4-31b", "qwen3.5-9b"] | |
| def wilson(x, n): | |
| if n == 0: return (0.0, 0.0) | |
| p = x/n; z = 1.96; d = 1 + z*z/n | |
| c = (p + z*z/(2*n))/d; m = z*math.sqrt(p*(1-p)/n + z*z/(4*n*n))/d | |
| return (max(0, c-m), min(1, c+m)) | |
| def brier(rows): | |
| return sum((r["conf"]/100 - r["correct"])**2 for r in rows)/len(rows) | |
| def ece(rows, nbins): | |
| bins = defaultdict(list) | |
| for r in rows: | |
| p = r["conf"]/100; b = min(nbins-1, int(p*nbins)); bins[b].append(r) | |
| n = len(rows); e = 0.0 | |
| for rs in bins.values(): | |
| conf = sum(x["conf"]/100 for x in rs)/len(rs); acc = sum(x["correct"] for x in rs)/len(rs) | |
| e += len(rs)/n*abs(conf-acc) | |
| return e | |
| def boot_ci(rows, fn, B=2000, seed=0): | |
| rng = random.Random(seed); vals = [] | |
| for _ in range(B): | |
| s = [rows[rng.randrange(len(rows))] for _ in rows] | |
| try: vals.append(fn(s)) | |
| except Exception: pass | |
| vals.sort(); return (vals[int(.025*len(vals))], vals[int(.975*len(vals))]) | |
| def reliability(rows, nbins=5): | |
| """Return (bin_centers, bin_acc, bin_conf, bin_count) for a reliability diagram.""" | |
| bins = defaultdict(list) | |
| for r in rows: | |
| p = r["conf"]/100; b = min(nbins-1, int(p*nbins)); bins[b].append(r) | |
| centers, accs, confs, counts = [], [], [], [] | |
| for b in range(nbins): | |
| rs = bins.get(b, []) | |
| centers.append((b+0.5)/nbins) | |
| if rs: | |
| accs.append(sum(x["correct"] for x in rs)/len(rs)) | |
| confs.append(sum(x["conf"]/100 for x in rs)/len(rs)); counts.append(len(rs)) | |
| else: | |
| accs.append(None); confs.append(None); counts.append(0) | |
| return centers, accs, confs, counts | |
| def main(): | |
| trials = json.load(open(EXP)) | |
| for r in trials: # apply label corrections, recompute correctness | |
| if r["id"] in LABEL_FIXES: | |
| r["truth"] = LABEL_FIXES[r["id"]] | |
| r["correct"] = int(r["answer"] == r["truth"]) | |
| by = defaultdict(list) | |
| for r in trials: by[r["model"]].append(r) | |
| results = {"n_label_fixes": len(LABEL_FIXES), "label_fixes": LABEL_FIXES, "per_model": {}} | |
| for m in MODELS: | |
| rows = by[m]; n = len(rows); x = sum(r["correct"] for r in rows) | |
| easy = [r for r in rows if r["tier"] == "easy"]; hard = [r for r in rows if r["tier"] == "hard"] | |
| results["per_model"][m] = { | |
| "n": n, | |
| "accuracy": round(x/n, 4), "accuracy_CI": [round(v, 4) for v in wilson(x, n)], | |
| "brier": round(brier(rows), 4), "brier_CI": [round(v, 4) for v in boot_ci(rows, brier)], | |
| "ece10": round(ece(rows, 10), 4), | |
| "ece5": round(ece(rows, 5), 4), "ece5_CI": [round(v, 4) for v in boot_ci(rows, lambda rs: ece(rs, 5))], | |
| "acc_easy": round(sum(r["correct"] for r in easy)/len(easy), 4), | |
| "acc_hard": round(sum(r["correct"] for r in hard)/len(hard), 4), | |
| "acc_easy_CI": [round(v, 4) for v in wilson(sum(r["correct"] for r in easy), len(easy))], | |
| "acc_hard_CI": [round(v, 4) for v in wilson(sum(r["correct"] for r in hard), len(hard))], | |
| } | |
| accs = [results["per_model"][m]["accuracy"] for m in MODELS] | |
| results["accuracy_spread_pp"] = round((max(accs)-min(accs))*100, 1) | |
| json.dump(results, open(OUT, "w"), indent=2) | |
| # Emit the LaTeX results table fragment so the paper never hand-types these numbers. | |
| def ci(p): return f"[{p[0]:.2f}, {p[1]:.2f}]" | |
| lines = [r"\begin{tabular}{lrrrrr}", r"\toprule", | |
| r"Model & $n$ & Accuracy [95\% CI] & ECE-5 [95\% CI] & Brier & Acc easy / hard \\", r"\midrule"] | |
| for m in MODELS: | |
| r = results["per_model"][m] | |
| lines.append(f"{m.replace('-','{-}')} & {r['n']} & {r['accuracy']:.3f} {ci(r['accuracy_CI'])} & " | |
| f"{r['ece5']:.3f} {ci(r['ece5_CI'])} & {r['brier']:.3f} & " | |
| f"{r['acc_easy']:.3f} / {r['acc_hard']:.3f} \\\\") | |
| lines += [r"\bottomrule", r"\end{tabular}"] | |
| (HERE / ".." / "tables").mkdir(exist_ok=True) | |
| # Write to a v0.2-specific path so this historical 4-model analyzer can never overwrite the | |
| # canonical 9-model Table 1 that analyze_panel.py produces at tables/tcb_results.tex. | |
| (HERE / ".." / "tables" / "tcb_results_v02.tex").write_text("\n".join(lines) + "\n") | |
| plt.rcParams.update({"font.size": 14, "axes.titlesize": 15, "axes.labelsize": 14, | |
| "xtick.labelsize": 12, "ytick.labelsize": 12, "legend.fontsize": 12}) | |
| short = {"glm-5.1-fp8": "glm", "gptoss-120b": "gptoss", "gemma-4-31b": "gemma", "qwen3.5-9b": "qwen"} | |
| colors = {"glm-5.1-fp8": "#2c7fb8", "gptoss-120b": "#31a354", "gemma-4-31b": "#756bb1", "qwen3.5-9b": "#d95f0e"} | |
| # Figure 1: reliability diagrams (4 panels) | |
| fig, axes = plt.subplots(2, 2, figsize=(8.4, 7.4)) | |
| for ax, m in zip(axes.flat, MODELS): | |
| c, acc, conf, cnt = reliability(by[m], 5) | |
| ax.plot([0, 1], [0, 1], ls="--", color="#999999", lw=1.2) | |
| xs = [conf[i] for i in range(5) if acc[i] is not None] | |
| ys = [acc[i] for i in range(5) if acc[i] is not None] | |
| ax.plot(xs, ys, "o-", color=colors[m], lw=2, ms=7) | |
| r = results["per_model"][m] | |
| ax.set_title(f"{short[m]}: acc {r['accuracy']:.2f}, ECE {r['ece5']:.2f}") | |
| ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.set_xlabel("confidence"); ax.set_ylabel("accuracy") | |
| ax.grid(alpha=0.25) | |
| fig.suptitle("Reliability diagrams (5 equal-width bins; dashed = perfect calibration)", y=0.995) | |
| plt.tight_layout(); plt.savefig(FIG / "tcb_reliability.pdf", bbox_inches="tight") | |
| plt.savefig(FIG / "tcb_reliability.png", dpi=150, bbox_inches="tight"); plt.close() | |
| # Figure 2: accuracy forest with Wilson CIs | |
| fig, ax = plt.subplots(figsize=(6.6, 3.2)) | |
| ys = range(len(MODELS)) | |
| for y, m in zip(ys, MODELS): | |
| r = results["per_model"][m]; a = r["accuracy"]; lo, hi = r["accuracy_CI"] | |
| ax.errorbar(a, y, xerr=[[a-lo], [hi-a]], fmt="o", color=colors[m], capsize=5, ms=8, lw=2) | |
| ax.text(a, y+0.16, f"{a:.3f}", ha="center", fontsize=11) | |
| ax.set_yticks(list(ys)); ax.set_yticklabels([short[m] for m in MODELS]) | |
| ax.set_xlabel("accuracy (Wilson 95% CI)"); ax.set_xlim(0.4, 1.02) | |
| ax.axvline(0.7, ls=":", color="#cc0000", lw=1.2); ax.text(0.7, -0.7, "gate 0.70", color="#cc0000", fontsize=10, ha="center") | |
| ax.set_title(f"Four-model accuracy panel ({results['accuracy_spread_pp']} pp spread)") | |
| ax.grid(axis="x", alpha=0.25); plt.tight_layout() | |
| plt.savefig(FIG / "tcb_forest.pdf", bbox_inches="tight"); plt.savefig(FIG / "tcb_forest.png", dpi=150, bbox_inches="tight"); plt.close() | |
| # Figure 3: per-tier accuracy | |
| fig, ax = plt.subplots(figsize=(6.8, 3.6)) | |
| xpos = list(range(len(MODELS))); w = 0.38 | |
| ev = [results["per_model"][m]["acc_easy"] for m in MODELS] | |
| hv = [results["per_model"][m]["acc_hard"] for m in MODELS] | |
| ax.bar([x-w/2 for x in xpos], ev, w, label="easy", color="#9ecae1", edgecolor="black", lw=0.6) | |
| ax.bar([x+w/2 for x in xpos], hv, w, label="hard", color="#fc9272", edgecolor="black", lw=0.6) | |
| ax.set_xticks(xpos); ax.set_xticklabels([short[m] for m in MODELS]) | |
| ax.set_ylabel("accuracy"); ax.set_ylim(0, 1.05); ax.legend(); ax.set_title("Accuracy by difficulty tier") | |
| ax.grid(axis="y", alpha=0.25); plt.tight_layout() | |
| plt.savefig(FIG / "tcb_tiers.pdf", bbox_inches="tight"); plt.savefig(FIG / "tcb_tiers.png", dpi=150, bbox_inches="tight"); plt.close() | |
| print(json.dumps(results, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |