OpenOOD v1.5 - ImageNet

Reproduces the OpenOOD v1.5 benchmark for OOD detection on ImageNet, using a pre-trained ResNet 50.

 9 import pandas as pd  # additional dependency, used here for convenience
10 import torch
11 from torchvision.models import resnet50
12 from torchvision.models.resnet import ResNet50_Weights
13
14 from pytorch_ood.benchmark import ImageNet_OpenOOD
15 from pytorch_ood.detector import MaxSoftmax
16 from pytorch_ood.utils import fix_random_seed
17
18 fix_random_seed(123)
19
20 device = "cuda:0"
21 loader_kwargs = {"batch_size": 16, "num_workers": 12}
24 model = resnet50(ResNet50_Weights.IMAGENET1K_V1).eval().to(device)
25 trans = ResNet50_Weights.IMAGENET1K_V1.transforms()
26
27 print(trans)

If you want to test more detectors, you can just add them here

31 detectors = {
32     "MSP": MaxSoftmax(model),
33 }

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.

38 results = []
39 benchmark = ImageNet_OpenOOD(root="data", image_net_root="data/imagenet-2012/", transform=trans)
40
41
42 with torch.no_grad():
43     for detector_name, detector in detectors.items():
44         print(f"> Evaluating {detector_name}")
45         res = benchmark.evaluate(detector, loader_kwargs=loader_kwargs, device=device)
46         for r in res:
47             r.update({"Detector": detector_name})
48         results += res
49
50 df = pd.DataFrame(results)
51 print((df.set_index(["Dataset", "Detector"]) * 100).to_csv(float_format="%.2f"))

This should produce a table with results for the following OOD datasets:

  • SSBHard (near-OOD)

  • NINCO (near-OOD)

  • iNaturalist (far-OOD)

  • Textures (far-OOD)

  • OpenImagesO (far-OOD)

Gallery generated by Sphinx-Gallery