File size: 1,377 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
"""One-off: apply the v2 threshold rule (p95 of calibration scores) to an existing run
without recomputing features (results are identical to re-running run.py)."""
import json, sys
from pathlib import Path
import numpy as np
from patchcore.metrics import f1_at

tag = sys.argv[1] if len(sys.argv) > 1 else "wrn50_c1"
d = Path("results") / tag
M = json.loads((d / "metrics.json").read_text())
for cat, r in M.items():
    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"])
    if r.get("threshold_rule") == "p95_calibration":
        continue
    t = float(np.quantile(cal, 0.95))
    pred = sc >= t
    r["image_f1_maxrule"] = r["image_f1_calibrated"]
    r.update(image_threshold=t, threshold_rule="p95_calibration",
             image_f1_calibrated=float(f1_at(lab, sc, t)),
             recall_calibrated=float(pred[lab == 1].mean()), fpr_calibrated=float(pred[lab == 0].mean()))
    cfgp = Path("models") / cat / "config.json"
    if tag == "wrn50_c1" and cfgp.exists():
        cfg = json.loads(cfgp.read_text())
        cfg["image_threshold"] = t
        cfg["metrics"] = r
        cfgp.write_text(json.dumps(cfg, indent=2))
(d / "metrics.json").write_text(json.dumps(M, indent=2))
print(tag, "mean F1 calibrated:", np.mean([r["image_f1_calibrated"] for r in M.values()]))