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 an anomaly score , higher for points that do not fit. Then it flags when for a threshold . Where labels exist, marks a true anomaly and 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 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: C 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 by maximum likelihood and take the score
One Gaussian. For , the score is, up to constants and a factor , the squared Mahalanobis distance from The multivariate Gaussian:
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, follows the chi-squared law with degrees of freedom. In the plane, , its tail has a closed form:
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 standard deviations by , a far more cautious threshold.
With estimated and , the chi-squared law is only an approximation, good when is large compared with . Take 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 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 where runs over the components. Probabilistic PCA is another density. For PCA, the reconstruction error , 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 dimensions. Its density peaks at the origin, where . But of a sample follows the chi-squared law with 100 degrees of freedom: mean 100, standard deviation . In 99% of samples lies between 67 and 140, and 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 be the distance from to its -th nearest training point. The -NN score is (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 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 be the nearest neighbours of . The reachability distance of from a neighbour is : the true distance, but never less than 's own -distance, which smooths the statistics for points very close to . The local reachability density is the inverse of its average:
The LOF is the average ratio of the neighbours' density to the point's own:
Deep inside a cluster, dense or sparse, a point is as dense as its neighbours, and . 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 and the points . 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 . Its nearest neighbour is , at distance 3. So , while , and .
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 . 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 points is
The anomaly score divides the average path length by it:
It equals when the path is of average length, tends to 1 as the path shrinks to zero and to 0 as the path grows. For , . A point isolated after 3 splits on average scores ; one that needs 15 splits scores . These are readings of an isolation score, not probabilities of being an anomaly: a threshold on still needs calibration.
Three design choices make the method fast and robust.
- Subsamples. Each of trees grows on points drawn without replacement. Fewer normal points crowd around the anomalies, and fewer anomalies shield each other.
- A height limit of , the average depth, since only short paths matter. A point that stops at a leaf still holding points gets its depth plus .
- Comparisons only. Training costs and scoring per point, whatever 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 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:
The decision function is , negative outside the boundary. As in Support vector machines, the dual sees the data only through the kernel:
With the RBF kernel of Kernels, is a weighted sum of bumps around the support vectors minus a threshold. For all , and becomes a kernel density estimate cut at a level.
The parameter 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 , 18.7% of the training points fall outside and 21.4% are support vectors.
So 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 is reasonable when the contamination is known, but it is a choice. The kernel width and must be chosen without labels, the cost grows faster than linearly in , 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
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, | 0.871 | 0.515 |
| Isolation forest | 0.915 | 0.636 |
| One-class SVM, | 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 . A bootstrap over the 513 points, as in Confidence intervals and the bootstrap, gives the Gaussian's AP a 95% interval of about and the isolation forest's about . 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 of the training scores. The
contaminationparameter of scikit-learn's detectors does this; it needs a guess of . - From a false-alarm rate. In novelty detection, score clean validation data and put at its quantile. Then about a share 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 -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.
Answers are saved on the server and tied to this browser until you sign in.