Datasets:
File size: 8,283 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 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 175 176 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unified evaluation for ALL models (RETFound / ResNet / ViT).
Reads <run_dir>/test_pred.npz (y_true:(N,), y_prob:(N,C)) saved by every training
run, then computes the full classification metric suite and writes:
<run_dir>/metrics.json
<run_dir>/confusion_matrix.png (counts + row-normalized)
<run_dir>/roc.png (binary: 1 curve; multiclass: per-class OvR + macro/micro)
<run_dir>/pr.png (precision-recall, same layout)
Using one shared script guarantees identical metric definitions across the 3 models.
"""
import os, sys, json, argparse
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.metrics import (accuracy_score, balanced_accuracy_score, f1_score,
precision_score, recall_score, cohen_kappa_score,
matthews_corrcoef, roc_auc_score, average_precision_score,
roc_curve, precision_recall_curve, confusion_matrix,
classification_report)
def _safe(fn, *a, **k):
try:
return float(fn(*a, **k))
except Exception:
return None
def compute_metrics(y_true, y_prob):
y_true = np.asarray(y_true).astype(int)
y_prob = np.asarray(y_prob)
C = y_prob.shape[1]
y_pred = y_prob.argmax(1)
classes = list(range(C))
y_true_oh = np.eye(C)[y_true]
binary = (C == 2)
m = {"n_test": int(len(y_true)), "n_classes": C, "task": "binary" if binary else "multiclass"}
# ---- threshold-based (argmax) ----
m["accuracy"] = _safe(accuracy_score, y_true, y_pred)
m["balanced_accuracy"] = _safe(balanced_accuracy_score, y_true, y_pred)
m["precision_macro"] = _safe(precision_score, y_true, y_pred, average="macro", zero_division=0)
m["recall_macro"] = _safe(recall_score, y_true, y_pred, average="macro", zero_division=0)
m["f1_macro"] = _safe(f1_score, y_true, y_pred, average="macro", zero_division=0)
m["precision_weighted"] = _safe(precision_score, y_true, y_pred, average="weighted", zero_division=0)
m["recall_weighted"] = _safe(recall_score, y_true, y_pred, average="weighted", zero_division=0)
m["f1_weighted"] = _safe(f1_score, y_true, y_pred, average="weighted", zero_division=0)
m["cohen_kappa"] = _safe(cohen_kappa_score, y_true, y_pred)
m["quadratic_weighted_kappa"] = _safe(cohen_kappa_score, y_true, y_pred, weights="quadratic")
m["mcc"] = _safe(matthews_corrcoef, y_true, y_pred)
# ---- probability-based ----
if binary:
s = y_prob[:, 1]
m["auroc"] = _safe(roc_auc_score, y_true, s)
m["auprc"] = _safe(average_precision_score, y_true, s)
cm = confusion_matrix(y_true, y_pred, labels=classes)
tn, fp, fn, tp = cm.ravel()
m["sensitivity"] = float(tp / (tp + fn)) if (tp + fn) else None # recall of positive
m["specificity"] = float(tn / (tn + fp)) if (tn + fp) else None
m["precision_pos"] = float(tp / (tp + fp)) if (tp + fp) else None
m["f1_pos"] = _safe(f1_score, y_true, y_pred, pos_label=1, zero_division=0)
else:
m["auroc_macro_ovr"] = _safe(roc_auc_score, y_true_oh, y_prob, multi_class="ovr", average="macro")
m["auroc_weighted_ovr"] = _safe(roc_auc_score, y_true_oh, y_prob, multi_class="ovr", average="weighted")
m["auprc_macro"] = _safe(average_precision_score, y_true_oh, y_prob, average="macro")
per_auc = {}
for c in classes:
per_auc[str(c)] = _safe(roc_auc_score, (y_true == c).astype(int), y_prob[:, c])
m["auroc_per_class"] = per_auc
# per-class report (precision/recall/f1/support)
m["per_class"] = classification_report(y_true, y_pred, labels=classes,
output_dict=True, zero_division=0)
return m, y_true, y_pred, y_prob
def plot_confusion(y_true, y_pred, C, names, path):
cm = confusion_matrix(y_true, y_pred, labels=list(range(C)))
cmn = cm.astype(float) / cm.sum(1, keepdims=True).clip(min=1)
fig, axes = plt.subplots(1, 2, figsize=(6 * 2, 5))
for ax, mat, title, fmt in [(axes[0], cm, "Confusion (counts)", "d"),
(axes[1], cmn, "Confusion (row-normalized)", ".2f")]:
im = ax.imshow(mat, cmap="Blues", vmin=0, vmax=(cm.max() if fmt == "d" else 1))
ax.set_xticks(range(C)); ax.set_yticks(range(C))
ax.set_xticklabels(names, rotation=45, ha="right"); ax.set_yticklabels(names)
ax.set_xlabel("Predicted"); ax.set_ylabel("True"); ax.set_title(title)
for i in range(C):
for j in range(C):
v = mat[i, j]
ax.text(j, i, format(v, fmt), ha="center", va="center",
color="white" if v > (mat.max() * 0.6) else "black", fontsize=8)
fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
fig.tight_layout(); fig.savefig(path, dpi=200, bbox_inches="tight"); plt.close(fig)
def plot_roc(y_true, y_prob, C, names, path):
fig, ax = plt.subplots(figsize=(6, 5))
if C == 2:
fpr, tpr, _ = roc_curve(y_true, y_prob[:, 1])
auc = roc_auc_score(y_true, y_prob[:, 1])
ax.plot(fpr, tpr, label=f"ROC (AUC={auc:.3f})")
else:
y_oh = np.eye(C)[y_true]
for c in range(C):
try:
fpr, tpr, _ = roc_curve(y_oh[:, c], y_prob[:, c])
auc = roc_auc_score(y_oh[:, c], y_prob[:, c])
ax.plot(fpr, tpr, label=f"{names[c]} (AUC={auc:.3f})", lw=1)
except Exception:
pass
try:
macro = roc_auc_score(y_oh, y_prob, multi_class="ovr", average="macro")
ax.plot([], [], " ", label=f"macro-AUC={macro:.3f}")
except Exception:
pass
ax.plot([0, 1], [0, 1], "k--", lw=0.8)
ax.set_xlabel("False Positive Rate"); ax.set_ylabel("True Positive Rate")
ax.set_title("ROC"); ax.legend(fontsize=8, loc="lower right")
fig.tight_layout(); fig.savefig(path, dpi=200, bbox_inches="tight"); plt.close(fig)
def plot_pr(y_true, y_prob, C, names, path):
fig, ax = plt.subplots(figsize=(6, 5))
if C == 2:
prec, rec, _ = precision_recall_curve(y_true, y_prob[:, 1])
ap = average_precision_score(y_true, y_prob[:, 1])
ax.plot(rec, prec, label=f"PR (AP={ap:.3f})")
else:
y_oh = np.eye(C)[y_true]
for c in range(C):
try:
prec, rec, _ = precision_recall_curve(y_oh[:, c], y_prob[:, c])
ap = average_precision_score(y_oh[:, c], y_prob[:, c])
ax.plot(rec, prec, label=f"{names[c]} (AP={ap:.3f})", lw=1)
except Exception:
pass
ax.set_xlabel("Recall"); ax.set_ylabel("Precision")
ax.set_title("Precision-Recall"); ax.legend(fontsize=8, loc="lower left")
fig.tight_layout(); fig.savefig(path, dpi=200, bbox_inches="tight"); plt.close(fig)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--run_dir", required=True)
ap.add_argument("--class_names", default="")
args = ap.parse_args()
npz = os.path.join(args.run_dir, "test_pred.npz")
if not os.path.isfile(npz):
print(f"[evaluate] missing {npz}", file=sys.stderr); sys.exit(1)
d = np.load(npz)
y_true, y_prob = d["y_true"], d["y_prob"]
C = y_prob.shape[1]
names = args.class_names.split(",") if args.class_names else [str(i) for i in range(C)]
if len(names) != C:
names = [str(i) for i in range(C)]
metrics, y_true, y_pred, y_prob = compute_metrics(y_true, y_prob)
with open(os.path.join(args.run_dir, "metrics.json"), "w") as f:
json.dump(metrics, f, indent=2)
plot_confusion(y_true, y_pred, C, names, os.path.join(args.run_dir, "confusion_matrix.png"))
plot_roc(y_true, y_prob, C, names, os.path.join(args.run_dir, "roc.png"))
plot_pr(y_true, y_prob, C, names, os.path.join(args.run_dir, "pr.png"))
key = "auroc" if C == 2 else "auroc_macro_ovr"
print(f"[evaluate] {args.run_dir} acc={metrics['accuracy']:.4f} "
f"{key}={metrics.get(key)} f1_macro={metrics['f1_macro']:.4f} "
f"qwk={metrics['quadratic_weighted_kappa']}")
if __name__ == "__main__":
main()
|