Skip to content

Out-of-Distribution Detection Metrics

← Calibration Metrics | Ensemble Metrics →

Out-of-Distribution (OOD) detection metrics evaluate how well a model can identify inputs or predictions that differ significantly from the training distribution.

OOD detection is a ranking problem, not a classification problem: a score \(s(x)\) is computed for each input (a density, a distance, an entropy, a typicality), and a threshold converts scores into accept/reject decisions. Because the threshold is a deployment choice, the threshold-free summary is the area under the ROC curve,

\[ \mathrm{AUROC} = P\big(s(X_{\text{in}}) > s(X_{\text{out}})\big) + \tfrac12 P\big(s(X_{\text{in}}) = s(X_{\text{out}})\big), \]

which is 0.5 for an uninformative score and 1.0 for perfect separation. A high AUROC does not imply good selective prediction: what matters downstream is the risk–coverage trade-off, scored by AURC and the rejection policy on the decision metrics page. → See also OOD API.


Mahalanobis Distance

Measures how many standard deviations a feature vector \(x\) is from the mean of the training representation distribution:

\[ d_M(x) = \sqrt{(x - \mu)^\top \Sigma^{-1} (x - \mu)} \]

where \(\mu\) is the mean vector of training representations and \(\Sigma\) is the training covariance matrix.

from torchregress.metrics.ood import mahalanobis_distance

# x has shape [batch_size, n_features]
# mean has shape [n_features]
# cov has shape [n_features, n_features]
md = mahalanobis_distance(x, mean, cov)
See also: mahalanobis_distance.

For numerical stability the covariance is regularised as \(\Sigma + \epsilon\,\overline{\operatorname{diag}\Sigma}\,I\) with jitter \(\epsilon = 10^{-6}\). The jitter is relative to the mean variance, so the distance does not change when the features are rescaled. Before 0.3 an absolute \(10^{-6} I\) dominated covariances with variances near \(10^{-8}\).


Typicality Score

Typicality measures whether a batch of test samples \(X = \{x_1, \dots, x_N\}\) exhibits the expected information content under the training distribution model \(p(x)\). Let the empirical entropy of the batch be:

\[ H_p(X) = -\frac{1}{N} \sum_{i=1}^N \log p(x_i) \]

The typicality score is the absolute deviation from the true model entropy \(H(p) = \mathbb{E}_{x \sim p}[-\log p(x)]\):

\[ T(X) = \left| H_p(X) - H(p) \right| \]

A high typicality score indicates that the batch contains samples that are either highly improbable or too structured, signaling a distribution shift.

from torchregress.metrics.ood import typicality_score

# Using a tuple of (mean, variance) representing distribution parameters
ts = typicality_score((mean_pred, var_pred), x_test)
See also: typicality_score.


Entropy Score

Calculates the Shannon/differential entropy of the predictive distribution \(p(y \mid x)\) as a measure of total predictive uncertainty:

\[ H(p) = -\int p(y \mid x) \log p(y \mid x) \, dy \]

For empirical samples, this can be estimated using histogram-based density binning:

\[ \hat{H}(p) = -\sum_{k=1}^K \hat{p}_k \log \hat{p}_k \]

where \(\hat{p}_k\) is the fraction of samples falling in bin \(k\).

from torchregress.metrics.ood import entropy_score

# samples has shape [n_samples, batch_size, ...]
es = entropy_score(samples)
See also: entropy_score.


Kernel Density Score

Estimates target density using a reference training set \(\{r_1, \dots, r_R\}\) under an RBF (Gaussian) kernel:

\[ \hat{f}_h(x) = \frac{1}{R} \sum_{k=1}^R K_h(x - r_k) \]
\[ K_h(d) = \frac{1}{(2\pi h^2)^{D/2}} \exp\left(-\frac{\|d\|^2}{2h^2}\right) \]

where \(h > 0\) is the bandwidth parameter and \(D\) is the dimensionality of feature space.

from torchregress.metrics.ood import kernel_density_score

kds = kernel_density_score(x_test, x_reference, bandwidth=0.5)
See also: kernel_density_score.


Comprehensive Reporting

OOD Metrics Report

Generate a comprehensive report of OOD detection metrics.

from torchregress.metrics.ood import ood_metrics_report

report = ood_metrics_report(
    model_output=(mean_pred, var_pred),
    x_test=x_test,
    x_reference=x_train,
    mean=train_mean,
    cov=train_cov,
    samples=pred_samples
)
See also: ood_metrics_report.


Limitations

  1. No ground truth for OOD: OOD detection is inherently unsupervised — there is no "true OOD label" to validate against. All OOD metrics are relative: they rank samples by abnormality, but setting a decision threshold requires domain knowledge.
  2. Mahalanobis assumes Gaussian features: The Mahalanobis distance uses a Gaussian approximation with \(\mu\) and \(\Sigma\) estimated from training data. For non-Gaussian or multimodal feature distributions, it can produce misleading distances.
  3. KDE bandwidth sensitivity: kernel_density_score with \(h\) too small produces spiky density estimates; \(h\) too large blurs genuine OOD regions. Tune \(h\) on a validation set with known OOD samples if available.
  4. Entropy conflates epistemic and aleatoric: High predictive entropy can indicate either genuine data noise (aleatoric) or unfamiliar inputs (epistemic). For decomposed OOD detection, use ensemble-based uncertainty metrics from Ensemble metrics.

Recommendations

  • Layer multiple OOD scores: No single OOD metric is universally best. Combine Mahalanobis distance (feature-space), entropy (prediction-space), and KDE score (density-based) for robust detection.
  • Calibrate uncertainty first: OOD scores that use predictive uncertainty (entropy, typicality) are only reliable if the model is well-calibrated. Always validate calibration before using uncertainty for OOD. See Calibration metrics.
  • OOD-aware training: The best OOD detection starts at training time. Use SpectralNormWrapper for smoother OOD behaviour, and train with data augmentations to cover plausible shifts.
  • ood_metrics_report consolidates all OOD metrics into one call.

Next steps


References

# Reference
1 K. Lee, K. Lee, H. Lee, J. Shin. "A Simple Unified Framework for Detecting Out-of-Distribution Samples and Adversarial Attacks." NeurIPS, 2018.
2 E. Nalisnick, A. Matsukawa, Y.W. Teh, D. Görür, B. Lakshminarayanan. "Do Deep Generative Models Know What They Don't Know?" ICLR, 2019.
3 E. Parzen. "On Estimation of a Probability Density Function and Mode." Ann. Math. Stat., 33(3):1065–1076, 1962.