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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Leave-One-Image-Out Cross-Validation (LOOCV) evaluation runner.
|
| 3 |
+
|
| 4 |
+
For each fold:
|
| 5 |
+
test: held-out image
|
| 6 |
+
val: next image (for threshold tuning)
|
| 7 |
+
train: remaining images
|
| 8 |
+
|
| 9 |
+
CRITICAL: Image-level splits ONLY. Patch-level splits inflate F1 by 5-15%.
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
python evaluate_loocv.py --config config/config.yaml
|
| 13 |
+
python evaluate_loocv.py --config config/config.yaml --ensemble-dir checkpoints/
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import pandas as pd
|
| 22 |
+
import torch
|
| 23 |
+
import yaml
|
| 24 |
+
|
| 25 |
+
from src.evaluate import match_detections_to_gt
|
| 26 |
+
from src.heatmap import extract_peaks
|
| 27 |
+
from src.model import ImmunogoldCenterNet
|
| 28 |
+
from src.postprocess import (
|
| 29 |
+
apply_structural_mask_filter,
|
| 30 |
+
cross_class_nms,
|
| 31 |
+
sweep_confidence_threshold,
|
| 32 |
+
)
|
| 33 |
+
from src.preprocessing import discover_synapse_data, load_synapse
|
| 34 |
+
from src.ensemble import ensemble_predict, sliding_window_inference
|
| 35 |
+
from src.visualize import overlay_annotations
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def parse_args():
|
| 39 |
+
parser = argparse.ArgumentParser(description="LOOCV evaluation")
|
| 40 |
+
parser.add_argument("--config", type=str, default="config/config.yaml")
|
| 41 |
+
parser.add_argument("--ensemble-dir", type=str, default="checkpoints",
|
| 42 |
+
help="Directory containing fold_*/phase3_*.pth")
|
| 43 |
+
parser.add_argument("--device", type=str, default="auto")
|
| 44 |
+
parser.add_argument("--use-tta", action="store_true")
|
| 45 |
+
parser.add_argument("--fold", type=str, default=None,
|
| 46 |
+
help="Evaluate a single fold (e.g., S1). If omitted, runs all folds.")
|
| 47 |
+
parser.add_argument("--output", type=str, default="results/loocv_metrics.csv")
|
| 48 |
+
return parser.parse_args()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def load_fold_models(ensemble_dir: Path, fold_id: str, cfg: dict,
|
| 52 |
+
device: torch.device):
|
| 53 |
+
"""Load all models for a fold (5 seeds × 3 snapshots = 15 models)."""
|
| 54 |
+
models = []
|
| 55 |
+
n_seeds = cfg["training"]["n_seeds"]
|
| 56 |
+
snapshot_epochs = cfg["training"]["n_snapshot_epochs"]
|
| 57 |
+
|
| 58 |
+
for seed_idx in range(n_seeds):
|
| 59 |
+
seed = seed_idx + 42 # seeds start at 42
|
| 60 |
+
fold_dir = ensemble_dir / f"fold_{fold_id}_seed{seed}"
|
| 61 |
+
|
| 62 |
+
for epoch in snapshot_epochs:
|
| 63 |
+
ckpt_path = fold_dir / f"phase3_{epoch}.pth"
|
| 64 |
+
if not ckpt_path.exists():
|
| 65 |
+
# Try best checkpoint instead
|
| 66 |
+
ckpt_path = fold_dir / "phase3_best.pth"
|
| 67 |
+
if not ckpt_path.exists():
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
model = ImmunogoldCenterNet(
|
| 71 |
+
bifpn_channels=cfg["model"]["bifpn_channels"],
|
| 72 |
+
bifpn_rounds=cfg["model"]["bifpn_rounds"],
|
| 73 |
+
num_classes=cfg["model"]["num_classes"],
|
| 74 |
+
)
|
| 75 |
+
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 76 |
+
model.load_state_dict(ckpt["model_state_dict"])
|
| 77 |
+
model.to(device)
|
| 78 |
+
model.eval()
|
| 79 |
+
models.append(model)
|
| 80 |
+
|
| 81 |
+
return models
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def main():
|
| 85 |
+
args = parse_args()
|
| 86 |
+
with open(args.config) as f:
|
| 87 |
+
cfg = yaml.safe_load(f)
|
| 88 |
+
|
| 89 |
+
device = torch.device(
|
| 90 |
+
"cuda" if args.device == "auto" and torch.cuda.is_available()
|
| 91 |
+
else args.device if args.device != "auto" else "cpu"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
records = discover_synapse_data(cfg["data"]["root"], cfg["data"]["synapse_ids"])
|
| 95 |
+
synapse_ids = cfg["data"]["synapse_ids"]
|
| 96 |
+
incomplete_6nm = set(cfg["data"].get("incomplete_6nm", []))
|
| 97 |
+
ensemble_dir = Path(args.ensemble_dir)
|
| 98 |
+
|
| 99 |
+
all_results = []
|
| 100 |
+
match_radii = {k: float(v) for k, v in cfg["evaluation"]["match_radii_px"].items()}
|
| 101 |
+
val_offset = cfg["evaluation"]["loocv_val_offset"]
|
| 102 |
+
|
| 103 |
+
# Support single-fold mode for SLURM array jobs
|
| 104 |
+
if args.fold:
|
| 105 |
+
eval_folds = [(synapse_ids.index(args.fold), args.fold)]
|
| 106 |
+
else:
|
| 107 |
+
eval_folds = list(enumerate(synapse_ids))
|
| 108 |
+
|
| 109 |
+
for test_idx, test_sid in eval_folds:
|
| 110 |
+
print(f"\n{'='*60}")
|
| 111 |
+
print(f"Fold {test_idx}: test={test_sid}")
|
| 112 |
+
|
| 113 |
+
# Val image for threshold tuning
|
| 114 |
+
val_idx = (test_idx + val_offset) % len(synapse_ids)
|
| 115 |
+
val_sid = synapse_ids[val_idx]
|
| 116 |
+
|
| 117 |
+
# Load test and val data
|
| 118 |
+
test_record = [r for r in records if r.synapse_id == test_sid][0]
|
| 119 |
+
val_record = [r for r in records if r.synapse_id == val_sid][0]
|
| 120 |
+
|
| 121 |
+
test_data = load_synapse(test_record)
|
| 122 |
+
val_data = load_synapse(val_record)
|
| 123 |
+
|
| 124 |
+
has_6nm = test_sid not in incomplete_6nm
|
| 125 |
+
|
| 126 |
+
# Load ensemble models
|
| 127 |
+
models = load_fold_models(ensemble_dir, test_sid, cfg, device)
|
| 128 |
+
if not models:
|
| 129 |
+
print(f" No models found for fold {test_sid}, skipping")
|
| 130 |
+
all_results.append({
|
| 131 |
+
"fold": test_sid,
|
| 132 |
+
"n_models": 0,
|
| 133 |
+
"6nm_f1": float("nan"),
|
| 134 |
+
"12nm_f1": float("nan"),
|
| 135 |
+
"mean_f1": float("nan"),
|
| 136 |
+
})
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
print(f" Loaded {len(models)} ensemble members")
|
| 140 |
+
|
| 141 |
+
# Tune threshold on validation image
|
| 142 |
+
val_hm, val_off = ensemble_predict(
|
| 143 |
+
models, val_data["image"], device, use_tta=args.use_tta,
|
| 144 |
+
)
|
| 145 |
+
val_hm_t = torch.from_numpy(val_hm)
|
| 146 |
+
val_off_t = torch.from_numpy(val_off)
|
| 147 |
+
|
| 148 |
+
# Get all detections at low threshold for sweep
|
| 149 |
+
val_dets = extract_peaks(
|
| 150 |
+
val_hm_t, val_off_t, stride=cfg["data"]["stride"],
|
| 151 |
+
conf_threshold=0.05,
|
| 152 |
+
nms_kernel_sizes=cfg["postprocessing"]["nms_kernel_size"],
|
| 153 |
+
)
|
| 154 |
+
best_thresholds = sweep_confidence_threshold(
|
| 155 |
+
val_dets, val_data["annotations"], match_radii,
|
| 156 |
+
)
|
| 157 |
+
print(f" Best thresholds: {best_thresholds}")
|
| 158 |
+
|
| 159 |
+
# Test inference
|
| 160 |
+
test_hm, test_off = ensemble_predict(
|
| 161 |
+
models, test_data["image"], device, use_tta=args.use_tta,
|
| 162 |
+
)
|
| 163 |
+
test_hm_t = torch.from_numpy(test_hm)
|
| 164 |
+
test_off_t = torch.from_numpy(test_off)
|
| 165 |
+
|
| 166 |
+
# Use per-class thresholds
|
| 167 |
+
all_detections = []
|
| 168 |
+
for cls in ["6nm", "12nm"]:
|
| 169 |
+
thr = best_thresholds.get(cls, 0.3)
|
| 170 |
+
cls_dets = extract_peaks(
|
| 171 |
+
test_hm_t, test_off_t,
|
| 172 |
+
stride=cfg["data"]["stride"],
|
| 173 |
+
conf_threshold=thr,
|
| 174 |
+
nms_kernel_sizes=cfg["postprocessing"]["nms_kernel_size"],
|
| 175 |
+
)
|
| 176 |
+
all_detections.extend([d for d in cls_dets if d["class"] == cls])
|
| 177 |
+
|
| 178 |
+
# Post-processing
|
| 179 |
+
if test_data["mask"] is not None:
|
| 180 |
+
all_detections = apply_structural_mask_filter(
|
| 181 |
+
all_detections, test_data["mask"],
|
| 182 |
+
margin_px=cfg["postprocessing"]["mask_filter_margin_px"],
|
| 183 |
+
)
|
| 184 |
+
all_detections = cross_class_nms(
|
| 185 |
+
all_detections, cfg["postprocessing"]["cross_class_nms_distance_px"],
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# Evaluate
|
| 189 |
+
results = match_detections_to_gt(
|
| 190 |
+
all_detections,
|
| 191 |
+
test_data["annotations"].get("6nm", np.empty((0, 2))),
|
| 192 |
+
test_data["annotations"].get("12nm", np.empty((0, 2))),
|
| 193 |
+
match_radii,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
fold_result = {
|
| 197 |
+
"fold": test_sid,
|
| 198 |
+
"n_models": len(models),
|
| 199 |
+
"6nm_f1": results["6nm"]["f1"] if has_6nm else float("nan"),
|
| 200 |
+
"6nm_precision": results["6nm"]["precision"] if has_6nm else float("nan"),
|
| 201 |
+
"6nm_recall": results["6nm"]["recall"] if has_6nm else float("nan"),
|
| 202 |
+
"12nm_f1": results["12nm"]["f1"],
|
| 203 |
+
"12nm_precision": results["12nm"]["precision"],
|
| 204 |
+
"12nm_recall": results["12nm"]["recall"],
|
| 205 |
+
"mean_f1": results["mean_f1"],
|
| 206 |
+
}
|
| 207 |
+
all_results.append(fold_result)
|
| 208 |
+
|
| 209 |
+
for cls in ["6nm", "12nm"]:
|
| 210 |
+
r = results[cls]
|
| 211 |
+
note = " (N/A)" if cls == "6nm" and not has_6nm else ""
|
| 212 |
+
print(f" {cls}: F1={r['f1']:.3f}, P={r['precision']:.3f}, "
|
| 213 |
+
f"R={r['recall']:.3f}{note}")
|
| 214 |
+
print(f" Mean F1: {results['mean_f1']:.3f}")
|
| 215 |
+
|
| 216 |
+
# Save per-fold visualization
|
| 217 |
+
overlay_annotations(
|
| 218 |
+
test_data["image"], test_data["annotations"],
|
| 219 |
+
title=f"Fold {test_sid} — F1={results['mean_f1']:.3f}",
|
| 220 |
+
save_path=Path("results/per_fold_predictions") / f"{test_sid}.png",
|
| 221 |
+
predictions=all_detections,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
# Summary
|
| 225 |
+
df = pd.DataFrame(all_results)
|
| 226 |
+
output_path = Path(args.output)
|
| 227 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 228 |
+
df.to_csv(output_path, index=False)
|
| 229 |
+
|
| 230 |
+
print(f"\n{'='*60}")
|
| 231 |
+
print("LOOCV Results:")
|
| 232 |
+
f1_6nm = df["6nm_f1"].dropna()
|
| 233 |
+
f1_12nm = df["12nm_f1"].dropna()
|
| 234 |
+
mean_f1 = df["mean_f1"].dropna()
|
| 235 |
+
|
| 236 |
+
print(f" 6nm F1: {f1_6nm.mean():.3f} ± {f1_6nm.std():.3f} (n={len(f1_6nm)})")
|
| 237 |
+
print(f" 12nm F1: {f1_12nm.mean():.3f} ± {f1_12nm.std():.3f} (n={len(f1_12nm)})")
|
| 238 |
+
print(f" Mean F1: {mean_f1.mean():.3f} ± {mean_f1.std():.3f}")
|
| 239 |
+
print(f"\nResults saved to {output_path}")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
main()
|