Simple Algorithm
Machine Learning · Convergence · 26 min

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 c(ψ)c(\psi) and the score 2−E[h(x)]/c(ψ)2^{-\E[h(\mathbf x)]/c(\psi)}.
  • State the one-class SVM in primal and dual form, and prove its ν\nu-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 X1,…,Xn\mathbf X_1,\dots,\mathbf X_n are drawn i.i.d. from PP with density pp on Rd\R^d. 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 AA declared normal, with false-alarm rate α=P(X∉A)\alpha=P(\mathbf X\notin A). With no anomalies to learn from, which AA 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 α\alpha is the one whose normal region has the smallest volume.

DerivationProof
  1. P(A∖Lτ) ≥ P(Lτ∖A)P(A\setminus L_\tau)\ \ge\ P(L_\tau\setminus A)

    Let P(A)≥1−α=P(Lτ)P(A)\ge1-\alpha=P(L_\tau). Removing the common part A∩LτA\cap L_\tau from both sides leaves

  2. τ λ(A∖Lτ) ≥ P(A∖Lτ) ≥ P(Lτ∖A) ≥ τ λ(Lτ∖A)\tau\,\lambda(A\setminus L_\tau)\ \ge\ P(A\setminus L_\tau)\ \ge\ P(L_\tau\setminus A)\ \ge\ \tau\,\lambda(L_\tau\setminus A)

    Outside LτL_\tau the density is below τ\tau, and inside it is at least τ\tau:

  3. λ(A) ≥ λ(Lτ)\lambda(A)\ \ge\ \lambda(L_\tau)

    Divide by τ\tau and add λ(A∩Lτ)\lambda(A\cap L_\tau) to both sides.

The "right" detector therefore depends on a reference measure: volume in the coordinates you chose. Under a smooth bijection y=g(x)\mathbf y=g(\mathbf x) the density becomes p(g−1(y))∣det⁡Jg−1(y)∣p\big(g^{-1}(\mathbf y)\big)\abs{\det J_{g^{-1}}(\mathbf y)}, so the level sets, and the ranking of points by rarity, change unless gg preserves volume. Every density-based detector makes this choice implicitly, through its features. In practice the level set is estimated by thresholding an estimate, L^={p^≥τ^}\hat L=\{\hat p\ge\hat\tau\}, with τ^\hat\tau set at the α\alpha-quantile of p^\hat p on held-out normal data; in high dimension, methods that estimate a score monotone in pp directly often work better than estimating pp itself.

Check your understanding

You flag incomes whose estimated density is in the lowest 1%. A colleague first takes y=log⁡xy=\log x and flags the lowest 1% of the density of yy. Do you flag the same people?

  1. Yes: a monotone transform keeps the data in the same order, so the flagged set is the same
  2. Yes, because both thresholds are set at the 1% quantile
  3. No: the log-space density is pY(log⁡x)=x pX(x)p_Y(\log x)=x\,p_X(x), so low incomes look rarer and high incomes less rare
  4. No, because the log transform changes the number of data points
Show the answer

C. No: the log-space density is pY(log⁡x)=x pX(x)p_Y(\log x)=x\,p_X(x), so low incomes look rarer and high incomes less rare

By the change-of-variables formula, pY(y)=pX(ey) eyp_Y(y)=p_X(e^y)\,e^y, 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 pp. The simplest score is the distance to the kk-th nearest neighbor, which is small where the data are dense: a kk-nearest-neighbor density estimate divides k/nk/n 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 Nk(x)N_k(\mathbf x) the kk nearest neighbors and dk(o)d_k(\mathbf o) the distance from o\mathbf o to its own kk-th neighbor, define the reachability distance max⁡{dk(o),∥x−o∥}\max\{d_k(\mathbf o),\norm{\mathbf x-\mathbf o}\}, the local reachability density lrd(x)\mathrm{lrd}(\mathbf x) as the reciprocal of the mean reachability distance from x\mathbf x to its neighbors, and

LOFk(x)=1∣Nk(x)∣∑o∈Nk(x)lrd(o)lrd(x).\mathrm{LOF}_k(\mathbf x)=\frac1{\abs{N_k(\mathbf x)}}\sum_{\mathbf o\in N_k(\mathbf x)}\frac{\mathrm{lrd}(\mathbf o)}{\mathrm{lrd}(\mathbf x)}.

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 ψ\psi 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 log⁡2ψ\log_2\psi is reached. The path length h(x)h(\mathbf x) counts the splits needed to isolate x\mathbf x, with a correction for subtrees cut off by the depth limit. Averaging over tt trees and normalizing gives the score

s(x,ψ)=2−E[h(x)]/c(ψ),c(n)=2H(n−1)−2(n−1)n,s(\mathbf x,\psi)=2^{-\E[h(\mathbf x)]/c(\psi)},\qquad c(n)=2H(n-1)-\frac{2(n-1)}n,

where H(i)≈ln⁡i+0.5772H(i)\approx\ln i+0.5772 is the harmonic number and c(n)c(n) is the average path length of an unsuccessful search in a binary search tree with nn keys. A point with E[h]=c(ψ)\E[h]=c(\psi) scores exactly 0.5, and scores near 1 flag anomalies. The defaults ψ=256\psi=256 and t=100t=100 work across many data sets, training takes O(t ψlog⁡ψ)O(t\,\psi\log\psi) 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).

Predict before you look

Isolation trees are grown on subsamples of ψ=256\psi=256 points, so c(256)≈10.24c(256)\approx10.24. A point is isolated after 4 splits on average. What is its score s=2−E[h(x)]/c(ψ)s=2^{-\E[h(\mathbf x)]/c(\psi)}?

Show the answer

0.76

4/10.24≈0.394/10.24\approx0.39 and 2−0.39≈0.762^{-0.39}\approx0.76: a likely anomaly. A point needing 15 splits scores 2−15/10.24≈0.362^{-15/10.24}\approx0.36, comfortably normal. The normalization by c(ψ)c(\psi) makes scores comparable across subsample sizes, since typical path lengths grow like log⁡ψ\log\psi.

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 k(x,z)=⟨φ(x),φ(z)⟩k(\mathbf x,\mathbf z)=\langle\varphi(\mathbf x),\varphi(\mathbf z)\rangle and separates them from the origin with maximum margin, allowing a few violations:

min⁡w,ξ,ρ 12∥w∥2+1νn∑i=1nξi−ρs.t.⟨w,φ(xi)⟩≥ρ−ξi,  ξi≥0.\min_{\mathbf w,\boldsymbol\xi,\rho}\ \tfrac12\norm{\mathbf w}^2+\frac1{\nu n}\sum_{i=1}^n\xi_i-\rho\quad\text{s.t.}\quad\langle\mathbf w,\varphi(\mathbf x_i)\rangle\ge\rho-\xi_i,\ \ \xi_i\ge0.

The decision function is f(x)=sign⁡(∑iαik(xi,x)−ρ)f(\mathbf x)=\sign\big(\sum_i\alpha_ik(\mathbf x_i,\mathbf x)-\rho\big), with dual coefficients solving

min⁡α 12∑i,jαiαjk(xi,xj)s.t.0≤αi≤1νn,  ∑iαi=1.\min_{\boldsymbol\alpha}\ \tfrac12\sum_{i,j}\alpha_i\alpha_jk(\mathbf x_i,\mathbf x_j)\quad\text{s.t.}\quad0\le\alpha_i\le\frac1{\nu n},\ \ \sum_i\alpha_i=1.

Points with αi>0\alpha_i>0 are the support vectors; points with ξi>0\xi_i>0 fall outside the estimated region and are the training outliers.

DerivationProof of the two bounds
  1. 1=∑iαi≤#{i:αi>0}⋅1νn⟹#{support vectors}n≥ν1=\sum_i\alpha_i\le\#\{i:\alpha_i>0\}\cdot\frac1{\nu n}\quad\Longrightarrow\quad\frac{\#\{\text{support vectors}\}}n\ge\nu

    Stationarity of the Lagrangian in ρ\rho gives ∑iαi=1\sum_i\alpha_i=1, and every αi≤1/(νn)\alpha_i\le1/(\nu n). So at least νn\nu n coefficients are nonzero:

  2. #{i:ξi>0}⋅1νn≤∑iαi=1⟹#{outliers}n≤ν\#\{i:\xi_i>0\}\cdot\frac1{\nu n}\le\sum_i\alpha_i=1\quad\Longrightarrow\quad\frac{\#\{\text{outliers}\}}n\le\nu

    Stationarity in ξi\xi_i gives αi=1νn−βi\alpha_i=\frac1{\nu n}-\beta_i, where βi≥0\beta_i\ge0 is the multiplier of ξi≥0\xi_i\ge0. By complementary slackness (KKT), ξi>0\xi_i>0 forces βi=0\beta_i=0, so every outlier sits at the upper bound and uses up its share of the budget:

So ν\nu is a direct handle on the training false-alarm rate. At ν=1\nu=1 the box constraint forces every αi=1/n\alpha_i=1/n, and the decision rule becomes 1n∑ik(xi,x)≥ρ\frac1n\sum_ik(\mathbf x_i,\mathbf x)\ge\rho: with a Gaussian RBF kernel this is, up to a constant factor, a thresholded kernel density estimate. Smaller ν\nu makes the expansion sparse. With an RBF kernel every φ(x)\varphi(\mathbf x) 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 KK classes still outputs a confident-looking prediction for an input from none of them, so a deployed system needs a score S(x)S(\mathbf x) that is high on the training distribution and low elsewhere. With logits f1(x),…,fK(x)f_1(\mathbf x),\dots,f_K(\mathbf x), common scores are:

  • Maximum softmax probability (Hendrycks & Gimpel, 2017): S=max⁡ksoftmax⁡(f)kS=\max_k\softmax(\mathbf f)_k. Correctly classified in-distribution inputs tend to score higher than misclassified or OOD ones.
  • Energy (Liu, Wang, Owens & Li, 2020): S=−E(x)S=-E(\mathbf x) with E(x)=−Tlog⁡∑kefk(x)/TE(\mathbf x)=-T\log\sum_ke^{f_k(\mathbf x)/T}. Read as an energy-based model, the classifier implies p(x)∝∑kefk(x)p(\mathbf x)\propto\sum_ke^{f_k(\mathbf x)}, so at T=1T=1 the score is log⁡p(x)\log p(\mathbf x) up to a constant.
  • Mahalanobis distance (Lee, Lee, Lee & Shin, 2018): fit class-conditional Gaussians with a shared covariance to a layer's features z\mathbf z, and score S=−min⁡k(z−μ^k)⊤Σ^−1(z−μ^k)S=-\min_k(\mathbf z-\hat{\boldsymbol\mu}_k)^\top\hat\Sigma^{-1}(\mathbf z-\hat{\boldsymbol\mu}_k).
  • Outlier exposure (Hendrycks, Mazeika & Dietterich, 2019): train with an auxiliary set of outliers whose predictions are pushed toward the uniform distribution.
log⁡max⁡ksoftmax⁡ ⁣(f(x)/T)k=max⁡kfk(x)T+E(x)T\log\max_k\softmax\!\big(\mathbf f(\mathbf x)/T\big)_k=\frac{\max_kf_k(\mathbf x)}T+\frac{E(\mathbf x)}T
The maximum softmax probability is the energy shifted by the largest logit, so it is not a monotone function of the implied density. Liu et al. found that the energy alone separates in- from out-of-distribution data better.

A generative model looks like the natural tool: fit pθp_\theta to the training images and flag low pθ(x)p_\theta(\mathbf x). 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.

Predict before you look

Model the pixels of a 32×32 color image (d=3,072d=3{,}072 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

log⁡p(0)−log⁡p(x)=∥x∥2/2\log p(\mathbf 0)-\log p(\mathbf x)=\norm{\mathbf x}^2/2, and ∥x∥2≈d=3,072\norm{\mathbf x}^2\approx d=3{,}072 for a typical sample, give or take 2d≈78\sqrt{2d}\approx78. The gap is about 1,536 nats, a density ratio of e1536e^{1536}. Yet samples lie about 3072≈55\sqrt{3072}\approx55 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 mm clean normal points with scores s1,…,sms_1,\dots,s_m (higher means more anomalous), and give a new point the conformal p-value

p^(x)=1+#{j:sj≥s(x)}m+1.\hat p(\mathbf x)=\frac{1+\#\{j:s_j\ge s(\mathbf x)\}}{m+1}.

If x\mathbf x is exchangeable with the calibration points, P(p^(x)≤α)≤αP\big(\hat p(\mathbf x)\le\alpha\big)\le\alpha for every α\alpha: 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 1−α1-\alpha 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 (kk-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 c(ψ)c(\psi).
  • The one-class SVM's ν\nu bounds the fraction of training outliers from above and the fraction of support vectors from below; with ν=1\nu=1 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.

Question 1

Why are density level sets {x:p(x)≥τ}\{\mathbf x:p(\mathbf x)\ge\tau\} the natural target of unsupervised anomaly detection?

  1. They maximize the likelihood of the anomalies
  2. Among all regions holding a fraction 1−α1-\alpha of the normal data, they have the smallest volume, so they catch the most anomalies spread uniformly
  3. They are unchanged by any change of coordinates
  4. They always equal the support of the normal distribution
Show the answer

B. Among all regions holding a fraction 1−α1-\alpha 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.

Question 2

A one-class SVM with ν=0.05\nu=0.05 is trained on 2,000 points, and its solution has ρ≠0\rho\ne0. What do you know?

  1. Exactly 100 training points are outliers
  2. At least 100 points are outliers and at most 100 are support vectors
  3. 5% of future anomalies will be missed
  4. 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 1/(νn)=1/1001/(\nu n)=1/100 and they sum to 1, so at least 100 are nonzero. Outliers sit at the upper bound 1/1001/100, so there are at most 100 of them. Asymptotically both fractions approach ν\nu.

Question 3

How does an isolation forest score points without estimating a density?

  1. It measures each point's distance to its kk nearest neighbors
  2. It trains a classifier on labeled anomalies
  3. Random cuts isolate a point in sparse territory after few splits, so a short average path length marks a likely anomaly
  4. 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 2−E[h]/c(ψ)2^{-\E[h]/c(\psi)} turns the average path length into a number near 1 for anomalies.

Question 4

A flow trained on CIFAR-10 assigns higher likelihood to SVHN test images than to CIFAR-10 test images. Which explanation fits?

  1. 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
  2. The flow memorized SVHN during training
  3. The change-of-variables formula does not apply to images
  4. 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).