File size: 2,600 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
"""Evaluation metrics: image AUROC, pixel AUROC, AU-PRO (FPR <= 0.3), F1."""
from __future__ import annotations

import numpy as np
from scipy import ndimage
from sklearn.metrics import precision_recall_curve, roc_auc_score


def f1_at(labels, scores, thr):
    pred = scores >= thr
    tp = np.sum(pred & (labels == 1))
    fp = np.sum(pred & (labels == 0))
    fn = np.sum(~pred & (labels == 1))
    return 2 * tp / max(1, 2 * tp + fp + fn)


def f1_max(labels, scores):
    p, r, t = precision_recall_curve(labels, scores)
    f1 = 2 * p * r / np.clip(p + r, 1e-12, None)
    i = int(np.nanargmax(f1[:-1]))
    return float(f1[i]), float(t[i])


def au_pro(masks: np.ndarray, maps: np.ndarray, fpr_limit=0.3, n_thr=500) -> float:
    """Per-Region Overlap curve area (Bergmann et al., MVTec AD), normalised to [0,1].

    masks: (N,H,W) binary, maps: (N,H,W) float.
    """
    masks = masks.astype(bool)
    normal_px = np.sort(maps[~masks])
    regions = []
    for m, a in zip(masks, maps):
        if not m.any():
            continue
        lab, n = ndimage.label(m)
        for k in range(1, n + 1):
            regions.append(np.sort(a[lab == k]))
    if not regions:
        return float("nan")
    lo, hi = maps.min(), maps.max()
    thrs = np.linspace(hi, lo, n_thr)
    fpr = 1.0 - np.searchsorted(normal_px, thrs, side="right") / len(normal_px)
    pro = np.mean([1.0 - np.searchsorted(r, thrs, side="right") / len(r) for r in regions], axis=0)
    keep = fpr <= fpr_limit
    f, p = fpr[keep], pro[keep]
    # close the curve exactly at fpr_limit by linear interpolation
    j = np.searchsorted(fpr, fpr_limit)
    if j < len(fpr) and len(f) and f[-1] < fpr_limit:
        f1_, f2_ = fpr[j - 1], fpr[j]
        w = (fpr_limit - f1_) / max(f2_ - f1_, 1e-12)
        f = np.append(f, fpr_limit)
        p = np.append(p, pro[j - 1] + w * (pro[j] - pro[j - 1]))
    return float(np.trapezoid(p, f) / fpr_limit)


def compute_all(labels, img_scores, masks, maps, image_thr):
    labels = np.asarray(labels)
    img_scores = np.asarray(img_scores)
    out = {
        "image_auroc": float(roc_auc_score(labels, img_scores)),
        "pixel_auroc": float(roc_auc_score(masks.ravel().astype(np.uint8), maps.ravel())),
        "au_pro": au_pro(masks, maps),
    }
    out["image_f1_max"], out["oracle_threshold"] = f1_max(labels, img_scores)
    out["image_f1_calibrated"] = float(f1_at(labels, img_scores, image_thr))
    pred = img_scores >= image_thr
    out["recall_calibrated"] = float(pred[labels == 1].mean())
    out["fpr_calibrated"] = float(pred[labels == 0].mean())
    return out