| |
| |
| """ |
| 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"} |
|
|
| |
| 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) |
|
|
| |
| 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 |
| 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 |
|
|
| |
| 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() |
|
|