| """SIFQ Evaluation Runner β SOTA verification across 4 Tracks. |
| |
| Requires: |
| - scores_sifq.jsonl : output of run_infer.py (SIFQ Q scores) |
| - MDGT checkpoint : for computing genuine/impostor match scores (Track 1) |
| - scipy, matplotlib : for plots and KS tests |
| |
| Outputs (saved to --out-dir): |
| - results_track1_erc.json : AUC_ERC table (SIFQ vs random baseline) |
| - results_track2_sensor.json : KS statistics per sensor pair |
| - results_track4_concepts.json: Spearman rho crosstalk matrix |
| - plot_erc.png : ERC curve |
| - plot_sensor_hist.png : Q distribution per sensor |
| - plot_crosstalk.png : concept grounding heatmap |
| |
| NFIQ2 baseline: pass --nfiq2-scores path/to/nfiq2.jsonl (same format as SIFQ |
| scores but generated externally via `nfiq2 --path ...`). |
| |
| Usage: |
| python scripts/run_eval.py \\ |
| --sifq-scores /tmp/sifq_scores.jsonl \\ |
| --mdgt-checkpoint pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt \\ |
| --out-dir eval_results/ |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| from collections import defaultdict |
| from pathlib import Path |
| from itertools import combinations |
|
|
| import numpy as np |
| import torch |
| import torch.nn.functional as F |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
|
|
| ROOT = Path(__file__).resolve().parents[1] |
| SRC_ROOT = ROOT / "src" |
| if str(SRC_ROOT) not in sys.path: |
| sys.path.insert(0, str(SRC_ROOT)) |
|
|
| from evaluation.erc import compute_erc |
| from evaluation.sensor_invariance import sensor_ks_test, cross_sensor_correlation |
| from training.mdgt_teacher import MDGTCheckpointTeacher |
|
|
|
|
| |
| |
| |
|
|
| def load_scores(jsonl_path: str) -> list[dict]: |
| rows = [] |
| with open(jsonl_path, encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if line: |
| rows.append(json.loads(line)) |
| return rows |
|
|
|
|
| def build_match_scores( |
| rows: list[dict], |
| mdgt: MDGTCheckpointTeacher, |
| device: torch.device, |
| image_size: int = 224, |
| max_pairs: int = 5000, |
| ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: |
| """Compute genuine and impostor match scores via MDGT cosine similarity. |
| |
| Returns: |
| quality_scores : [N] SIFQ Q scores for each pair member (mean of pair) |
| match_scores : [N] MDGT cosine similarity |
| labels : [N] 1=genuine, 0=impostor |
| """ |
| from PIL import Image |
| from torchvision import transforms |
|
|
| tf = transforms.Compose([ |
| transforms.Resize((image_size, image_size)), |
| transforms.ToTensor(), |
| ]) |
|
|
| |
| print(" Computing MDGT embeddings for match scores...") |
| paths = [r["image_path"] for r in rows] |
| emb_list: list[torch.Tensor] = [] |
| batch_paths: list[str] = [] |
| batch_size = 16 |
|
|
| def flush_emb(bpaths: list[str]) -> None: |
| imgs = [] |
| for p in bpaths: |
| img = Image.open(p).convert("L") |
| imgs.append(tf(img)) |
| batch = torch.stack(imgs, dim=0).to(device) |
| with torch.no_grad(): |
| embs = mdgt(batch) |
| emb_list.extend(embs.cpu()) |
|
|
| for row in rows: |
| batch_paths.append(row["image_path"]) |
| if len(batch_paths) >= batch_size: |
| flush_emb(batch_paths) |
| batch_paths.clear() |
| if batch_paths: |
| flush_emb(batch_paths) |
|
|
| embs = torch.stack(emb_list, dim=0) |
|
|
| |
| |
| by_subject: dict[str, list[int]] = defaultdict(list) |
| by_finger_sensor: dict[tuple[str, str], list[int]] = defaultdict(list) |
| for i, r in enumerate(rows): |
| key_fs = (r["identity_id"], r["finger_id"]) |
| by_subject[r["identity_id"]].append(i) |
| by_finger_sensor[key_fs].append(i) |
|
|
| rng = np.random.default_rng(42) |
| genuine_pairs: list[tuple[int, int]] = [] |
| for (_, _), idxs in by_finger_sensor.items(): |
| for a, b in combinations(idxs, 2): |
| if rows[a]["sensor_id"] != rows[b]["sensor_id"]: |
| genuine_pairs.append((a, b)) |
|
|
| subjects = sorted(by_subject.keys()) |
| impostor_pairs: list[tuple[int, int]] = [] |
| while len(impostor_pairs) < len(genuine_pairs) * 3: |
| s1, s2 = rng.choice(len(subjects), size=2, replace=False) |
| i1 = int(rng.choice(by_subject[subjects[s1]])) |
| i2 = int(rng.choice(by_subject[subjects[s2]])) |
| impostor_pairs.append((i1, i2)) |
|
|
| all_pairs = ( |
| [(a, b, 1) for a, b in genuine_pairs] + |
| [(a, b, 0) for a, b in impostor_pairs] |
| ) |
| rng.shuffle(all_pairs) |
| if max_pairs > 0 and len(all_pairs) > max_pairs: |
| all_pairs = all_pairs[:max_pairs] |
|
|
| q_all, ms_all, lb_all = [], [], [] |
| q_arr = np.array([r["q_score"] for r in rows]) |
| for a, b, label in all_pairs: |
| cos = float(F.cosine_similarity(embs[a].unsqueeze(0), embs[b].unsqueeze(0)).item()) |
| q_all.append((q_arr[a] + q_arr[b]) / 2.0) |
| ms_all.append(cos) |
| lb_all.append(label) |
|
|
| print(f" Pairs: {len(genuine_pairs)} genuine, {len(impostor_pairs)} impostor " |
| f"(using {len(all_pairs)} total)") |
| return np.array(q_all), np.array(ms_all), np.array(lb_all) |
|
|
|
|
| |
| |
| |
|
|
| def run_track1( |
| rows: list[dict], |
| mdgt: MDGTCheckpointTeacher, |
| device: torch.device, |
| out_dir: Path, |
| nfiq2_rows: list[dict] | None = None, |
| image_size: int = 224, |
| ) -> dict: |
| print("[Track 1] Computing ERC...") |
| q_sifq, ms, labels = build_match_scores(rows, mdgt, device, image_size=image_size) |
|
|
| rejection_ratios = np.linspace(0.0, 0.5, 50) |
| fnmr_sifq, auc_sifq = compute_erc(q_sifq, ms, labels, rejection_ratios=rejection_ratios) |
|
|
| |
| rng = np.random.default_rng(0) |
| q_rand = rng.uniform(0, 100, size=len(q_sifq)) |
| fnmr_rand, auc_rand = compute_erc(q_rand, ms, labels, rejection_ratios=rejection_ratios) |
|
|
| results = { |
| "SIFQ": {"auc_erc": round(auc_sifq, 4)}, |
| "Random": {"auc_erc": round(auc_rand, 4)}, |
| } |
|
|
| |
| if nfiq2_rows: |
| nfiq2_map = {r["image_path"]: r["q_score"] for r in nfiq2_rows} |
| q_nfiq2 = np.array([nfiq2_map.get(r["image_path"], 50.0) for r in rows]) |
| |
| q_nfiq2_pairs = (q_nfiq2[[a for a, _, _ in [(0,0,0)]]] + q_nfiq2) / 2 |
| fnmr_nfiq2, auc_nfiq2 = compute_erc(q_nfiq2, ms, labels, rejection_ratios=rejection_ratios) |
| results["NFIQ2"] = {"auc_erc": round(auc_nfiq2, 4)} |
|
|
| |
| fig, ax = plt.subplots(figsize=(7, 5)) |
| ax.plot(rejection_ratios, fnmr_sifq, label=f"SIFQ (AUC={auc_sifq:.4f})", linewidth=2, color="steelblue") |
| ax.plot(rejection_ratios, fnmr_rand, label=f"Random (AUC={auc_rand:.4f})", linewidth=1.5, |
| linestyle="--", color="gray") |
| if nfiq2_rows: |
| ax.plot(rejection_ratios, fnmr_nfiq2, label=f"NFIQ2 (AUC={auc_nfiq2:.4f})", |
| linewidth=1.5, linestyle=":", color="orangered") |
| ax.set_xlabel("Rejection ratio") |
| ax.set_ylabel("FNMR @ FMR=1e-4") |
| ax.set_title("Error Rejection Curve β lower AUC is better") |
| ax.legend() |
| ax.grid(True, alpha=0.3) |
| fig.tight_layout() |
| fig.savefig(out_dir / "plot_erc.png", dpi=150) |
| plt.close(fig) |
| print(f" ERC plot saved. AUC_ERC: {results}") |
| return results |
|
|
|
|
| |
| |
| |
|
|
| def run_track2(rows: list[dict], out_dir: Path, nfiq2_rows: list[dict] | None = None) -> dict: |
| print("[Track 2] Computing sensor invariance...") |
|
|
| scores_by_sensor: dict[str, np.ndarray] = {} |
| tmp: dict[str, list[float]] = defaultdict(list) |
| for r in rows: |
| tmp[r["sensor_id"]].append(r["q_score"]) |
| for sid, vals in tmp.items(): |
| scores_by_sensor[sid] = np.array(vals) |
|
|
| ks_rows = sensor_ks_test(scores_by_sensor) |
| mean_ks = float(np.mean([row["ks_stat"] for row in ks_rows])) if ks_rows else 0.0 |
|
|
| |
| by_finger: dict[tuple[str, str], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) |
| for r in rows: |
| key = (r["identity_id"], r["finger_id"]) |
| by_finger[key][r["sensor_id"]].append(r["q_score"]) |
|
|
| paired_scores: list[tuple[float, float]] = [] |
| for key, by_s in by_finger.items(): |
| sensors = sorted(by_s.keys()) |
| for s1, s2 in combinations(sensors, 2): |
| for q1, q2 in zip(by_s[s1], by_s[s2]): |
| paired_scores.append((q1, q2)) |
|
|
| pearson_sifq = cross_sensor_correlation(paired_scores) |
|
|
| results = { |
| "SIFQ": { |
| "mean_ks_across_sensors": round(mean_ks, 4), |
| "cross_sensor_pearson": round(pearson_sifq, 4), |
| "n_sensor_pairs": len(ks_rows), |
| "per_pair_ks": ks_rows, |
| } |
| } |
|
|
| if nfiq2_rows: |
| n_tmp: dict[str, list[float]] = defaultdict(list) |
| nfiq2_by_path = {r["image_path"]: r for r in nfiq2_rows} |
| for r in rows: |
| if r["image_path"] in nfiq2_by_path: |
| n_tmp[r["sensor_id"]].append(nfiq2_by_path[r["image_path"]]["q_score"]) |
| nfiq2_by_sensor = {sid: np.array(vals) for sid, vals in n_tmp.items()} |
| nfiq2_ks = sensor_ks_test(nfiq2_by_sensor) |
| nfiq2_mean_ks = float(np.mean([row["ks_stat"] for row in nfiq2_ks])) if nfiq2_ks else 0.0 |
| results["NFIQ2"] = {"mean_ks_across_sensors": round(nfiq2_mean_ks, 4)} |
|
|
| |
| n_sensors = len(scores_by_sensor) |
| fig, ax = plt.subplots(figsize=(8, 5)) |
| colors = plt.cm.tab10(np.linspace(0, 1, min(n_sensors, 10))) |
| for (sid, vals), color in zip(sorted(scores_by_sensor.items()), colors): |
| ax.hist(vals, bins=40, alpha=0.5, label=sid[:30], color=color, density=True) |
| ax.set_xlabel("SIFQ Quality Score") |
| ax.set_ylabel("Density") |
| ax.set_title(f"Quality score distribution per sensor\n(mean KS={mean_ks:.4f}, Pearson={pearson_sifq:.4f})\nLow KS = sensor-invariant") |
| ax.legend(fontsize=7, loc="upper left") |
| ax.grid(True, alpha=0.3) |
| fig.tight_layout() |
| fig.savefig(out_dir / "plot_sensor_hist.png", dpi=150) |
| plt.close(fig) |
|
|
| |
| if paired_scores: |
| arr = np.array(paired_scores[:2000]) |
| fig2, ax2 = plt.subplots(figsize=(5, 5)) |
| ax2.scatter(arr[:, 0], arr[:, 1], alpha=0.3, s=10, color="steelblue") |
| ax2.set_xlabel("Q β sensor 1") |
| ax2.set_ylabel("Q β sensor 2") |
| ax2.set_title(f"Cross-sensor quality consistency\nPearson r={pearson_sifq:.3f}") |
| mn, mx = arr.min(), arr.max() |
| ax2.plot([mn, mx], [mn, mx], "r--", alpha=0.5, label="ideal") |
| ax2.legend() |
| ax2.grid(True, alpha=0.3) |
| fig2.tight_layout() |
| fig2.savefig(out_dir / "plot_sensor_scatter.png", dpi=150) |
| plt.close(fig2) |
|
|
| print(f" Sensor invariance done. Mean KS={mean_ks:.4f}, Pearson={pearson_sifq:.4f}") |
| return results |
|
|
|
|
| |
| |
| |
|
|
| def run_track4( |
| checkpoint_path: str, |
| device: torch.device, |
| test_image_paths: list[str], |
| out_dir: Path, |
| image_size: int = 224, |
| max_images: int = 100, |
| ) -> list[dict]: |
| from evaluation.concept_grounding import compute_crosstalk_matrix |
| from data.degradation import DegradationPipeline |
| from models.aggregator import ScoreAggregator |
| from models.backbone import SIFQBackbone |
| from models.concept_head import ConceptHead, SpatialConceptHead |
| from models.sensor_discriminator import SensorDiscriminator |
| from models.sifq import SIFQ |
| import cv2 |
|
|
| print("[Track 4] Computing concept grounding (crosstalk matrix)...") |
| ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False) |
| num_sensors = ckpt.get("metrics", {}).get("n_sensors", 10) |
| backbone = SIFQBackbone(model_name="tiny_vit_5m_224.dist_in22k", pretrained=False) |
| _use_spatial = ckpt.get("config", {}).get("spatial_concept_head", False) |
| if _use_spatial: |
| concept_head = SpatialConceptHead(in_dim=backbone.feature_dim) |
| else: |
| concept_head = ConceptHead(in_dim=backbone.feature_dim) |
| aggregator = ScoreAggregator(k=6) |
| sensor_disc = SensorDiscriminator(in_dim=backbone.feature_dim, num_sensors=num_sensors) |
| model = SIFQ(backbone, concept_head, aggregator, sensor_disc) |
| model.load_state_dict(ckpt["model"], strict=True) |
| model.to(device).eval() |
|
|
| deg_pipeline = DegradationPipeline() |
| test_images_np = [] |
| for p in test_image_paths[:max_images]: |
| img = cv2.imread(p, cv2.IMREAD_GRAYSCALE) |
| if img is not None: |
| img = cv2.resize(img, (image_size, image_size)) |
| test_images_np.append(img) |
|
|
| if not test_images_np: |
| print(" No test images loaded for concept grounding β skipping Track 4") |
| return [] |
|
|
| rows = compute_crosstalk_matrix(model, deg_pipeline, test_images_np, device=str(device)) |
|
|
| |
| try: |
| concept_names = concept_head.CONCEPT_NAMES |
| deg_names = [r["degradation"] for r in rows] |
| matrix = np.array([[r[c] for c in concept_names] for r in rows]) |
|
|
| fig, ax = plt.subplots(figsize=(10, 6)) |
| im = ax.imshow(matrix, vmin=-1, vmax=1, cmap="RdYlGn", aspect="auto") |
| ax.set_xticks(range(len(concept_names))) |
| ax.set_xticklabels(concept_names, rotation=30, ha="right", fontsize=9) |
| ax.set_yticks(range(len(deg_names))) |
| ax.set_yticklabels(deg_names, fontsize=9) |
| for i in range(len(deg_names)): |
| for j in range(len(concept_names)): |
| ax.text(j, i, f"{matrix[i, j]:.2f}", ha="center", va="center", fontsize=7) |
| plt.colorbar(im, ax=ax, label="Spearman Ο") |
| ax.set_title("Concept grounding (crosstalk matrix)\nDiagonal-heavy = well-grounded concepts") |
| fig.tight_layout() |
| fig.savefig(out_dir / "plot_crosstalk.png", dpi=150) |
| plt.close(fig) |
| print(f" Crosstalk matrix saved.") |
| except Exception as e: |
| print(f" Warning: could not plot crosstalk: {e}") |
|
|
| return rows |
|
|
|
|
| |
| |
| |
|
|
| def parse_args() -> argparse.Namespace: |
| p = argparse.ArgumentParser(description="SIFQ evaluation β SOTA verification") |
| p.add_argument("--sifq-scores", type=str, required=True, |
| help="JSONL output from run_infer.py") |
| p.add_argument("--checkpoint", type=str, required=True, |
| help="SIFQ checkpoint (for Track 4 concept grounding)") |
| p.add_argument("--mdgt-checkpoint", type=str, |
| default="/home/aiserver/works/fingerprint/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt", |
| help="MDGT checkpoint for computing match scores") |
| p.add_argument("--nfiq2-scores", type=str, default="", |
| help="Optional JSONL with NFIQ2 scores (same format as --sifq-scores)") |
| p.add_argument("--out-dir", type=str, default="eval_results", |
| help="Directory to save plots and result JSONs") |
| p.add_argument("--image-size", type=int, default=224) |
| p.add_argument("--max-pairs", type=int, default=5000, |
| help="Max genuine+impostor pairs for ERC computation") |
| p.add_argument("--max-concept-images", type=int, default=50, |
| help="Max images for concept grounding (Track 4)") |
| p.add_argument("--skip-track1", action="store_true", |
| help="Skip ERC (Track 1) β needs MDGT inference which is slow") |
| p.add_argument("--skip-track4", action="store_true", |
| help="Skip concept grounding (Track 4)") |
| p.add_argument("--exclude-sensor", type=str, default="", |
| help="Comma-separated sensor_ids to exclude before evaluation. " |
| "E.g. 'R_1000_slap,R_500_slap,S_500_slap'") |
| return p.parse_args() |
|
|
|
|
| |
| |
| |
|
|
| _CONCEPT_KEYS = [ |
| ("orientation_coherence", "orient_coh"), |
| ("ridge_valley_clarity", "clarity "), |
| ("continuity", "continuity"), |
| ("noise_level", "noise_lvl "), |
| ("contrast_uniformity", "contrast "), |
| ("minutiae_reliability", "minutiae "), |
| ] |
|
|
| |
| |
| |
| _DEG_TARGETS = { |
| "blur": {1, 2}, |
| "noise": {1, 3}, |
| "jpeg": {1}, |
| "occlusion": {5}, |
| "dry_skin": {4, 0}, |
| "wet_press": {1, 5, 0}, |
| } |
|
|
|
|
| def _save_summary_txt(all_results: dict, out_path: Path) -> None: |
| from datetime import datetime |
| W = 72 |
| lines = [] |
|
|
| def sep(ch="="): |
| lines.append(ch * W) |
|
|
| sep() |
| lines.append(f"{'SIFQ EVALUATION SUMMARY':^{W}}") |
| sep() |
| lines.append(f"Generated : {datetime.now().strftime('%Y-%m-%d %H:%M')}") |
| lines.append("") |
|
|
| |
| if "track1_erc" in all_results: |
| lines.append("TRACK 1 β ERROR REJECTION CURVE (AUC β better)") |
| sep("-") |
| for method, v in all_results["track1_erc"].items(): |
| lines.append(f" {method:<10s} AUC_ERC = {v['auc_erc']:.4f}") |
| lines.append("") |
|
|
| |
| if "track2_sensor_invariance" in all_results: |
| lines.append("TRACK 2 β SENSOR INVARIANCE") |
| sep("-") |
| for method, v in all_results["track2_sensor_invariance"].items(): |
| if not isinstance(v, dict) or "mean_ks_across_sensors" not in v: |
| continue |
| ks = v["mean_ks_across_sensors"] |
| pr = v.get("cross_sensor_pearson", float("nan")) |
| n = v.get("n_sensor_pairs", "?") |
| ks_flag = "β" if ks <= 0.15 else "β" |
| pr_flag = "β" if pr >= 0.75 else "β" |
| lines.append(f" Method : {method}") |
| lines.append(f" Mean KS (β better) : {ks:.4f} {ks_flag} [target β€ 0.15]") |
| lines.append(f" Pearson (β better) : {pr:.4f} {pr_flag} [target β₯ 0.75]") |
| lines.append(f" Pairs : {n}") |
|
|
| pairs = v.get("per_pair_ks", []) |
| if pairs: |
| lines.append("") |
| lines.append(f" All {len(pairs)} sensor pairs sorted by KS β:") |
| lines.append(f" {'Sensor A':<24s} {'Sensor B':<24s} {'KS':>7s}") |
| lines.append(f" {'-'*24} {'-'*24} {'-'*7}") |
| for p in sorted(pairs, key=lambda x: x["ks_stat"], reverse=True): |
| lines.append( |
| f" {p['sensor_a']:<24s} {p['sensor_b']:<24s} {p['ks_stat']:>7.4f}" |
| ) |
| lines.append("") |
|
|
| |
| if "track4_concept_grounding" in all_results: |
| lines.append("TRACK 4 β CONCEPT GROUNDING") |
| lines.append(" Spearman Ο: negative = concept β with degradation = correct (*= target)") |
| sep("-") |
| |
| col_w = 9 |
| hdr_keys = [short for _, short in _CONCEPT_KEYS] |
| lines.append( |
| f" {'Degradation':<12s} " + " ".join(f"{h:>{col_w}s}" for h in hdr_keys) |
| ) |
| lines.append( |
| f" {'-'*12} " + " ".join("-" * col_w for _ in _CONCEPT_KEYS) |
| ) |
| for row in all_results["track4_concept_grounding"]: |
| deg = row.get("degradation", "?") |
| targets = _DEG_TARGETS.get(deg, set()) |
| cells = [] |
| for ci, (json_key, _) in enumerate(_CONCEPT_KEYS): |
| val = row.get(json_key, float("nan")) |
| tag = "*" if ci in targets else " " |
| cells.append(f"{val:>+7.3f}{tag} ") |
| lines.append(f" {deg:<12s} " + " ".join(cells)) |
| lines.append("") |
|
|
| sep() |
| txt = "\n".join(lines) |
| with open(out_path, "w", encoding="utf-8") as f: |
| f.write(txt) |
| print(f"[eval] Summary table: {out_path}") |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| out_dir = Path(args.out_dir) |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| rows = load_scores(args.sifq_scores) |
| print(f"Loaded {len(rows)} SIFQ score records from {args.sifq_scores}") |
| if args.exclude_sensor: |
| excluded = {s.strip() for s in args.exclude_sensor.split(",") if s.strip()} |
| rows = [r for r in rows if r["sensor_id"] not in excluded] |
| print(f"After excluding sensors {excluded}: {len(rows)} records remain") |
|
|
| nfiq2_rows = load_scores(args.nfiq2_scores) if args.nfiq2_scores else None |
|
|
| all_results: dict = {} |
|
|
| |
| t2 = run_track2(rows, out_dir, nfiq2_rows=nfiq2_rows) |
| all_results["track2_sensor_invariance"] = t2 |
|
|
| |
| if not args.skip_track1: |
| print(f"Loading MDGT teacher from {args.mdgt_checkpoint}") |
| mdgt = MDGTCheckpointTeacher( |
| checkpoint_path=args.mdgt_checkpoint, |
| model_name="vit_small_patch14_dinov2.lvd142m", |
| image_size=args.image_size, |
| device=str(device), |
| ).to(device) |
| t1 = run_track1(rows, mdgt, device, out_dir, nfiq2_rows=nfiq2_rows, |
| image_size=args.image_size) |
| all_results["track1_erc"] = t1 |
| else: |
| print("[Track 1] Skipped (--skip-track1)") |
|
|
| |
| if not args.skip_track4: |
| test_paths = [r["image_path"] for r in rows] |
| t4 = run_track4(args.checkpoint, device, test_paths, out_dir, |
| image_size=args.image_size, max_images=args.max_concept_images) |
| all_results["track4_concept_grounding"] = t4 |
| else: |
| print("[Track 4] Skipped (--skip-track4)") |
|
|
| |
| summary_path = out_dir / "eval_summary.txt" |
| _save_summary_txt(all_results, summary_path) |
|
|
| print(f"\n{'='*60}") |
| print("EVALUATION SUMMARY") |
| print(f"{'='*60}") |
| if "track1_erc" in all_results: |
| print("\nTrack 1 β Error Rejection Curve (AUC, lower=better):") |
| for method, v in all_results["track1_erc"].items(): |
| print(f" {method:10s}: AUC_ERC = {v['auc_erc']:.4f}") |
| if "track2_sensor_invariance" in all_results: |
| print("\nTrack 2 β Sensor Invariance:") |
| for method, v in all_results["track2_sensor_invariance"].items(): |
| if isinstance(v, dict) and "mean_ks_across_sensors" in v: |
| print(f" {method:10s}: Mean KS = {v['mean_ks_across_sensors']:.4f} " |
| f"Pearson = {v.get('cross_sensor_pearson', 'N/A')}") |
| print(f"\nPlots and TXT saved to: {out_dir}") |
| print(f"Full summary: {summary_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|