File size: 4,979 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""Fit + calibrate + evaluate PatchCore on MVTec AD categories.

Example:
    python run.py --backbone wide_resnet50_2 --coreset 0.01 --tag wrn50_c1
"""
from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

import numpy as np
import torch
from torch.utils.data import DataLoader

from patchcore.data import CATEGORIES, MVTecItems, list_category
from patchcore.metrics import compute_all, f1_at
from patchcore.model import PatchCore


def run_predict(model, loader):
    scores, maps, masks, labels, paths, defects = [], [], [], [], [], []
    t0 = time.time()
    for b in loader:
        s, m = model.predict(b["image"])
        scores.append(s)
        maps.append(m)
        masks.append(b["mask"][:, 0])
        labels += list(b["label"].numpy())
        paths += b["path"]
        defects += b["defect"]
    dt = time.time() - t0
    return (torch.cat(scores).numpy(), torch.cat(maps).numpy(), torch.cat(masks).numpy() > 0.5,
            np.array(labels), paths, defects, dt)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", default="data/mvtec_ad")
    ap.add_argument("--categories", nargs="*", default=CATEGORIES)
    ap.add_argument("--backbone", default="wide_resnet50_2")
    ap.add_argument("--coreset", type=float, default=0.01)
    ap.add_argument("--tag", default=None)
    ap.add_argument("--batch", type=int, default=16)
    ap.add_argument("--workers", type=int, default=4)
    ap.add_argument("--threads", type=int, default=12)
    ap.add_argument("--save-models", action="store_true")
    ap.add_argument("--no-crop", action="store_true",
                    help="resize full image to 224 instead of resize 256 + center-crop 224")
    args = ap.parse_args()
    torch.set_num_threads(args.threads)
    tag = args.tag or f"{args.backbone}_c{args.coreset}"
    out = Path("results") / tag
    out.mkdir(parents=True, exist_ok=True)
    summary_path = out / "metrics.json"
    summary = json.loads(summary_path.read_text()) if summary_path.exists() else {}

    for cat in args.categories:
        print(f"=== {cat} [{tag}]", flush=True)
        train, calib, test = list_category(args.data, cat)
        size_kw = {"resize": 224, "crop": None} if args.no_crop else {}
        mk = lambda items: DataLoader(MVTecItems(items, **size_kw), batch_size=args.batch,
                                      num_workers=args.workers, shuffle=False)
        model = PatchCore(args.backbone, coreset_ratio=args.coreset)
        fit_info = model.fit(mk(train))

        # --- thresholds from held-out NORMAL images only (no anomaly seen)
        c_scores, c_maps, *_ = run_predict(model, mk(calib))
        # v1 rule (max) kept for reference; v2 rule = 95th percentile, robust to a
        # mislabelled "good" image (see docs/difficulties.md, threshold_study.py)
        thr_max = float(c_scores.max())
        model.image_threshold = float(np.quantile(c_scores, 0.95))
        model.pixel_threshold = float(c_maps.max())

        scores, maps, masks, labels, paths, defects, dt = run_predict(model, mk(test))
        res = compute_all(labels, scores, masks, maps, model.image_threshold)
        res["image_f1_maxrule"] = float(f1_at(labels, scores, thr_max))
        res["threshold_rule"] = "p95_calibration"
        res.update(fit_info)
        res.update({
            "n_train": len(train), "n_calib": len(calib), "n_test": len(test),
            "n_anomalous": int(labels.sum()),
            "ms_per_image": 1000 * dt / len(test),
            "image_threshold": model.image_threshold, "pixel_threshold": model.pixel_threshold,
        })
        print("  " + "  ".join(f"{k}={v:.4f}" for k, v in res.items()
                               if k in ("image_auroc", "pixel_auroc", "au_pro", "image_f1_calibrated",
                                        "image_f1_max", "ms_per_image")), flush=True)
        summary[cat] = res
        (out / f"{cat}_scores.json").write_text(json.dumps({
            "paths": paths, "labels": labels.tolist(), "defects": defects,
            "scores": scores.tolist(), "calib_scores": c_scores.tolist(),
        }))
        if args.save_models:
            model.save(Path("models") / cat, extra={"category": cat, "metrics": res,
                                                    "resize": 224 if args.no_crop else 256,
                                                    "crop": None if args.no_crop else 224})
        summary_path.write_text(json.dumps(summary, indent=2))

    keys = ["image_auroc", "pixel_auroc", "au_pro", "image_f1_calibrated", "image_f1_max", "ms_per_image"]
    print(f"\n{'category':12s} " + " ".join(f"{k[:14]:>14s}" for k in keys))
    for cat, r in summary.items():
        print(f"{cat:12s} " + " ".join(f"{r[k]:14.4f}" for k in keys))
    mean = {k: float(np.mean([r[k] for r in summary.values()])) for k in keys}
    print(f"{'MEAN':12s} " + " ".join(f"{mean[k]:14.4f}" for k in keys))


if __name__ == "__main__":
    main()