A Python library for Out-of-Distribution (OOD) Detection with Deep Neural Networks based on PyTorch.
The library provides:
Out-of-Distribution Detection Methods
Loss Functions
Datasets
Neural Network Architectures, as well as pre-trained weights
Data Augmentations
Useful Utilities
and is designed to be compatible with frameworks like pytorch-lightning and pytorch-segmentation-models. The library also covers some methods from closely related fields, such as Open-Set Recognition, Novelty Detection, Confidence Estimation and Anomaly Detection.
📚 Documentation
The documentation is available here.
NOTE: An important convention adopted in pytorch-ood is that OOD detectors predict outlier scores that should be larger for outliers than for inliers. If you notice that the scores predicted by a detector do not match the formulas in the corresponding publication, we may have adjusted the score calculation to comply with this convention.
💬 Getting Help
For questions about using PyTorch-OOD, open a usage support request.
To report incorrect or broken behavior, open a bug report.
To propose or contribute changes, read the contribution guidelines.
Before requesting support, please check the documentation and existing issues. Include the PyTorch-OOD, Python, and PyTorch versions, your platform and device, a minimal reproducer, and the complete error output. See the support guide for details.
⏳ Quick Start
Load a WideResNet-40 model (used in major publications), pre-trained on CIFAR-10 with the Energy-Bounded Learning Loss [8] (weights from to original paper), and predict on some dataset data_loader using Energy-based OOD Detection (EBO) [8], calculating the common metrics. OOD data must be marked with labels < 0.
from pytorch_ood.detector import EnergyBased
from pytorch_ood.utils import OODMetrics
from pytorch_ood.model import load_model, load_transform
data_loader = ... # your data, OOD with label < 0
# Create Neural Network
model = load_model("wrn-40-2/cifar10/energy/s1").cuda()
preprocess = load_transform("wrn-40-2/cifar10/energy/s1")
# Create detector
detector = EnergyBased(model)
# Evaluate
metrics = OODMetrics()
for x, y in data_loader:
x = preprocess(x).cuda()
metrics.update(detector(x), y)
print(metrics.compute())
You can find more examples in the documentation.
Benchmarks (Beta)
Evaluate detectors against common benchmarks, for example the OpenOOD v1.5 CIFAR benchmark. All datasets will be downloaded automatically. When evaluating several detectors on the same benchmark, cached logits and pooled features can be reused across calls:
import pandas as pd
from pytorch_ood.benchmark import CIFAR10_OpenOOD
from pytorch_ood.detector import EnergyBased, MaxSoftmax
from pytorch_ood.model import load_model, load_transform
model = load_model("wrn-40-2/cifar10/crossentropy").to("cuda:0")
trans = load_transform("wrn-40-2/cifar10/crossentropy")
benchmark = CIFAR10_OpenOOD(root="data", transform=trans)
detectors = {
"MSP": MaxSoftmax(model),
"Energy": EnergyBased(model),
}
results = []
for name, detector in detectors.items():
res = benchmark.evaluate(
detector,
loader_kwargs={"batch_size": 128, "num_workers": 12},
device="cuda:0",
cache=True,
cache_dir="data/benchmark-cache",
cache_key="cifar10-openood-wrn-cifar10-pt",
)
for row in res:
row.update({"Detector": name})
results += res
print(pd.DataFrame(results))
🛠 ️️Installation
The package can be installed via PyPI:
pip install pytorch-ood
Dependencies
torch
torchvision
scipy
torchmetrics
Optional Dependencies
scikit-learn for ViM and k-NN
gdown to download some datasets and model weights
pandas for the examples.
segmentation-models-pytorch to run the examples for anomaly segmentation
📝 Citing
If you use this project, please cite:
@inproceedings{kirchheim2022pytorch,
title={Pytorch-ood: A library for out-of-distribution detection based on pytorch},
author={Kirchheim, Konstantin and Filax, Marco and Ortmeier, Frank},
booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
pages={4351--4360},
year={2022}
}
📦 Implemented
Detectors:
Detector |
Description |
Year |
Ref |
|---|---|---|---|
OpenMax |
Implementation of the OpenMax Layer as proposed in the paper Towards Open Set Deep Networks. |
2016 |
|
Monte Carlo Dropout |
Implements Monte Carlo Dropout. |
2016 |
|
Maximum Softmax Probability |
Implements the Softmax Baseline for OOD and Error detection. |
2017 |
|
Temperature Scaling |
Implements the Temperature Scaling for Softmax. |
2017 |
|
ODIN |
ODIN is a preprocessing method for inputs that aims to increase the discriminability of the softmax outputs for In- and Out-of-Distribution data. |
2018 |
|
Mahalanobis |
Implements the Mahalanobis Method. |
2018 |
|
Multi-Layer Mahalanobis |
Mahalanobis distance computed across multiple network layers. |
2018 |
|
GRAM |
Detects OOD elements via deviations in the gram matrices |
2019 |
|
Energy-Based OOD Detection |
Implements the energy score of Energy-based Out-of-distribution Detection. |
2020 |
|
GradNorm |
Gradient norms as a measure of uncertainty in neural networks. |
2020 |
|
Entropy |
Uses entropy to detect OOD inputs. |
2021 |
|
ReAct |
ReAct: Out-of-distribution detection with Rectified Activations. |
2021 |
|
GradNormKL |
KL-divergence gradient norms for detecting distributional shifts. |
2021 |
|
Relative Mahalanobis (RMD) |
Relative Mahalanobis distance with a background Gaussian. |
2021 |
|
PNML |
Predictive normalized maximum likelihood regret on normalized penultimate-layer features. |
2021 |
|
Maximum Logit |
Implements the MaxLogit method. |
2022 |
|
KL-Matching |
Implements the KL-Matching method for Multi-Class classification. |
2022 |
|
ViM |
Implements Virtual Logit Matching. |
2022 |
|
Weighted Energy-Based |
Implements Weighted Energy-Based for OOD Detection |
2022 |
|
Nearest Neighbor |
Implements Depp Nearest Neighbors for OOD Detection |
2022 |
|
DICE |
Implements Sparsification for OOD Detection |
2022 |
|
RankFeat |
Rank-1 feature removal from feature maps for OOD detection. |
2022 |
|
MCM |
Maximum Concept Matching for zero-shot OOD detection with vision-language models. |
2022 |
|
ASH |
Implements Extremely Simple Activation Shaping |
2023 |
|
SHE |
Implements Simplified Hopfield Networks |
2023 |
|
NNGuide |
Nearest Neighbor Guidance for OOD Detection |
2023 |
|
GEN |
Generalized entropy score pushing the limits of softmax-based detection. |
2023 |
|
fDBD |
Fast decision boundary distance for OOD detection. |
2023 |
|
VRA |
Variance-based ReAct adjustment with learned percentile thresholds. |
2023 |
|
NAC-UE |
Neuron Activation Coverage for OOD detection. |
2023 |
|
SCALE |
Implements Activation Scaling for OOD Detection |
2024 |
|
NCI |
Neural Collapse Inspired OOD Detection |
2025 |
|
GMM |
Class-conditional Gaussian Mixture Model on penultimate-layer features. |
Objective Functions:
Objective Function |
Description |
Year |
Ref |
|---|---|---|---|
Objectosphere |
Implementation of the paper Reducing Network Agnostophobia. |
2016 |
|
Center Loss |
Generalized version of the Center Loss from the Paper A Discriminative Feature Learning Approach for Deep Face Recognition. |
2016 |
|
Outlier Exposure |
Implementation of the paper Deep Anomaly Detection With Outlier Exposure. |
2018 |
|
Confidence Loss |
Model learn confidence additional to class membership prediction. |
2018 |
|
Deep SVDD |
Implementation of the Deep Support Vector Data Description from the paper Deep One-Class Classification. |
2018 |
|
Energy-Bounded Loss |
Adds a regularization term to the cross-entropy that aims to increase the energy gap between IN and OOD samples. |
2020 |
|
CAC Loss |
Class Anchor Clustering Loss from Class Anchor Clustering: a Distance-based Loss for Training Open Set Classifiers |
2021 |
|
Entropic Open-Set Loss |
Entropy maximization and meta classification for OOD in semantic segmentation |
2021 |
|
II Loss |
Implementation of II Loss function from Learning a neural network-based representation for open set recognition. |
2022 |
|
MCHAD Loss |
Implementation of the MCHAD Loss from the paper Multi Class Hypersphere Anomaly Detection. |
2022 |
|
VOS Energy-Based Loss |
Implementation of the paper VOS: Learning what you don’t know by virtual outlier synthesis. |
2022 |
|
Logit Normalization |
Implementation of the paper Mitigating Neural Network Overconfidence with Logit Normalization. |
2022 |
Image Datasets:
Dataset |
Description |
Year |
Ref |
|---|---|---|---|
Chars74k |
The Chars74K dataset contains 74,000 images across 64 classes, comprising English letters and Arabic numerals. |
2012 |
|
TinyImages |
The TinyImages dataset is often used as auxiliary OOD training data. However, use is discouraged. |
2012 |
|
Textures |
Textures dataset, also known as DTD, often used as OOD Examples. |
2013 |
|
FoolingImages |
OOD Images Generated to fool certain Deep Neural Networks. |
2015 |
|
Tiny ImageNet |
A derived version of ImageNet with 64x64-sized images. |
2015 |
|
TinyImages300k |
A cleaned version of the TinyImages Dataset with 300.000 images, often used as auxiliary OOD training data. |
2018 |
|
LSUN |
A version of the Large-scale Scene UNderstanding Dataset with 10.000 images, often used as auxiliary OOD training data. |
2018 |
|
MNIST-C |
Corrupted version of the MNIST. |
2019 |
|
CIFAR10-C |
Corrupted version of the CIFAR 10. |
2019 |
|
CIFAR100-C |
Corrupted version of the CIFAR 100. |
2019 |
|
ImageNet-C |
Corrupted version of the ImageNet. |
2019 |
|
ImageNet - A, O, R |
Different Outlier Variants for the ImageNet. |
2019 |
|
ImageNet - V2 |
A new test set for the ImageNet. |
2019 |
|
ImageNet - ES |
Event stream (ES) version of the ImageNet. |
2021 |
|
iNaturalist |
A Subset of iNaturalist, with 10.000 images. |
2021 |
|
FS Static |
The FishyScapes (FS) Static dataset contains real world OOD images from the CityScapes dataset. |
2021 |
|
FS LostAndFound |
The FishyScapes dataset contains images from the CityScapes dataset blended with unknown objects scraped from the web. |
2021 |
|
MVTech-AD |
The MVTec AD is a dataset for benchmarking anomaly detection methods with a focus on industrial inspection. |
2021 |
|
Fractals |
A dataset with Fractals from PIXMIX: Dreamlike Pictures Comprehensively Improve Safety Measures |
2022 |
|
Feature Visualizations |
A dataset with Feature visualizations from PIXMIX: Dreamlike Pictures Comprehensively Improve Safety Measures |
2022 |
|
StreetHazards |
Anomaly Segmentation Dataset |
2022 |
|
CIFAR100-GAN |
Images sampled from low likelihood regions of a BigGAN trained on CIFAR 100 from the paper On Outlier Exposure with Generative Models. |
2022 |
|
SSB - hard |
The hard split of the Semantic Shift Benchmark, which contains 49.00 images. |
2022 |
|
ImageNet-200 |
The 200-class ImageNet subset used as in-distribution data in the OpenOOD benchmark. |
2023 |
|
NINCO |
The NINCO (No ImageNet Class Objects) dataset which contains 5.879 images of 64 OOD classes. |
2023 |
|
SuMNIST |
The SuMNIST dataset is based on MNIST but each image display four numbers instead of one. |
2023 |
|
Gaussian Noise |
Dataset with samples drawn from a normal distribution. |
||
Uniform Noise |
Dataset with samples drawn from a uniform distribution. |
Text Datasets:
Dataset |
Description |
Year |
Ref |
|---|---|---|---|
Multi30k |
Multi-30k dataset, as used by Hendrycks et al. in the OOD baseline paper. |
2016 |
|
WikiText2 |
Texts from the wikipedia often used as auxiliary OOD training data. |
2016 |
|
WikiText103 |
Texts from the wikipedia often used as auxiliary OOD training data. |
2016 |
|
NewsGroup20 |
Texts from different newsgroups, as used by Hendrycks et al. in the OOD baseline paper. |
Augmentation Methods:
Augmentation |
Description |
Year |
Ref |
|---|---|---|---|
COCO Outlier Pasting |
From “Entropy maximization and meta classification for OOD in semantic segmentation” |
2021 |
|
PixMix |
PixMix image augmentation method |
2022 |
Benchmarks:
Benchmark |
Description |
Year |
Ref |
|---|---|---|---|
CIFAR-10 ODIN |
ODIN benchmark for CIFAR-10 OOD detection evaluation. |
2018 |
|
CIFAR-100 ODIN |
ODIN benchmark for CIFAR-100 OOD detection evaluation. |
2018 |
|
CIFAR-10 OpenOOD |
CIFAR-10 benchmark with OpenOOD protocol for standardized OOD evaluation. |
2023 |
|
CIFAR-100 OpenOOD |
CIFAR-100 benchmark with OpenOOD protocol for standardized OOD evaluation. |
2023 |
|
ImageNet OpenOOD |
ImageNet-1K OOD detection benchmark with OpenOOD protocol and evaluation suite. |
2023 |
|
ImageNet-200 OpenOOD |
ImageNet-200 (200-class subset) OOD detection benchmark with OpenOOD protocol. |
2023 |
|
MIDOG OpenMIBOOD |
Microscopy / mitosis detection with 4-way split (ID, covariate-shifted, near-OOD, far-OOD). |
2025 |
|
PhaKIR OpenMIBOOD |
Surgical video frames with 4-way split (ID, covariate-shifted, near-OOD, far-OOD). |
2025 |
|
OASIS-3 OpenMIBOOD |
Brain MRI volumes with 4-way split (ID, covariate-shifted, near-OOD, far-OOD). |
2025 |
🤝 Contributing
We encourage everyone to contribute to this project by adding implementations of OOD Detection methods, datasets etc, or check the existing implementations for bugs. See the contribution guidelines to get started.
🛡️ ️License
The code is licensed under Apache 2.0. We have taken care to make sure any third party code included or adapted has compatible (permissive) licenses such as MIT, BSD, etc. The legal implications of using pre-trained models in commercial services are, to our knowledge, not fully understood.
🔗 References
Release files for pytorch-ood 0.3.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| pytorch_ood-0.3.3-py3-none-any.whl | Python 3 | none | any | Details |
Release files / pytorch_ood-0.3.3-py3-none-any.whl
| Download URL | pytorch_ood-0.3.3-py3-none-any.whl |
|---|---|
| Size | 473.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2591ccca70bfcd5bdc4ef0c9bd2c1462018e1127526f75c9be807a8693c3128b
|
|
BLAKE2b-256 checksum How to use checksums |
c3de37d7ff5115f75301e9a468a557068b737cae1f51391354f69818a1de9d76
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.2
|