"""Render the paper's figures from results// OOF predictions and summaries. Figures (saved under results/figures/): fig_main_comparison.png Macro-F1 mean±std bar chart across all models fig_confusion_.png pooled 3x3 confusion matrix (row-normalized) per model fig_roc_.png one-vs-rest ROC curves (CN/VMD/AD) per model fig_subgroup.png Macro-F1 by age band and sex for the strongest models All figures are regenerated deterministically from saved OOF preds; no re-training. Models without a summary.json yet are silently skipped, so this can run while the grid is still in progress. """ from __future__ import annotations import json import sys from pathlib import Path import numpy as np import pandas as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 from sklearn.metrics import roc_curve, auc # noqa: E402 ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) RESULTS = ROOT / "results" FIGURES = RESULTS / "figures" SUBJECTS_CSV = ROOT / "data/metadata/subjects_clean.csv" from trifuse.eval.metrics import CLASS_NAMES, confusion # noqa: E402 from trifuse.analysis.subgroup import subgroup_table # noqa: E402 # display order + labels (same keys as make_tables.MAIN_ORDER) MODELS = [ ("xgboost", "XGBoost"), ("tabular_mlp", "MLP"), ("resnet50", "ResNet50"), ("densenet2p5d", "DenseNet121"), ("resnet3d", "3D ResNet18"), ("vit_b16", "ViT-B/16"), ("swin3d", "3D Swin-T"), ("hcct", "3D HCCT"), ("vswin_lite", "VSwinFormer-lite"), ("densenet_latefusion", "DenseNet+concat"), ("trifuse_ad", "TriFuse-AD"), ] PROB_COLS = ["prob_0", "prob_1", "prob_2"] def _summary(name): p = RESULTS / name / "summary.json" return json.loads(p.read_text()) if p.exists() else None def _oof(name): p = RESULTS / name / "oof.csv" return pd.read_csv(p) if p.exists() else None def fig_main_comparison(): names, means, stds = [], [], [] for key, disp in MODELS: s = _summary(key) if s is None: continue m = s["summary"]["macro_f1"] names.append(disp) means.append(m["mean"] * 100) stds.append(m["std"] * 100) if not names: return colors = ["#4c72b0"] * len(names) if "TriFuse-AD" in names: colors[names.index("TriFuse-AD")] = "#c44e52" fig, ax = plt.subplots(figsize=(10, 5)) y = np.arange(len(names)) ax.barh(y, means, xerr=stds, color=colors, capsize=3, alpha=0.9) ax.set_yticks(y) ax.set_yticklabels(names) ax.invert_yaxis() ax.set_xlabel("Macro-F1 (%) — mean ± std over 15 runs") ax.set_title("Three-stage classification (CN / VMD / AD), OASIS-1 age≥60") ax.grid(axis="x", alpha=0.3) for yi, mv in zip(y, means): ax.text(mv + 1, yi, f"{mv:.1f}", va="center", fontsize=8) fig.tight_layout() fig.savefig(FIGURES / "fig_main_comparison.png", dpi=150) plt.close(fig) def fig_confusion(name, disp): oof = _oof(name) if oof is None: return cm = confusion(oof["y_true"].to_numpy(), oof["y_pred"].to_numpy()) cmn = cm / cm.sum(axis=1, keepdims=True).clip(min=1) fig, ax = plt.subplots(figsize=(4.2, 3.8)) im = ax.imshow(cmn, cmap="Blues", vmin=0, vmax=1) ax.set_xticks(range(3)); ax.set_yticks(range(3)) ax.set_xticklabels(CLASS_NAMES); ax.set_yticklabels(CLASS_NAMES) ax.set_xlabel("Predicted"); ax.set_ylabel("True") ax.set_title(f"{disp} (pooled 15 runs)") for i in range(3): for j in range(3): ax.text(j, i, f"{cmn[i, j]:.2f}\n({cm[i, j]})", ha="center", va="center", color="white" if cmn[i, j] > 0.5 else "black", fontsize=8) fig.colorbar(im, ax=ax, fraction=0.046) fig.tight_layout() fig.savefig(FIGURES / f"fig_confusion_{name}.png", dpi=150) plt.close(fig) def fig_roc(name, disp): oof = _oof(name) if oof is None or not set(PROB_COLS).issubset(oof.columns): return y = oof["y_true"].to_numpy() prob = oof[PROB_COLS].to_numpy() fig, ax = plt.subplots(figsize=(4.5, 4.2)) for c, cname in enumerate(CLASS_NAMES): yc = (y == c).astype(int) if yc.sum() == 0: continue fpr, tpr, _ = roc_curve(yc, prob[:, c]) ax.plot(fpr, tpr, label=f"{cname} (AUC={auc(fpr, tpr):.2f})") ax.plot([0, 1], [0, 1], "k--", alpha=0.4) ax.set_xlabel("False positive rate"); ax.set_ylabel("True positive rate") ax.set_title(f"{disp} — one-vs-rest ROC") ax.legend(loc="lower right", fontsize=8) fig.tight_layout() fig.savefig(FIGURES / f"fig_roc_{name}.png", dpi=150) plt.close(fig) def fig_subgroup(): """Macro-F1 by age band / sex for the models that have OOF, focused on the strongest.""" if not SUBJECTS_CSV.exists(): return have = [(k, d) for k, d in MODELS if (RESULTS / k / "oof.csv").exists()] # prefer TriFuse-AD + best MRI-only + a tabular shortcut, if present pick = [kd for kd in have if kd[0] in {"trifuse_ad", "resnet3d", "xgboost", "densenet_latefusion"}] pick = pick or have[:3] if not pick: return subgroups = ["Overall", "60-69", "70-79", "80+", "Male", "Female"] fig, ax = plt.subplots(figsize=(9, 4.5)) width = 0.8 / len(pick) x = np.arange(len(subgroups)) for i, (key, disp) in enumerate(pick): t = subgroup_table(RESULTS / key / "oof.csv", SUBJECTS_CSV).set_index("subgroup") vals = [t.loc[g, "macro_f1"] * 100 if g in t.index and "macro_f1" in t.columns and not pd.isna(t.loc[g, "macro_f1"]) else 0 for g in subgroups] ax.bar(x + i * width, vals, width, label=disp) ax.set_xticks(x + width * (len(pick) - 1) / 2) ax.set_xticklabels(subgroups) ax.set_ylabel("Macro-F1 (%)") ax.set_title("Subgroup robustness (pooled OOF)") ax.legend(fontsize=8) ax.grid(axis="y", alpha=0.3) fig.tight_layout() fig.savefig(FIGURES / "fig_subgroup.png", dpi=150) plt.close(fig) def main(): FIGURES.mkdir(parents=True, exist_ok=True) fig_main_comparison() for key, disp in MODELS: fig_confusion(key, disp) fig_roc(key, disp) fig_subgroup() made = sorted(p.name for p in FIGURES.glob("*.png")) print(f"wrote {len(made)} figures to {FIGURES}:") for m in made: print(" ", m) if __name__ == "__main__": main()