File size: 7,638 Bytes
bb5e4ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Generate publication-quality 300-DPI figures strictly from audited CSV/NPZ artifacts."""
from __future__ import annotations

from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import auc, roc_curve

REPO_ROOT = Path(__file__).resolve().parents[1]
RES_DIR = REPO_ROOT / "results"
FIG_DIR = REPO_ROOT / "figures"

plt.rcParams.update({
    "font.size": 10,
    "axes.titlesize": 11,
    "axes.labelsize": 10,
    "figure.dpi": 300,
})


def plot_priority1_comparison() -> None:
    df = pd.read_csv(RES_DIR / "priority1_test_evaluation.csv")
    npz = np.load(RES_DIR / "priority1_predictions.npz")
    labels = npz["labels"]

    # 1. Confusion matrices (all 5 verified Aug-12 models)
    fig, axes = plt.subplots(1, 5, figsize=(18, 3.6))
    for ax, (_, row) in zip(axes, df.iterrows()):
        cm = np.array([[row["tn"], row["fp"]], [row["fn"], row["tp"]]])
        ax.imshow(cm, cmap="Blues")
        for r in range(2):
            for c in range(2):
                color = "white" if cm[r, c] > cm.max() * 0.55 else "black"
                ax.text(c, r, f"{cm[r, c]}", ha="center", va="center", color=color, fontsize=11, fontweight="bold")
        ax.set_xticks([0, 1])
        ax.set_xticklabels(["NORMAL", "PNEU"], fontsize=8)
        ax.set_yticks([0, 1])
        ax.set_yticklabels(["NORMAL", "PNEU"], fontsize=8)
        ax.set_xlabel("Predicted")
        if ax is axes[0]:
            ax.set_ylabel("True")
        short = row["model"].replace("Ablation_", "").replace("Student_", "").replace("Baseline_", "")
        ax.set_title(f"{short}\nAcc={row['accuracy_pct']:.2f}% | F1={row['f1']:.3f}", fontsize=9)
    fig.suptitle("Held-Out Kermany Test (N=624, Fixed Threshold t=0.50) — Confusion Matrices", fontweight="bold")
    fig.tight_layout()
    fig.savefig(FIG_DIR / "fig1_priority1_confusion_matrices.png", dpi=300)
    plt.close(fig)

    # 2. Side-by-side ROC Curves & 10-bin Reliability Calibration Curves
    fig, (ax_roc, ax_cal) = plt.subplots(1, 2, figsize=(12, 5.0))
    colors = ["#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e"]
    for color, (_, row) in zip(colors, df.iterrows()):
        mname = row["model"]
        probs = npz[f"probs_{mname}"]
        fpr, tpr, _ = roc_curve(labels, probs)
        roc_val = auc(fpr, tpr)
        label_txt = f"{mname.replace('Ablation_', '').replace('_', ' ')} (AUC={roc_val:.3f}, ECE={row['ece']:.3f})"
        ax_roc.plot(fpr, tpr, lw=2.0, color=color, label=label_txt)

        # Reliability bin stats
        preds = (probs >= 0.50).astype(int)
        confs = np.where(preds == 1, probs, 1.0 - probs)
        correct = (preds == labels).astype(float)
        edges = np.linspace(0.5, 1.0, 6)
        bx, by = [], []
        for lo, hi in zip(edges[:-1], edges[1:]):
            mask = (confs >= lo) & (confs <= hi if hi == 1.0 else confs < hi)
            if mask.sum() >= 5:
                bx.append(confs[mask].mean())
                by.append(correct[mask].mean())
        ax_cal.plot(bx, by, marker="o", lw=1.8, color=color, label=f"{mname.replace('Ablation_', '')} (Brier={row['brier_score']:.3f})")

    ax_roc.plot([0, 1], [0, 1], "k--", alpha=0.5)
    ax_roc.set_title("ROC Curves (Ranking Performance)")
    ax_roc.set_xlabel("False Positive Rate (1 - Specificity)")
    ax_roc.set_ylabel("True Positive Rate (Sensitivity)")
    ax_roc.legend(loc="lower right", fontsize=7.5)
    ax_roc.grid(alpha=0.25)

    ax_cal.plot([0.5, 1.0], [0.5, 1.0], "k--", alpha=0.5, label="Perfect calibration")
    ax_cal.set_title("Confidence Reliability at Operating Boundary")
    ax_cal.set_xlabel("Mean Predicted Confidence")
    ax_cal.set_ylabel("Empirical Accuracy")
    ax_cal.legend(loc="lower right", fontsize=7.5)
    ax_cal.grid(alpha=0.25)

    fig.suptitle("Calibration vs. Ranking Analysis: Why BioHCL-SSSM Leads at Fixed t=0.50", fontweight="bold")
    fig.tight_layout()
    fig.savefig(FIG_DIR / "fig2_roc_and_calibration.png", dpi=300)
    plt.close(fig)


def plot_priority3_cv() -> None:
    cv_path = RES_DIR / "priority3_patient_groupkfold.csv"
    npz_path = RES_DIR / "priority3_oof_predictions.npz"
    if not cv_path.exists() or not npz_path.exists():
        return
    df_cv = pd.read_csv(cv_path)
    npz = np.load(npz_path)
    labels = npz["labels"]
    probs = npz["probs"]
    preds = (probs >= 0.50).astype(int)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.6))
    x = np.arange(len(df_cv))
    w = 0.25
    ax1.bar(x - w, df_cv["accuracy_pct"], width=w, label="Accuracy %", color="#2b8cbe")
    ax1.bar(x, df_cv["macro_f1"] * 100.0, width=w, label="Macro-F1 x100", color="#1b9e77")
    ax1.bar(x + w, df_cv["roc_auc"] * 100.0, width=w, label="ROC-AUC x100", color="#7570b3")
    ax1.set_xticks(x)
    ax1.set_xticklabels([f"Fold {f}\n({n} imgs)" for f, n in zip(df_cv["fold"], df_cv["val_images"])])
    ax1.set_ylim(max(50, df_cv["accuracy_pct"].min() - 10), 102)
    ax1.set_ylabel("Score (%)")
    ax1.set_title(f"5-Fold Patient-Grouped CV (0 Patient/MD5 Overlap)\nMean Acc={df_cv['accuracy_pct'].mean():.2f}% +/- {df_cv['accuracy_pct'].std(ddof=1):.2f}%")
    ax1.legend(fontsize=8)
    ax1.grid(axis="y", alpha=0.25)

    from sklearn.metrics import confusion_matrix
    cm = confusion_matrix(labels, preds, labels=[0, 1])
    ax2.imshow(cm, cmap="Blues")
    for r in range(2):
        for c in range(2):
            color = "white" if cm[r, c] > cm.max() * 0.55 else "black"
            ax2.text(c, r, f"{cm[r, c]}", ha="center", va="center", color=color, fontsize=12, fontweight="bold")
    ax2.set_xticks([0, 1])
    ax2.set_xticklabels(["NORMAL", "PNEUMONIA"])
    ax2.set_yticks([0, 1])
    ax2.set_yticklabels(["NORMAL", "PNEUMONIA"])
    ax2.set_xlabel("Predicted (t=0.50)")
    ax2.set_ylabel("True")
    ax2.set_title(f"Pooled OOF Confusion Matrix (N={len(labels)})")

    fig.suptitle("Priority 3: Clean Patient-Grouped 5-Fold Cross-Validation", fontweight="bold")
    fig.tight_layout()
    fig.savefig(FIG_DIR / "fig3_priority3_patient_cv.png", dpi=300)
    plt.close(fig)


def plot_priority4_ablations() -> None:
    ab_path = RES_DIR / "priority4_clean_ablations.csv"
    if not ab_path.exists():
        return
    df_ab = pd.read_csv(ab_path)
    fig, ax = plt.subplots(figsize=(10.5, 5.8))
    y = np.arange(len(df_ab))
    bar_colors = ["#c51b7d" if s != "CONVERGED" else "#1b9e77" for s in df_ab["status"]]
    ax.barh(y, df_ab["test_acc_pct"], color=bar_colors, alpha=0.88)
    err_lo = df_ab["test_acc_pct"] - df_ab["test_acc_ci95_low"]
    err_hi = df_ab["test_acc_ci95_high"] - df_ab["test_acc_pct"]
    ax.errorbar(df_ab["test_acc_pct"], y, xerr=[err_lo, err_hi], fmt="none", ecolor="black", elinewidth=1.0, capsize=3)
    ax.set_yticks(y)
    ax.set_yticklabels([f"{r['variant']} ({r['status']})" for _, r in df_ab.iterrows()], fontsize=8.5)
    ax.invert_yaxis()
    ax.set_xlabel("Held-Out Kermany Test Accuracy (%) at Fixed t=0.50 [95% CI]")
    ax.set_title("Priority 4: Unified 256-d Controlled Ablation Suite (Green=Converged, Magenta=Collapsed)")
    ax.set_xlim(50, 100)
    ax.grid(axis="x", alpha=0.25)
    for i, r in df_ab.iterrows():
        ax.text(r["test_acc_ci95_high"] + 0.6, i, f"{r['test_acc_pct']:.2f}% (F1={r['test_f1']:.3f})", va="center", fontsize=8)
    fig.tight_layout()
    fig.savefig(FIG_DIR / "fig4_priority4_ablations.png", dpi=300)
    plt.close(fig)


if __name__ == "__main__":
    FIG_DIR.mkdir(parents=True, exist_ok=True)
    plot_priority1_comparison()
    plot_priority3_cv()
    plot_priority4_ablations()
    print("Generated figures in", FIG_DIR)