File size: 2,162 Bytes
142281f | 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 | """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))
|