Skip to content
BIASED

Anomaly detection

Supervised, novelty and outlier settings, density scores from a Gaussian or a mixture and why high density is not typicality, neighbour distances and the local outlier factor, the isolation forest, the one-class SVM and its ν-property, and how to evaluate a detector and set its threshold when anomalies are rare.

Three settings

The topic Dimensionality reduction ended with models that are densities. Probabilistic PCA and the Gaussian mixture of Mixtures and the EM algorithm say not only where the data lie but how probable each point is. A fraudulent payment, a failing sensor, a corrupted record or a network intrusion is usually a point that such a model finds improbable. Anomaly detection turns this into a method.

Every detector in this topic does the same two things. It gives each point xx an anomaly score s(x)s(x), higher for points that do not fit. Then it flags xx when s(x)>τs(x) > \tau for a threshold τ\tau. Where labels exist, y=1y = 1 marks a true anomaly and y=0y = 0 a normal point.

Anomalies are rare, varied and often new, so labelled examples of them are scarce. What can be learned depends on what is labelled.

  • Supervised. Both normal points and anomalies are labelled. This is classification with very unequal classes, handled with class weights and the metrics of Classification metrics. It finds the kinds of anomalies it was shown and can miss new kinds.
  • Novelty detection. The training set holds only normal points, known to be clean. The model describes them, and a new point is flagged if it does not fit the description. Most methods below are built for this setting.
  • Outlier detection. The training set is unlabelled and contaminated with a small share ϵ\epsilon of anomalies, the contamination. The task is to find them in the same data. The methods are the same, but they are fitted on the very anomalies they must find.

Most methods look for point anomalies, points unusual in themselves. A contextual anomaly is unusual only in a context: −10 ∘-10\,^\circC is normal in January and alarming in July. Adding the context as a feature, or modelling the distribution given the context, reduces it to a point anomaly.

Like a cluster, "does not fit" has no single definition. Each family of scores below picks one: low density, far from the neighbours, quick to isolate, outside a learned boundary.

Density scores

The most direct definition: an anomaly is a point of low probability under a model of the normal data. Fit a density p^\hat p by maximum likelihood and take the score

s(x)=−log⁡p^(x).s(x) = -\log \hat p(x).

One Gaussian. For p^=N(μ^,Σ^)\hat p = \mathcal N(\hat\mu, \hat\Sigma), the score is, up to constants and a factor 12\tfrac12, the squared Mahalanobis distance from The multivariate Gaussian:

Δ2(x)=(x−μ^)⊤Σ^−1(x−μ^).\Delta^2(x) = (x - \hat\mu)^\top \hat\Sigma^{-1} (x - \hat\mu).

It measures each direction by the spread in that direction, so changing the units of a feature does not change it. That topic also gives the threshold. If the normal data are Gaussian with the true mean and covariance, Δ2\Delta^2 follows the chi-squared law with dd degrees of freedom. In the plane, d=2d = 2, its tail has a closed form:

P(Δ2>t)=e−t/2.P(\Delta^2 > t) = e^{-t/2}.

So the threshold for any target share of false alarms comes from one logarithm. Without the Gaussian assumption, Chebyshev's inequality from Inequalities and concentration still bounds the share beyond kk standard deviations by 1/k21/k^2, a far more cautious threshold.

With estimated μ^\hat\mu and Σ^\hat\Sigma, the chi-squared law is only an approximation, good when nn is large compared with dd. Take n=30n = 30 Gaussian points in the plane and the 1% threshold. In simulation it flags about 0.45% of the 30 fitted points and 2.4% of new normal points: the estimates fit their own sample too well.

The estimates are also pulled by the anomalies they should catch. A few far points inflate Σ^\hat\Sigma and hide each other; this is masking. Robust estimates, such as the minimum covariance determinant (Rousseeuw and Van Driessen, 1999), fit the covariance to the most concentrated part of the data. They assume one cluster of normal points.

A mixture. Normal data with several modes need a Gaussian mixture, with s(x)=−log⁡∑kπkN(x∣μk,Σk)s(x) = -\log \sum_k \pi_k \mathcal N(x \mid \mu_k, \Sigma_k) where kk runs over the components. Probabilistic PCA is another density. For PCA, the reconstruction error ∥x−WW⊤x∥2\lVert x - WW^\top x \rVert^2, the squared distance from the principal subspace, is a common score in its own right, and so is the reconstruction error of an autoencoder.

Density is not typicality

Density scores have two weaknesses. The first: a density needs many points per dimension, so nonparametric estimates only work in a few dimensions.

The second is subtler. In high dimension, high density is not typicality. Take a standard Gaussian in d=100d = 100 dimensions. Its density peaks at the origin, where Δ2=0\Delta^2 = 0. But Δ2\Delta^2 of a sample follows the chi-squared law with 100 degrees of freedom: mean 100, standard deviation 200≈14.1\sqrt{200} \approx 14.1. In 99% of samples Δ2\Delta^2 lies between 67 and 140, and Δ2<50\Delta^2 < 50 happens about 7 times in a million. The samples live in a thin shell at radius about 10, far from the peak.

A density score ranks a point at the origin as the most normal point there could be. Yet no real sample ever lands there. The point is unusual for its very lack of unusualness.

Deep generative models show the same effect on images. Models trained on CIFAR-10 photos give higher likelihood to SVHN house numbers than to CIFAR-10 test images (Nalisnick et al., 2019). The Generative Models course returns to this likelihood paradox with flows and energy-based models.

Neighbours and the local outlier factor

A definition without a density: an anomaly is far from the other points. Let dk(x)d_k(x) be the distance from xx to its kk-th nearest training point. The kk-NN score is s(x)=dk(x)s(x) = d_k(x) (Ramaswamy, Rastogi and Shim, 2000). It needs no model, works with any distance and follows clusters of any shape. It inherits the weaknesses of Nearest neighbours: the cost of the search, the dependence on scaling, and distances that look alike in high dimension.

It also uses one global scale. Next to a dense cluster, a point at distance 1 is clearly odd; inside a sparse cluster, distance 1 is ordinary. One threshold on dkd_k either misses the first or flags the edge of the second.

The local outlier factor (LOF) of Breunig et al. (2000) compares a point's density with its neighbours' densities. Let Nk(x)N_k(x) be the kk nearest neighbours of xx. The reachability distance of xx from a neighbour oo is max⁡(dk(o),∥x−o∥)\max\big(d_k(o), \lVert x - o \rVert\big): the true distance, but never less than oo's own kk-distance, which smooths the statistics for points very close to oo. The local reachability density is the inverse of its average:

lrd⁡(x)=(1k∑o∈Nk(x)max⁡(dk(o),∥x−o∥))−1.\operatorname{lrd}(x) = \Big( \frac1k \sum_{o \in N_k(x)} \max\big(d_k(o), \lVert x - o \rVert\big) \Big)^{-1}.

The LOF is the average ratio of the neighbours' density to the point's own:

LOF⁡(x)=1k∑o∈Nk(x)lrd⁡(o)lrd⁡(x).\operatorname{LOF}(x) = \frac1k \sum_{o \in N_k(x)} \frac{\operatorname{lrd}(o)}{\operatorname{lrd}(x)}.

Deep inside a cluster, dense or sparse, a point is as dense as its neighbours, and LOF⁡≈1\operatorname{LOF} \approx 1. A point in a sparse spot next to a dense cluster has neighbours much denser than itself, so its LOF is large even when its distances are small.

A worked case on a line, with k=1k = 1 and the points 0,1,2,10,110, 1, 2, 10, 11. Every point has its nearest neighbour at distance 1, so every reachability distance, every density and every LOF equals 1. Two separate groups of equal density contain no local outlier. Now add the point 55. Its nearest neighbour is 22, at distance 3. So lrd⁡(5)=1/max⁡(1,3)=1/3\operatorname{lrd}(5) = 1/\max(1, 3) = 1/3, while lrd⁡(2)=1\operatorname{lrd}(2) = 1, and LOF⁡(5)=3\operatorname{LOF}(5) = 3.

Isolation forest

The scores so far model the normal data and measure how far a point is from it. The isolation forest (Liu, Ting and Zhou, 2008) measures how easy a point is to cut off. Split the data at random: pick a feature at random and a threshold uniformly between the minimum and maximum of the current points in that feature. Repeat in each part until every point is alone. An anomaly, few and different, is usually cut off after a few splits; a point in a dense region needs many.

The number of splits from the root to a point's leaf is its path length h(x)h(x). It is averaged over many random trees, as in Bagging and random forests. Trees on more points are deeper, so the path length needs a reference scale. The average path length of a point in a random tree on nn points is

c(n)=2H(n−1)−2(n−1)n,H(i)=1+12+⋯+1i.c(n) = 2H(n - 1) - \frac{2(n - 1)}{n}, \qquad H(i) = 1 + \frac12 + \dots + \frac1i.

The anomaly score divides the average path length by it:

s(x)=2−E[h(x)]/c(n).s(x) = 2^{-\mathbb E[h(x)] / c(n)}.

It equals 0.50.5 when the path is of average length, tends to 1 as the path shrinks to zero and to 0 as the path grows. For n=256n = 256, c(256)=10.249c(256) = 10.249. A point isolated after 3 splits on average scores 2−3/10.249=0.8162^{-3/10.249} = 0.816; one that needs 15 splits scores 0.3630.363. These are readings of an isolation score, not probabilities of being an anomaly: a threshold on ss still needs calibration.

Three design choices make the method fast and robust.

  • Subsamples. Each of t=100t = 100 trees grows on ψ=256\psi = 256 points drawn without replacement. Fewer normal points crowd around the anomalies, and fewer anomalies shield each other.
  • A height limit of ⌈log⁡2ψ⌉=8\lceil \log_2 \psi \rceil = 8, the average depth, since only short paths matter. A point that stops at a leaf still holding mm points gets its depth plus c(m)c(m).
  • Comparisons only. Training costs O(tψlog⁡ψ)O(t \psi \log \psi) and scoring O(tlog⁡ψ)O(t \log \psi) per point, whatever nn is. No distances are computed.

Its weakness is the axis-parallel cuts. An anomaly that differs from the data only along a diagonal, or sits in a hole surrounded by normal points, takes many such cuts to isolate.

One-class SVM

The one-class SVM (Schölkopf et al., 2001) learns a boundary around the normal data. In the feature space φ\varphi of a kernel it separates the mapped points from the origin with the widest margin, and lets a share of them fall on the wrong side:

min⁡w, ξ, ρ 12∥w∥2+1νn∑i=1nξi−ρs.t.w⊤φ(xi)≥ρ−ξi,  ξi≥0.\min_{w,\, \xi,\, \rho}\ \frac12 \lVert w \rVert^2 + \frac{1}{\nu n} \sum_{i=1}^n \xi_i - \rho \quad \text{s.t.} \quad w^\top \varphi(x_i) \ge \rho - \xi_i,\ \ \xi_i \ge 0.

The decision function is f(x)=w⊤φ(x)−ρf(x) = w^\top \varphi(x) - \rho, negative outside the boundary. As in Support vector machines, the dual sees the data only through the kernel:

f(x)=∑i=1nαiK(xi,x)−ρ,0≤αi≤1νn,∑i=1nαi=1.f(x) = \sum_{i=1}^n \alpha_i K(x_i, x) - \rho, \qquad 0 \le \alpha_i \le \frac{1}{\nu n}, \quad \sum_{i=1}^n \alpha_i = 1.

With the RBF kernel of Kernels, ff is a weighted sum of bumps around the support vectors minus a threshold. For ν=1\nu = 1 all αi=1/n\alpha_i = 1/n, and ff becomes a kernel density estimate cut at a level.

The parameter ν∈(0,1]\nu \in (0, 1] has a direct meaning, the ν-property. It is an upper bound on the share of training points outside the boundary and a lower bound on the share of support vectors. On the data of the next block, with ν=0.2\nu = 0.2, 18.7% of the training points fall outside and 21.4% are support vectors.

So ν\nu is a setting of the optimization, not the true share of anomalies. It sets how many training points the boundary leaves out, whatever they are. Choosing ν=ϵ\nu = \epsilon is reasonable when the contamination is known, but it is a choice. The kernel width and ν\nu must be chosen without labels, the cost grows faster than linearly in nn, and the features must be scaled.

Evaluating detectors

Training may use no labels, but evaluation needs some: a set of points with known status, often a few hundred normal points and a few dozen anomalies from past incidents. Three things make it unlike ordinary classification.

Accuracy is meaningless. With 1% anomalies, flagging nothing is 99% accurate. Detectors are compared by how they rank the points, since the threshold comes later. Two summaries from Classification metrics do this: the ROC-AUC, the probability that a random anomaly scores above a random normal point, and the average precision (AP), the area under the precision–recall curve.

ROC-AUC flatters rare positives. The false-positive rate divides by the huge number of normal points. So a detector can have a small false-positive rate and still bury its true alarms among false ones. Precision shows it, by Bayes' formula from Conditional probability and Bayes' formula. With 1% anomalies, a detector that finds 90% of them at a false-positive rate of 1% has precision

0.9⋅0.010.9⋅0.01+0.01⋅0.99=0.476.\frac{0.9 \cdot 0.01}{0.9 \cdot 0.01 + 0.01 \cdot 0.99} = 0.476.

Half of its alarms are false.

Here is a test bed: a dense cluster of 300 points, a sparse one of 200, and 13 anomalies spread uniformly over the plane, 2.5% of 513 points. Each detector is fitted on all the points, as in outlier detection, and the labels are used only to score it.

Detector ROC-AUC AP
Gaussian, Mahalanobis 0.886 0.512
Robust Gaussian (MCD) 0.738 0.145
Mixture, 2 components 0.911 0.644
10-NN distance 0.915 0.693
LOF, k=10k = 10 0.871 0.515
Isolation forest 0.915 0.636
One-class SVM, ν=0.05\nu = 0.05 0.893 0.516

The ROC-AUC values range from 0.74 to 0.92 and look alike. The AP values range from 0.15 to 0.69 and separate the detectors far more. The robust Gaussian fails as warned: it fits the dense cluster only and flags the whole sparse one. On these uniform anomalies LOF is no better than the plain Gaussian; its strength is local anomalies, which this test bed barely has. No table ranks detectors in general.

Few labels, wide error bars. With 13 anomalies, recall moves in steps of 1/13≈7.7%1/13 \approx 7.7\%. A bootstrap over the 513 points, as in Confidence intervals and the bootstrap, gives the Gaussian's AP a 95% interval of about [0.24,0.77][0.24, 0.77] and the isolation forest's about [0.36,0.86][0.36, 0.86]. One or two detections more is noise.

Thresholds and what comes next

The score ranks; the threshold decides how many points become alarms. Three common ways to set it:

  • From the contamination. In outlier detection, flag the top share ϵ\epsilon of the training scores. The contamination parameter of scikit-learn's detectors does this; it needs a guess of ϵ\epsilon.
  • From a false-alarm rate. In novelty detection, score clean validation data and put τ\tau at its 1−α1 - \alpha quantile. Then about a share α\alpha of future normal points will be flagged. For an isolation forest on the two clusters, the 99% quantile of 10,000 clean validation scores flags 0.87% of 20,000 fresh normal points, against the target 1%.
  • From costs or capacity. If an analyst can review 50 alerts a day, the threshold is the score of the 50th point of the day. The cost rule of Classification metrics needs a calibrated probability of being an anomaly, and none of these scores is one. Either calibrate the score on labelled data first, or search thresholds on such data for the lowest total cost.

What changed in this topic: each family gave its own meaning to "does not fit". A density calls a point improbable, a kk-NN distance calls it far, LOF calls it sparser than its neighbours, an isolation forest calls it quick to cut off, and a one-class SVM puts it outside a boundary. The limits are shared. No definition covers every anomaly. In high dimension densities cannot be estimated and distances concentrate, so scores are usually computed on a few principal components or learned representations. A score is a number, not a reason an analyst can check. And new kinds of anomalies appear after deployment, so a detector needs monitoring.

This topic closes the module Learning without labels, and one more look at its output points to the next module. An analyst reads the alerts from the top, and what matters is that true anomalies come first, not the value of the score. That is a ranking, here built without labels. The next topic, Learning to rank, supervises it: search engines and catalogues learn to order items from relevance labels, with metrics and losses built for the top of the list.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.