Note
Go to the end to download the full example code.
OpenOOD - ImageNet
Reproduces the OpenOOD benchmark for OOD detection, using a pre-trained ResNet 50.
Warning
This is currently incomplete, see ImageNet-OpenOOD.
10 import pandas as pd # additional dependency, used here for convenience
11 import torch
12 from torchvision.models import resnet50
13 from torchvision.models.resnet import ResNet50_Weights
14
15 from pytorch_ood.benchmark import ImageNet_OpenOOD
16 from pytorch_ood.detector import MaxSoftmax
17 from pytorch_ood.utils import fix_random_seed
18
19 fix_random_seed(123)
20
21 device = "cuda:0"
22 loader_kwargs = {"batch_size": 16, "num_workers": 12}
25 model = resnet50(ResNet50_Weights.IMAGENET1K_V1).eval().to(device)
26 trans = ResNet50_Weights.IMAGENET1K_V1.transforms()
27
28 print(trans)
If you want to test more detectors, you can just add them here
32 detectors = {
33 "MSP": MaxSoftmax(model),
34 }
The ImageNet root should contain at least the validation tar, the dev kit tar, and the meta.bin that is generated by the torchvision ImageNet implementation.
39 results = []
40 benchmark = ImageNet_OpenOOD(
41 root="data", image_net_root="data/imagenet-2012/", transform=trans
42 )
43
44
45 with torch.no_grad():
46 for detector_name, detector in detectors.items():
47 print(f"> Evaluating {detector_name}")
48 res = benchmark.evaluate(detector, loader_kwargs=loader_kwargs, device=device)
49 for r in res:
50 r.update({"Detector": detector_name})
51 results += res
52
53 df = pd.DataFrame(results)
54 print((df.set_index(["Dataset", "Detector"]) * 100).to_csv(float_format="%.2f"))
This should produce a table with the following output:
Dataset |
Detector |
AUROC |
AUPR-IN |
AUPR-OUT |
FPR95TPR |
|---|---|---|---|---|---|
ImageNetO |
MSP |
28.64 |
2.52 |
94.85 |
91.20 |
OpenImagesO |
MSP |
84.98 |
62.61 |
94.67 |
49.95 |
Textures |
MSP |
80.46 |
37.50 |
96.80 |
67.75 |
SVHN |
MSP |
97.62 |
95.56 |
98.77 |
11.58 |
MNIST |
MSP |
90.04 |
90.45 |
89.88 |
39.03 |