Download threshold_study.py from salimamri9/patchcore-mvtec-cpu: direct link, hf CLI and curl.
- Browser
- Download file 2.16 kB
-
https://huggingface.co/salimamri9/patchcore-mvtec-cpu/resolve/main/threshold_study.py
- Command line
-
hf download hf://salimamri9/patchcore-mvtec-cpu/threshold_study.py
-
curl -L -o threshold_study.py https://huggingface.co/salimamri9/patchcore-mvtec-cpu/resolve/main/threshold_study.py
2.16 kB
| """Compare threshold rules that only use NORMAL calibration scores. | |
| max : max(calib) (v1, zero false alarm on calibration) | |
| mean+3sd : mean + 3 * std | |
| robust : median + 4 * 1.4826 * MAD (robust z-score, insensitive to one outlier) | |
| p95 : 95th percentile of calib scores | |
| oracle : F1-optimal threshold chosen on the test set (upper bound, not deployable) | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| from patchcore.metrics import f1_at | |
| RULES = { | |
| "max": lambda c: c.max(), | |
| "mean+3sd": lambda c: c.mean() + 3 * c.std(), | |
| "robust": lambda c: np.median(c) + 4 * 1.4826 * np.median(np.abs(c - np.median(c))), | |
| "p95": lambda c: np.quantile(c, 0.95), | |
| } | |
| def study(tag): | |
| d = Path("results") / tag | |
| metrics = json.loads((d / "metrics.json").read_text()) | |
| rows = {} | |
| for cat in metrics: | |
| s = json.loads((d / f"{cat}_scores.json").read_text()) | |
| sc, lab, cal = np.array(s["scores"]), np.array(s["labels"]), np.array(s["calib_scores"]) | |
| r = {} | |
| for name, fn in RULES.items(): | |
| t = fn(cal) | |
| pred = sc >= t | |
| r[name] = {"thr": float(t), "f1": float(f1_at(lab, sc, t)), | |
| "recall": float(pred[lab == 1].mean()), "fpr": float(pred[lab == 0].mean())} | |
| r["oracle"] = {"thr": metrics[cat]["oracle_threshold"], "f1": metrics[cat]["image_f1_max"]} | |
| rows[cat] = r | |
| return rows | |
| if __name__ == "__main__": | |
| tag = sys.argv[1] if len(sys.argv) > 1 else "wrn50_c1" | |
| rows = study(tag) | |
| names = list(RULES) + ["oracle"] | |
| print(f"{'F1':12s}" + "".join(f"{n:>10s}" for n in names)) | |
| for cat, r in rows.items(): | |
| print(f"{cat:12s}" + "".join(f"{r[n]['f1']:10.3f}" for n in names)) | |
| print(f"{'MEAN':12s}" + "".join(f"{np.mean([r[n]['f1'] for r in rows.values()]):10.3f}" for n in names)) | |
| for k in ("recall", "fpr"): | |
| print(f"{'mean ' + k:12s}" + "".join(f"{np.mean([r[n][k] for r in rows.values()]):10.3f}" for n in RULES)) | |
| Path("results", tag, "threshold_study.json").write_text(json.dumps(rows, indent=2)) | |