Foundations to Frontier
Tests
I. Probabilistic ML and Uncertainty Quantification › I5 Robustness to Distribution Shift

Out-of-distribution detection

A classifier must give some answer for every input, including inputs from nothing it was trained on: a new object class, a broken sensor, an image from another planet. Out-of-distribution (OOD) detection adds a score that flags such inputs so that the system can abstain or hand over. This page covers the main post-hoc scores and what each measures. The maximum softmax probability, max logit and energy measure confidence. ODIN and ReAct modify the network. Mahalanobis distance, k-nearest-neighbour distance and ViM measure distance in feature space. Training-time methods such as outlier exposure are covered too, along with the AUROC and FPR-at-95%-TPR metrics, the near-OOD and far-OOD split used by OpenOOD, and why generative likelihoods can fail. In the exercises you implement the scores and the metrics. You then test them on a simulated feature space with four kinds of OOD input, and no score won everywhere. Mahalanobis and kNN distances caught far-away inputs perfectly (AUROC 1.000), where MSP reached only 0.898. Inputs with exaggerated class features fooled every logit-based score and normalised kNN (AUROC 0.000, more confident than real data) but not Mahalanobis (1.000). Inputs lying between the classes were caught by energy (0.991) and missed by Mahalanobis (0.777).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Knowing what you don’t know

A classifier trained to recognise five kinds of spacecraft will confidently label a bird as one of them, because it has no option to say “none of these”. OOD detection adds a second number: how unusual the input looks compared with the training data. If the number is too high, the system refuses to answer or asks a human. The tricky part is choosing the number. The classifier’s own confidence is easy to use but can be fooled; distances in the network’s feature space catch other cases. The demo shows how the overlap between in-distribution and OOD scores sets the trade-off between missed OOD inputs and false alarms.

Calibration, conformal and shift lab
ID scores (green) and OOD scores (red); flag as OOD above the threshold. TPR on ID kept 94.5%, OOD wrongly kept (FPR) 65.5%, AUROC 0.921.
Why engineers care

A rover’s terrain classifier was trained on sand, rock and bedrock. Ice, a dust-covered lens or an unknown mineral should be flagged and routed to a cautious mode, not forced into the nearest class.

📝 Quick check (Level 0)
0/3 answered
  1. 1. OOD detection flags inputs that are…
  2. 2. A plain classifier on an unknown input will…
  3. 3. AUROC of 0.5 means the score is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Confidence scores: maximum softmax probability, MSP (Hendrycks and Gimpel, 2017); max logit (Hendrycks et al., 2022); energy −T log Σ exp(z/T) (Liu et al., 2020). ODIN (Liang et al., 2018) adds temperature and a small input perturbation. ReAct (Sun et al., 2021) clips large activations, and ASH (Djurisic et al., 2023) prunes them.
  • Feature-distance scores: class-conditional Gaussians with a shared covariance and the minimum Mahalanobis distance (Lee et al., 2018); k-th nearest-neighbour distance on L2-normalised features (Sun et al., 2022); ViM (Wang et al., 2022) combines the residual off the principal subspace with logits.
  • Training-time methods: outlier exposure (Hendrycks et al., 2019) trains on an auxiliary outlier set to output uniform predictions; contrastive and logit-normalised training also help.
  • Generative models: likelihoods from flows and VAEs can rate OOD data higher than training data, such as SVHN under a CIFAR-10 model (Nalisnick et al., 2019); likelihood ratios and typicality tests help.
  • Metrics: AUROC; FPR at 95% TPR, the share of OOD inputs accepted when 95% of in-distribution inputs pass; AUPR. Benchmarks: OpenOOD v1.5 (Zhang et al., 2023) separates near-OOD (semantically close, such as new classes) from far-OOD (other datasets).
  • Foundation models: zero-shot OOD with CLIP (maximum concept matching, MCM; Ming et al., 2022) and embedding-distance monitors for LLM inputs.
📝 Quick check (Level 1)
0/3 answered
  1. 1. The energy score is…
  2. 2. FPR at 95% TPR measures…
  3. 3. Outlier exposure trains with…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Scores and metrics

Exercise 1.

  • MSP and energy scores from logits.
  • The minimum class-conditional Mahalanobis distance.
  • AUROC by counting pairs, and FPR at 95% TPR.

Practice.

  • Start with energy or max logit (free) and a feature-distance score (Mahalanobis or kNN on penultimate features). Compare them on near-OOD and far-OOD sets similar to what you expect in deployment.
  • Fit covariances and kNN banks on training features only; tune thresholds on in-distribution validation data to a target TPR.
  • Report AUROC and FPR at 95% TPR per OOD set, not averaged across sets.
  • Combine OOD detection with selective prediction and monitoring; OOD scores also flag misclassified ID inputs, which may or may not be wanted.
  • Libraries: OpenOOD (benchmark and 40+ methods), pytorch-ood, and FAISS for kNN banks.
import torch, faiss
z, f = model.logits_and_features(x)                      # logits (N, K), penultimate features (N, d)
energy = -torch.logsumexp(z, dim=1)                       # higher = more OOD
msp = -torch.softmax(z, dim=1).max(dim=1).values
P = torch.linalg.inv(cov_train)                           # shared covariance of training features
d = f[:, None, :] - class_means[None]                     # (N, K, d)
maha = torch.einsum("nkd,de,nke->nk", d, P, d).min(dim=1).values
index = faiss.IndexFlatL2(feat_dim); index.add(train_feats_normalized)
knn = index.search(torch.nn.functional.normalize(f, dim=1).numpy(), 10)[0][:, -1]
🐍 Exercise 1: OOD scores and metrics
Implement MSP, energy and Mahalanobis OOD scores, AUROC by pair counting and FPR at 95% TPR.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Thresholds for OOD scores are set on…
  2. 2. A benchmark with near- and far-OOD splits:
  3. 3. Report OOD metrics…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

What each score sees. Softmax-based scores depend only on the logits. A linear classifier’s logits grow with the feature component along the class directions, so an input with an exaggerated version of a class pattern gets larger logits and higher confidence than any real example. Confidence scores rank it as most in-distribution. Normalising features to unit length, as the kNN method does, throws away the same norm information. The Mahalanobis distance measures distance to the class clusters in all directions, so it catches exaggerated inputs and far-away inputs. It is less reliable for inputs between clusters, because in high dimensions in-distribution points are themselves far from their means: their squared distance is about d.

Energy versus MSP. The energy −log Σ exp(z_k) is, up to a constant, the negative log of the unnormalised density p(x) of the energy-based model behind the softmax. MSP = exp(z_max)/Σ exp(z_k) normalises this away and saturates near 1. Energy keeps the scale of the logits, which is why it separated far-OOD inputs better than MSP in the exercise.

No free lunch for OOD. Detecting every possible OOD input is impossible without assumptions about what OOD looks like (Fang et al., 2022, on learnability of OOD detection). Each score encodes such an assumption, so evaluate on OOD data that resembles the failures you fear.

AUROC as a probability. AUROC = P(score_OOD > score_ID) for independent draws. For Gaussian scores N(0, 1) and N(d, 1) it equals Φ(d/√2).

📝 Quick check (Level 3)
0/3 answered
  1. 1. Inputs with exaggerated class features fool…
  2. 2. Energy is related to…
  3. 3. AUROC for Gaussian scores separated by d is…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Which OOD score catches which kind of novelty, and is there one that wins everywhere?

History.

  • D. Hendrycks and K. Gimpel (2017) MSP baseline; S. Liang, Y. Li and R. Srikant (2018) ODIN; K. Lee et al. (2018) Mahalanobis.
  • D. Hendrycks, M. Mazeika and T. Dietterich (2019) outlier exposure; E. Nalisnick et al. (2019) generative likelihood failures; W. Liu et al. (2020) energy.
  • Y. Sun et al. (2021) ReAct and (2022) kNN; H. Wang et al. (2022) ViM; J. Zhang et al. (2023) OpenOOD v1.5.

Exercise 2. A simulated feature space standing in for a network’s penultimate layer.

  • In-distribution: 5 classes in 16 dimensions with identity covariance and class means of norm 4; 200 training points per class; linear classifier from class means (LDA); ID accuracy 0.990.
  • OOD sets (1000 each): far (centre at norm 8 in a random direction); a new class (a sixth cluster of norm 4); amplified (3 times a class mean plus noise: an exaggerated class pattern); central (noise around the origin, between the classes).
  • Scores: MSP, max logit, energy, Mahalanobis (shared covariance) and kNN (10th neighbour on unit-normalised features). Results are AUROC, with FPR at 95% TPR in brackets.
OOD set MSP max logit energy Mahalanobis kNN
far 0.898 (0.449) 0.957 (0.222) 0.957 (0.222) 1.000 (0.000) 1.000 (0.000)
new class 0.932 (0.350) 0.974 (0.146) 0.974 (0.150) 0.958 (0.208) 0.990 (0.047)
amplified 0.000 (1.000) 0.000 (1.000) 0.000 (1.000) 1.000 (0.000) 0.005 (1.000)
central 0.958 (0.220) 0.991 (0.044) 0.991 (0.044) 0.777 (0.761) 0.983 (0.087)
  • No score won everywhere. Feature distances were perfect on far OOD inputs, and kNN was best on the new class.
  • Amplified inputs were the starkest failure: every softmax-based score, and kNN on normalised features, rated them more in-distribution than real data (AUROC 0, every one accepted). Mahalanobis caught all of them.
  • Inputs between the classes were easy for logit scores (energy 0.991) and hard for Mahalanobis (0.777). In 16 dimensions, ordinary points already lie at squared distance about 16 from their class mean, so being far from all means is less unusual than it sounds.
  • On seed 0, energy and max logit beat MSP on every OOD set except amplified, where all three failed (not on seed 1, below).
  • Seeds 1 and 2: the far set depends on its random direction. On seed 1 energy dropped to 0.740 and MSP reached 0.859; on seed 2 energy reached 0.978 and MSP 0.763. Mahalanobis stayed at 1.000 on far and amplified inputs; central-set Mahalanobis gave 0.791 and 0.816; new-class kNN 0.997 and 0.973.
🐍 Exercise 2 (research): which OOD score catches which kind of novelty, and is there one that wins everywhere?
Simulate class-conditional features and four kinds of OOD input; compare MSP, max logit, energy, Mahalanobis and kNN scores by AUROC and FPR at 95% TPR.

OOD detection in AI, robotics and aerospace

  • Autonomous driving and drones: OOD monitors on perception features trigger fallback behaviours when the scene is outside the operational design domain.
  • Space missions: onboard classifiers for science targets flag novel observations for downlink, turning OOD detection into discovery.
  • Safety assurance: guidance for ML in aviation, such as EASA’s AI concept papers, asks for monitors of the operational domain at run time; OOD scores are one ingredient.

References

  1. D. Hendrycks and K. Gimpel (2017). “A baseline for detecting misclassified and out-of-distribution examples in neural networks.” ICLR.
  2. K. Lee, K. Lee, H. Lee and J. Shin (2018). “A simple unified framework for detecting out-of-distribution samples and adversarial attacks.” NeurIPS.
  3. W. Liu, X. Wang, J. Owens and Y. Li (2020). “Energy-based out-of-distribution detection.” NeurIPS.
  4. Y. Sun, Y. Ming, X. Zhu and Y. Li (2022). “Out-of-distribution detection with deep nearest neighbors.” ICML.
  5. J. Zhang et al. (2023). “OpenOOD v1.5: enhanced benchmark for out-of-distribution detection.” arXiv.