Datasets:
File size: 5,887 Bytes
3c366de | 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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Read downsample experiment results and generate:
results/downsample/summary.csv — all metrics by dataset/frac/model
results/downsample/curve_<model>.png — AUROC vs training samples, per model facet
Plus print a readable table.
"""
import os, json, csv
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
PROJ = "/mnt/tidal-alsh-share2/dataset/qinshengqian/research/c3/GPT-Image"
RES = f"{PROJ}/results/downsample"
OUT = RES
FRACTIONS = [100, 50, 25, 10, 5]
MODELS = ["retfound", "resnet", "vit"]
MLABEL = {"retfound": "RetFound (ViT-L, CFP)", "resnet": "ResNet-50", "vit": "ViT-B/16"}
MCOLOR = {"retfound": "#4C72B0", "resnet": "#55A868", "vit": "#C44E52"}
DSETS = ["adam", "airogs", "papila"]
DNAME = {"adam": "ADAM (AMD)", "airogs": "AIROGS (Glaucoma)", "papila": "PAPILA (Glaucoma)"}
TRAIN_COUNTS = { # stratified train set size per fraction
"adam": {100: 280, 50: 140, 25: 70, 10: 28, 5: 14},
"airogs": {100: 5000, 50: 2500, 25: 1250, 10: 500, 5: 250},
"papila": {100: 294, 50: 146, 25: 73, 10: 29, 5: 15},
}
def load(dsk, frac, model):
p = os.path.join(RES, dsk, f"{frac:03d}", model, "metrics.json")
try:
return json.load(open(p))
except Exception:
return None
def main():
rows = []
for dsk in DSETS:
for frac in FRACTIONS:
for model in MODELS:
m = load(dsk, frac, model)
n = TRAIN_COUNTS[dsk][frac]
if m:
au = m.get("auroc") if m.get("task") == "binary" else m.get("auroc_macro_ovr")
rows.append({"dataset": dsk, "frac": frac, "n_train": n, "model": model,
"acc": m.get("accuracy"), "auroc": au, "f1": m.get("f1_macro"),
"kappa": m.get("cohen_kappa"), "mcc": m.get("mcc"),
"n_test": m.get("n_test")})
# write CSV
os.makedirs(OUT, exist_ok=True)
csvp = os.path.join(OUT, "summary.csv")
with open(csvp, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=["dataset", "frac", "n_train", "model",
"acc", "auroc", "f1", "kappa", "mcc", "n_test"])
w.writeheader(); w.writerows(rows)
print(f"wrote {csvp} ({len(rows)} rows)\n")
# print table
for dsk in DSETS:
print(f"\n### {DNAME[dsk]}")
print(f"{'Frac':>5} {'n':>5} ", end="")
for model in MODELS:
print(f" {model[:8]:>8}", end="")
print()
for frac in FRACTIONS:
print(f"{frac:>4}% {TRAIN_COUNTS[dsk][frac]:>5} ", end="")
for model in MODELS:
m = load(dsk, frac, model)
au = m.get("auroc") if m and m.get("task") == "binary" else (m.get("auroc_macro_ovr") if m else None)
print(f" {au:>8.4f}" if au else " NaN ", end="")
print()
# learn curve plots: one facet per model, 3x1 layout
for model in MODELS:
fig, axes = plt.subplots(1, 3, figsize=(15, 4.5), sharey=True)
for i, dsk in enumerate(DSETS):
ax = axes[i]
xs, ys = [], []
for frac in sorted(FRACTIONS):
m = load(dsk, frac, model)
n = TRAIN_COUNTS[dsk][frac]
au = m.get("auroc") if m and m.get("task") == "binary" else (m.get("auroc_macro_ovr") if m else None)
if au is not None:
xs.append(n); ys.append(au)
if xs:
ax.plot(xs, ys, "o-", color=MCOLOR[model], lw=2, markersize=7)
# annotate
for x, y in zip(xs, ys):
ax.text(x, y, f" {y:.3f}", fontsize=8, va="bottom")
ax.set_xscale("log")
ax.set_xlabel("Training samples (log scale)")
ax.set_ylabel("AUROC" if i == 0 else "")
ax.set_title(f"{DNAME[dsk]}", fontsize=11, fontweight="bold")
ax.grid(True, ls=":", alpha=0.4)
ax.set_xticks(sorted([TRAIN_COUNTS[dsk][f] for f in FRACTIONS]))
ax.set_xticklabels([str(TRAIN_COUNTS[dsk][f]) for f in FRACTIONS], fontsize=8)
ax.set_ylim(0.35, 1.02)
fig.suptitle(f"{MLABEL[model]} · Data Scarcity Curve", fontsize=13, fontweight="bold", y=1.02)
fig.tight_layout()
figp = os.path.join(OUT, f"curve_{model}.png")
fig.savefig(figp, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f" wrote {figp}")
# combined: all models on ADAM only (paper-style)
fig, ax = plt.subplots(figsize=(6, 4.5))
for model in MODELS:
xs, ys = [], []
for frac in sorted(FRACTIONS):
m = load("adam", frac, model)
au = m.get("auroc") if m and m.get("task") == "binary" else (m.get("auroc_macro_ovr") if m else None)
_n = TRAIN_COUNTS["adam"][frac]
if au is not None:
xs.append(_n); ys.append(au)
ax.plot(xs, ys, "o-", label=MLABEL[model], color=MCOLOR[model], lw=2, markersize=7)
for x, y in zip(xs, ys):
ax.text(x, y, f" {y:.3f}", fontsize=7, va="bottom", color=MCOLOR[model])
ax.set_xscale("log"); ax.set_xlabel("Training samples (log scale)"); ax.set_ylabel("AUROC")
ax.set_title("ADAM (AMD) · 3 models", fontweight="bold")
ax.set_xticks(sorted([TRAIN_COUNTS["adam"][f] for f in FRACTIONS]))
ax.set_xticklabels([str(TRAIN_COUNTS["adam"][f]) for f in FRACTIONS])
ax.set_ylim(0.4, 1.02); ax.legend(fontsize=8); ax.grid(True, ls=":", alpha=0.4)
fig.tight_layout()
fig.savefig(os.path.join(OUT, "curve_adam_combined.png"), dpi=150, bbox_inches="tight")
plt.close(fig)
print(" wrote adam combined curve")
print(f"\n=== summary csv: {csvp} ===")
if __name__ == "__main__":
main()
|