Anomaly & Out-of-Distribution Detection
Isolation forests, one-class methods and OOD detection.
Anomaly detection asks a model to recognize what it has never seen. With no examples of anomalies, the only principled target is the region where normal data are unlikely, and that target quietly depends on a reference measure, a representation and a base rate. This lesson proves what density level sets optimize, analyzes the classic detectors (local outlier factor, isolation forest, one-class SVM), and shows why out-of-distribution detection for deep networks, especially with generative likelihoods, is harder than it looks.
What you’ll learn
- Formalize anomaly detection as density level-set estimation, and prove that level sets are minimum-volume sets: most powerful tests against uniformly spread anomalies.
- Explain the local outlier factor and isolation forests, including the path-length normalization and the score .
- State the one-class SVM in primal and dual form, and prove its -property from the KKT conditions.
- Compare out-of-distribution scores for deep classifiers, explain why deep generative likelihoods fail as detectors, and evaluate detectors honestly under realistic base rates.
Anomalies as level sets
Normal data are drawn i.i.d. from with density on . This lesson treats point anomalies; contextual and collective anomalies (Chandola, Banerjee & Kumar, 2009) can be turned into point anomalies by building the context or the sequence into the features. In novelty detection the training data are clean; in outlier detection they contain a few anomalies already. Either way, an anomaly detector is defined by a region declared normal, with false-alarm rate . With no anomalies to learn from, which should you pick? If anomalies could appear with equal probability anywhere in a bounded region that holds the normal data, the detector that catches the most of them at a given is the one whose normal region has the smallest volume.
Let . Removing the common part from both sides leaves
Outside the density is below , and inside it is at least :
Divide by and add to both sides.
The "right" detector therefore depends on a reference measure: volume in the coordinates you chose. Under a smooth bijection the density becomes , so the level sets, and the ranking of points by rarity, change unless preserves volume. Every density-based detector makes this choice implicitly, through its features. In practice the level set is estimated by thresholding an estimate, , with set at the -quantile of on held-out normal data; in high dimension, methods that estimate a score monotone in directly often work better than estimating itself.
You flag incomes whose estimated density is in the lowest 1%. A colleague first takes and flags the lowest 1% of the density of . Do you flag the same people?
- Yes: a monotone transform keeps the data in the same order, so the flagged set is the same
- Yes, because both thresholds are set at the 1% quantile
- No: the log-space density is , so low incomes look rarer and high incomes less rare
- No, because the log transform changes the number of data points
Show the answer
C. No: the log-space density is , so low incomes look rarer and high incomes less rare
By the change-of-variables formula, , so each point's density is multiplied by its own income. The ranking of points by density changes, and with it the flagged set. Which answer is "right" depends on which coordinates make anomalies roughly uniform, a modeling choice the data cannot make for you.
Neighbors and isolation
Distance-based detectors avoid estimating . The simplest score is the distance to the -th nearest neighbor, which is small where the data are dense: a -nearest-neighbor density estimate divides by the volume of the ball with that radius. A single global threshold fails when clusters have different densities, though: a point at the fringe of a tight cluster can be anomalous while points in a diffuse cluster, at the same distance from their neighbors, are not.
The local outlier factor (Breunig, Kriegel, Ng & Sander, 2000) compares each point's density with its neighbors'. With the nearest neighbors and the distance from to its own -th neighbor, define the reachability distance , the local reachability density as the reciprocal of the mean reachability distance from to its neighbors, and
LOF is about 1 inside any cluster, dense or diffuse, and well above 1 for points much sparser than their neighbors. The cost is a nearest-neighbor search, which is expensive and unreliable in high dimension.
An isolation forest (Liu, Ting & Zhou, 2008) turns the question around: anomalies are few and different, so they are easy to isolate. Each isolation tree is grown on a random subsample of points by repeatedly picking a feature at random and a split value uniformly between that feature's minimum and maximum in the node, until points are alone or a depth limit near is reached. The path length counts the splits needed to isolate , with a correction for subtrees cut off by the depth limit. Averaging over trees and normalizing gives the score
where is the harmonic number and is the average path length of an unsuccessful search in a binary search tree with keys. A point with scores exactly 0.5, and scores near 1 flag anomalies. The defaults and work across many data sets, training takes time, and nothing needs distances or densities. Axis-parallel cuts leave artifacts along the coordinate directions; random oblique cuts reduce them (Hariri, Carrasco Kind & Brunner, 2021).
Isolation trees are grown on subsamples of points, so . A point is isolated after 4 splits on average. What is its score ?
Show the answer
0.76
and : a likely anomaly. A point needing 15 splits scores , comfortably normal. The normalization by makes scores comparable across subsample sizes, since typical path lengths grow like .
One-class SVMs and the ν-property
The one-class SVM (Schölkopf, Platt, Shawe-Taylor, Smola & Williamson, 2001) maps the data into a feature space with a kernel and separates them from the origin with maximum margin, allowing a few violations:
The decision function is , with dual coefficients solving
Points with are the support vectors; points with fall outside the estimated region and are the training outliers.
Stationarity of the Lagrangian in gives , and every . So at least coefficients are nonzero:
Stationarity in gives , where is the multiplier of . By complementary slackness (KKT), forces , so every outlier sits at the upper bound and uses up its share of the budget:
So is a direct handle on the training false-alarm rate. At the box constraint forces every , and the decision rule becomes : with a Gaussian RBF kernel this is, up to a constant factor, a thresholded kernel density estimate. Smaller makes the expansion sparse. With an RBF kernel every has unit norm, and the one-class SVM coincides with support vector data description, which encloses the data in the smallest ball in feature space (Tax & Duin, 2004). The weak spot is tuning: the kernel width decides whether the region is one blob or a halo around each point, and without labeled anomalies there is no validation error to choose it by.
Out-of-distribution detection for deep networks
Out-of-distribution (OOD) detection asks the same question of a trained classifier. A network trained on classes still outputs a confident-looking prediction for an input from none of them, so a deployed system needs a score that is high on the training distribution and low elsewhere. With logits , common scores are:
- Maximum softmax probability (Hendrycks & Gimpel, 2017): . Correctly classified in-distribution inputs tend to score higher than misclassified or OOD ones.
- Energy (Liu, Wang, Owens & Li, 2020): with . Read as an energy-based model, the classifier implies , so at the score is up to a constant.
- Mahalanobis distance (Lee, Lee, Lee & Shin, 2018): fit class-conditional Gaussians with a shared covariance to a layer's features , and score .
- Outlier exposure (Hendrycks, Mazeika & Dietterich, 2019): train with an auxiliary set of outliers whose predictions are pushed toward the uniform distribution.
A generative model looks like the natural tool: fit to the training images and flag low . Nalisnick, Matsukawa, Teh, Gorur & Lakshminarayanan (2019) found that flows, VAEs and PixelCNNs trained on CIFAR-10 assign higher likelihood to SVHN house numbers than to CIFAR-10's own test images, with similar failures for other dataset pairs, and traced the gap to the data's location and variance and the model's curvature. One way to see the problem: in high dimension, typical samples lie far from where the density peaks.
Model the pixels of a 32×32 color image ( numbers) as a standard Gaussian. By how many nats does the log-density at the origin exceed the log-density of a typical sample?
Show the answer
1536 nats
, and for a typical sample, give or take . The gap is about 1,536 nats, a density ratio of . Yet samples lie about units from the origin and essentially never near it: the densest point is not a typical one.
Low-variance inputs, like SVHN's smooth digits, sit closer to the peak of a model fitted to more varied images and score higher, although no training image looks like them. Fixes compare likelihoods instead of thresholding them, for instance a ratio against a background model trained on perturbed inputs (Ren et al., 2019), or a test of whether a batch's likelihoods look typical. They help on some benchmarks and not on others.
Evaluating detectors, and what theory says
Metrics. OOD papers report the AUROC (the probability that a random anomaly outscores a random normal point), the area under the precision–recall curve with anomalies as the positive class, and the false-positive rate at 95% true-positive rate. AUROC does not depend on the base rate, and that is exactly how it misleads: when anomalies are 0.1% of traffic, even a small false-positive rate buries the true alarms.
Pitfalls. The OOD sets used for evaluation must not be used to tune the score, since real anomalies are unknown in advance. Near-OOD inputs (a new dog breed) are far harder than far-OOD ones (random noise). Training data are rarely clean. And a large benchmark study of unsupervised detectors found that how well each method does varies with the dataset and the parameter settings, and that the usual evaluation measures have biases of their own (Campos et al., 2016).
Calibrated thresholds. Hold out clean normal points with scores (higher means more anomalous), and give a new point the conformal p-value
If is exchangeable with the calibration points, for every : a finite-sample false-alarm guarantee for any score whatsoever. Bates, Candès, Lei, Romano & Sesia (2023) prove these p-values are positively dependent across test points, so the Benjamini–Hochberg procedure controls the false discovery rate, in a marginal sense. The Convergence lesson Conformal Prediction develops the method.
Key takeaways
- With no anomaly examples, a detector is a region holding of the normal data. Density level sets are the smallest such regions by volume, the most powerful tests against uniformly spread anomalies, and that reference measure ties the answer to the chosen representation.
- Neighbor-based scores (-NN distance, LOF) compare local density with that of the neighbors; isolation forests average the number of random splits needed to isolate a point, normalized by .
- The one-class SVM's bounds the fraction of training outliers from above and the fraction of support vectors from below; with it is a thresholded kernel density estimate.
- For deep classifiers, maximum softmax probability, energy and Mahalanobis scores flag inputs the network should not trust. Deep generative likelihoods can rank out-of-distribution data higher, because high density is not typicality.
- AUROC ignores base rates. Set thresholds by a false-alarm budget on normal data (conformal p-values make the guarantee exact) and report precision at the prevalence you expect in deployment.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why are density level sets the natural target of unsupervised anomaly detection?
- They maximize the likelihood of the anomalies
- Among all regions holding a fraction of the normal data, they have the smallest volume, so they catch the most anomalies spread uniformly
- They are unchanged by any change of coordinates
- They always equal the support of the normal distribution
Show the answer
B. Among all regions holding a fraction of the normal data, they have the smallest volume, so they catch the most anomalies spread uniformly
The minimum-volume property is the Neyman–Pearson lemma against a constant density. It is optimal only relative to that reference, which is why the choice of features matters.
A one-class SVM with is trained on 2,000 points, and its solution has . What do you know?
- Exactly 100 training points are outliers
- At least 100 points are outliers and at most 100 are support vectors
- 5% of future anomalies will be missed
- At most 100 training points are outliers and at least 100 are support vectors
Show the answer
D. At most 100 training points are outliers and at least 100 are support vectors
Each dual coefficient is at most and they sum to 1, so at least 100 are nonzero. Outliers sit at the upper bound , so there are at most 100 of them. Asymptotically both fractions approach .
How does an isolation forest score points without estimating a density?
- It measures each point's distance to its nearest neighbors
- It trains a classifier on labeled anomalies
- Random cuts isolate a point in sparse territory after few splits, so a short average path length marks a likely anomaly
- It fits a Gaussian in each leaf and thresholds the likelihood
Show the answer
C. Random cuts isolate a point in sparse territory after few splits, so a short average path length marks a likely anomaly
A random split lands between an isolated point and the rest of the data with high probability, so few splits suffice; a point inside a dense cluster needs many. The score turns the average path length into a number near 1 for anomalies.
A flow trained on CIFAR-10 assigns higher likelihood to SVHN test images than to CIFAR-10 test images. Which explanation fits?
- Likelihood rewards inputs near the model's high-density region, such as smoother, lower-variance images, whether or not they look like typical training images
- The flow memorized SVHN during training
- The change-of-variables formula does not apply to images
- SVHN images are a subset of CIFAR-10
Show the answer
A. Likelihood rewards inputs near the model's high-density region, such as smoother, lower-variance images, whether or not they look like typical training images
In high dimension, typical samples lie far from where the density peaks. Images with lower variance sit closer to the peak of a model fitted to more varied data and score higher, though no training image looks like them. High density is not typicality.
Further reading
- M. M. Breunig, H.-P. Kriegel, R. T. Ng & J. Sander, "LOF: identifying density-based local outliers," Proceedings of the 2000 ACM SIGMOD International Conference on Management of Data, 93–104 (2000).
- F. T. Liu, K. M. Ting & Z.-H. Zhou, "Isolation forest," Proceedings of the 8th IEEE International Conference on Data Mining, 413–422 (2008).
- B. Schölkopf, J. C. Platt, J. Shawe-Taylor, A. J. Smola & R. C. Williamson, "Estimating the support of a high-dimensional distribution," Neural Computation 13(7), 1443–1471 (2001).
- E. Nalisnick, A. Matsukawa, Y. W. Teh, D. Gorur & B. Lakshminarayanan, "Do deep generative models know what they don't know?," ICLR (2019).
- J. Yang, K. Zhou, Y. Li & Z. Liu, "Generalized out-of-distribution detection: a survey," International Journal of Computer Vision 132, 5635–5662 (2024).