A sensor on a pump reports its temperature every second. For months the readings wander between and degrees. Then one reads . Nobody ever recorded a failure that looked like this, so there is no “failure” label to train on. Yet the reading is a sensor reading that does not resemble any normal reading, and that alone is a reason to look.
Anomaly detection is the task of learning what usual looks like and flagging what does not fit. This lesson builds it from small pieces: a score for each example, a threshold that turns scores into alarms, and four ways to compute a score. Then it asks how to tell whether a detector is any good when the examples you care about are rare.
What counts as an anomaly
The words overlap, so fix them first.
- An outlier is a value far from the rest of the data, a statement about the numbers (P1.D2). A broken sensor that reports is an outlier.
- An anomaly is an example that does not fit the process that made the rest, a statement about the world. A fraudulent payment is an anomaly, and it may or may not be an outlier in the numbers.
- Outlier detection looks for such points in the training data itself, which may be polluted with them. Novelty detection assumes the training data is clean, and judges new examples as they arrive. The same algorithms are used for both, and scikit-learn names the two settings in its user guide.
P1.D2 asked what to do with an outlier, and said that for a real but rare event, such as a fraud transaction or a rare disease, deleting it deletes what you wanted to find. This lesson is where that sentence pays off: here the odd rows are the product, not the noise.
Anomalies come in three kinds.
- A point anomaly is unusual on its own, such as the degrees.
- A contextual anomaly is unusual only in its context: degrees is normal in July and strange in January. The context (time, place, user) has to be a feature, or the detector cannot see it.
- A collective anomaly is a group that is odd together even though each member is ordinary: a heartbeat trace that is flat for ten seconds, each value normal. Methods on single rows miss it unless the features describe the window.
How you detect depends on what labels exist.
- Unsupervised: no labels. Learn the shape of the data, flag the points at its edge. This lesson’s main setting.
- Semi-supervised: you have data believed to be normal. Train on that alone, then score new examples. This is novelty detection.
- Supervised: you have labelled anomalies and an ordinary classifier (P3.A9). Use it when there are enough, but a rare class brings the problems of P3.A10 (class imbalance), and a classifier only finds the kinds of anomaly it saw before.
Scores, thresholds and the alarm rate
Every method below produces a score for each example: a number that is larger when the example is more unusual. (Some libraries flip the sign, so check which way is which.) A score alone does not raise an alarm. A threshold does: flag the examples with a score at or above it.
The threshold decides how many alarms there are. A high threshold gives few alarms, most of them real, but misses subtler anomalies. A low threshold catches more, and also flags many normal points. Choosing it is a decision about cost (what does a missed fraud cost, and what does a false alarm cost the analyst who has to check it), not a fact the algorithm can find out.
In scikit-learn this decision is made with the contamination setting, and it is easy to misread. In IsolationForest, LocalOutlierFactor and EllipticEnvelope, a number such as contamination=0.05 means: when fitting, set the threshold at the score that of the training points exceed. It is a way of choosing a threshold from a share, which is also how the widget below works. It is not an estimate of the share of anomalies, and it does not tell the model how many to look for. If the real share is , a setting of flags five times as many points as there are anomalies; if the real share is , at least half of them are missed. On new data the fixed threshold flags whatever share exceeds it, which can be quite different from .
Defaults differ between the estimators. For IsolationForest and LocalOutlierFactor the default is contamination="auto", which does not use a share: IsolationForest flags scores above (the neutral value of the paper’s score), and LocalOutlierFactor flags a factor above about . EllipticEnvelope defaults to . OneClassSVM has no contamination setting, but its nu plays a similar role: for large samples it is roughly an upper bound on the share of training points outside the boundary.
One feature: z-scores and fences
For a single feature the scores are old friends from P1.D2. Take the seven readings . The -score of is , and the rule flags . It does not fire: one extreme value inflates and shifts , which shrinks its own (masking), and for no can exceed . The IQR rule uses the quartiles: the fences are and , and lies far beyond the upper one. The quartiles hardly notice a single bad value, so the IQR rule is the safer score for small samples.
Two words for the same trouble in several dimensions. Masking is when anomalies hide each other (or themselves) by distorting the statistics: three similar anomalies look like a small cluster, and a method that counts neighbors sees company. Swamping is the reverse: anomalies pull the model so that normal points near them look unusual. A method that is fitted on data containing anomalies can suffer from both, which is why a robust fit or a small random sample (isolation forests, below) helps.
Real data has several features, and one feature at a time misses points that are ordinary in each coordinate but odd in combination. The next sections score the whole point at once.
Several features: the Gaussian and the Mahalanobis distance
The simplest model of “usual” is a single Gaussian: fit a mean and a covariance matrix to the data (P1.D7), and call a point unusual when its density is low. The density depends on the point only through the squared Mahalanobis distance,
so itself is the score: a large means a low density. It counts distance in units of the cloud’s own spread and tilt.
Here is the example of P1.D7. A machine has two sensors, with and (made up)
Four readings:
- lies along the cloud’s long direction: , . Common.
- lies across it: , . The same ordinary distance from the center, but rarer.
- : , , even though it is from the origin.
- : , , with an ordinary distance of only . It is far less ordinary than although it is closer to the origin, because it lies across the cloud.
How big is too big? If the data really are Gaussian with two features, then follows a known distribution whose upper tail is simply (this exact form holds for two features only). So a cut-off at flags the outer , is exceeded by about of normal readings and stays unflagged, and , exceeded by only , is flagged. The first cell below checks these numbers.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The cell prints (the largest possible is ), the fences and with flagged, and the four distances above.
A single Gaussian has two weak spots. It is one ellipse: if the normal data form two clouds, the mean falls in the gap between them, and an anomaly sitting in the gap looks perfectly central. The widget below plants exactly such points. And the mean and covariance are computed from data that include the anomalies, which stretch the ellipse (swamping and masking again). EllipticEnvelope in scikit-learn reduces the second problem by fitting a robust covariance estimate (the minimum covariance determinant), which ignores the most extreme points while fitting.
Distance to the k-th neighbor, and local density
A different idea needs no model of the shape: a normal point has other points nearby, and an anomaly is far from everything. The -th nearest neighbor distance of a point is the distance to its -th closest other point (the neighbors of P3.B1). A large value is a high score. Any shape of normal data is allowed, including several clouds, so this score finds the points in the gap that the Gaussian misses. The price: it stores all the data, it depends on , and it depends on the scale of each feature.
Scale matters (P3.A11). Suppose a person has an age and an income in dollars, a query is , and two stored people are and . The raw distance to is and to is : the income, with its huge numbers, decides, and the person who is years older counts as the nearer one. After dividing each feature by a standard deviation ( years and dollars, made up), the distances are and . The third cell below reproduces this. Scale the features before any distance-based score, and learn the scaling on training data only.
The local outlier factor (LOF; Breunig, Kriegel, Ng and Sander, 2000) fixes a second weakness. If one cloud is dense and another is spread out, a single distance threshold flags the edge of the spread-out one. LOF divides the density around a point’s neighbors by the density around the point itself: about means “as crowded as my neighbors”, clearly above means “much emptier than my neighbors”. In scikit-learn, LocalOutlierFactor scores the training data by default; to score new data, create it with novelty=True and fit it on normal data only.
Isolation forests: anomalies are easy to cut off
The methods so far describe where the normal data are and measure the distance from it. The isolation forest of Liu, Ting and Zhou (2008) never models normal data at all. It asks how easily a point can be separated from the others.
Play the game on the seven readings . Pick a cut point at random between the smallest and the largest value, keep the side that holds your reading, and repeat until it is alone. For , a cut anywhere from to (most of the range) separates it at once. For , the cuts keep missing it: it sits in the crowd, and it takes several cuts. An anomaly is a few and different point, so random cuts isolate it after fewer steps. Isolation is a tree: each cut is a node (a random feature, a random value between that feature’s smallest and largest value in the node), and the number of cuts to isolate a point is its path length .
One tree is noisy, so build many and average the path lengths , as P3.B4 averaged trees. The trees use no labels and no information about the target. Two details make this cheap and effective: each tree is built from a small random subsample of points (the paper uses small samples, such as ), which keeps normal points from crowding out anomalies, and the trees are grown only to a depth of about .
To turn an average path length into a score between and , compare it with a typical path length. In a binary search tree built on points, the average length of an unsuccessful search is
where (the number is Euler’s constant).
(For , ; for , .) The isolation score is
Read it at three points. If a point is isolated at once, and . If its average path equals the typical length, and . If it takes very long to isolate, falls toward . So a score well above marks an anomaly, scores clearly below mark safe normal points, and if all points score near , no point stands out. scikit-learn’s score_samples returns the negative of , so that lower means more abnormal.
The second cell plays the game with random cuts, times per value (a tree-less version: a stopping rule “all values left are equal” replaces the leaf adjustment of the real implementation, because the two readings of cannot be told apart).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The value needs cuts on average and scores . The others need between and cuts and score to , close to the neutral because in a sample of seven there is little room to stand out. The real isolation forest also picks a random feature for each cut, and a cut is placed uniformly between that feature’s smallest and largest value, so stretching one feature changes no path. It does not need the scaling that a distance needs.
See it: a contamination slider
This widget scores made-up points in two features: a large tilted cloud of normal points, a small round cloud of normal points, and planted anomalies. Five of them are far from everything. Three are a tight group in the gap between the two clouds. All of this is invented for the lesson; the planted label is used only to count the readouts, never by the methods.
Try these.
- Gaussian at 4%. The top scores are five planted points and three normal ones: of caught. The three gap points rank th to rd of : their is between and , since the mean of all the points sits in the gap. Move the slider to and the Gaussian still catches only of , while flagging normal points.
- Distance to the 5th neighbor. At it catches of , at it catches , and at all . The three gap points are close to each other, so with they partly hide each other (masking), and they need a threshold that flags more normal points as well.
- Isolation forest. At it flags points and catches ; at , of .
- Precision and recall. Going from to raises recall and, here, lowers precision from (one flagged point, a real anomaly) to between and . The best case at is of caught with normal points among flagged: recall , precision .
Reconstruction error: PCA now, autoencoders later
A third family of scores learns a compressed description of normal data, rebuilds each point from it, and flags points that are rebuilt badly. With PCA (P3.C3), the description is a projection onto a few directions of largest variance. A normal point lies near those directions, and the reconstruction error (the distance between the point and its projection) is small. A point away from them has a large error. A neural network can do the same with a nonlinear bottleneck: an autoencoder (P8.2) trained on normal data only. The preview is the one idea: whatever a model has learned to rebuild well is called normal.
That idea has a blind spot, which the third cell shows. Made-up normal data lie close to the line . A typical point on the line has error . A point off the line, , has error and a squared Mahalanobis distance of . A point on the line but far along it, , has an error of only : PCA rebuilds it perfectly, because the line is all it knows. Its Mahalanobis distance of does flag it. The reconstruction error only sees the distance from the subspace, and not how far along the subspace the point lies.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The same data in scikit-learn
Here are four scikit-learn detectors on the widget’s data, each with the share (so points) as its contamination (for OneClassSVM, nu=0.04). This is a static block, because scikit-learn does not run in the browser: the output below was produced on the machine used for this lesson, with scikit-learn 1.8.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.covariance import EllipticEnvelope
from sklearn.svm import OneClassSVM
from sklearn.metrics import average_precision_score
# Made-up data of the widget: two normal clouds and 8 planted anomalies (y = 1).
rng = np.random.default_rng(5)
big = rng.multivariate_normal([-1.2, -0.6], [[0.9, 0.72], [0.72, 0.9]], 150)
small = rng.multivariate_normal([3.0, 3.0], [[0.25, 0], [0, 0.25]], 42)
planted = np.array([[-4.2, 2.6], [5.6, -0.8], [0.2, 5.0], [-3.0, -4.0],
[0.9, 1.2], [1.1, 0.6], [1.6, 1.6], [4.8, 5.2]])
order = rng.permutation(200) # shuffle the rows, as in the widget
X = np.round(np.vstack([big, small, planted])[order], 3)
y = np.r_[np.zeros(192), np.ones(8)][order]
models = {
"IsolationForest": IsolationForest(n_estimators=50, max_samples=64, contamination=0.04, random_state=0),
"LocalOutlierFactor": LocalOutlierFactor(n_neighbors=20, contamination=0.04),
"EllipticEnvelope": EllipticEnvelope(contamination=0.04, random_state=0),
"OneClassSVM": OneClassSVM(nu=0.04, gamma="scale"),
}
for name, m in models.items():
flag = m.fit_predict(X) == -1 # -1 means "anomaly"
score = -(m.negative_outlier_factor_ if name == "LocalOutlierFactor" else m.score_samples(X))
print(f"{name:19s} flagged {flag.sum():2d} planted caught {int(flag[y == 1].sum())}"
f" average precision {average_precision_score(y, score):.2f}")
iso = models["IsolationForest"] # the threshold was fixed on the training scores
new = np.vstack([rng.multivariate_normal([-1.2, -0.6], [[0.9, 0.72], [0.72, 0.9]], 1560),
rng.multivariate_normal([3.0, 3.0], [[0.25, 0], [0, 0.25]], 440)])
print("flagged among 2000 new normal points:", (iso.predict(new) == -1).mean())
IsolationForest flagged 8 planted caught 5 average precision 0.55
LocalOutlierFactor flagged 8 planted caught 5 average precision 0.82
EllipticEnvelope flagged 8 planted caught 4 average precision 0.56
OneClassSVM flagged 9 planted caught 6 average precision 0.77
flagged among 2000 new normal points: 0.02
Read the output with care. The isolation forest here is the one in the widget, and its flags match the widget at ( of caught). OneClassSVM flagged and not , because nu only controls the share approximately. The last line shows the threshold at work: it was fixed on the training scores (where were flagged), and on new normal points about are flagged, not , because five of the eight flagged training points are planted anomalies, which score higher than most normal points, so the threshold sits higher than it would for clean data. With contamination="auto" the same forest flags of the training points: that threshold means “score above ”, and on this data far more than of the points exceed it. A default is a starting point.
How good is the detector?
Suppose of the points are anomalies. A detector that flags nothing is right on of them, an accuracy of , and finds no anomaly at all. With rare events accuracy mostly reports the size of the normal class. The numbers that matter are about the rare class (P3.A9).
- Precision: of the points flagged, the share that are really anomalies. It tells the analyst how much of their time the alarms waste.
- Recall: of the real anomalies, the share that are flagged. It tells you what slips through.
Both depend on the threshold, which is why the widget shows them for each setting of the slider. To judge a score, independent of any one threshold, sweep the threshold and plot precision against recall: the area under that curve is summarised as average precision. It punishes false alarms in a way that the area under the ROC curve does not when normal points greatly outnumber anomalies. On the widget’s data, the three scores have a ROC AUC of (Gaussian), (-NN distance) and (isolation forest), but average precisions of , and : the isolation forest ranks most planted points high, yet a dozen or more normal points rank above each of the three in the gap, and average precision feels that far more.
Two cautions about real data. Labels for anomalies are often incomplete: a fraud nobody noticed is labelled normal, so the measured precision is a lower bound, and the labelled cases may not look like future ones. And the alarm rate is a budget. If an analyst can review cases a day out of transactions, the threshold is the one that flags the top , and the question to ask of a detector is how many true cases are in those .
Intuition
Think of a school playground at break. Ask for the one child who wears a red hat, and a few questions find them: “left half or right half?” Ask for one child out of a crowd who all look alike, and you need many questions. The isolation forest is that guessing game with random questions, and the number of questions is the score. A method that measures a distance from the group’s center instead asks “how far from the crowd?”. The analogy breaks when the crowd has two parts: the center is empty, and “far from the center” no longer means “unusual”.
Math
Squared Mahalanobis distance: . For Gaussian data in dimensions, follows a chi-squared distribution with degrees of freedom, and for the tail is .
-NN score: , where is the -th closest other point.
Isolation score: with and . In an implementation, a leaf that still holds points at depth gives the path length , to account for the part of the tree that was not grown.
Threshold from a contamination share : flag a point when its score is at or above about the quantile of the training scores.
Code
from sklearn.ensemble import IsolationForest
iso = IsolationForest(n_estimators=100, contamination=0.01, random_state=0)
iso.fit(X_train) # X_train: the training features (scaling is optional for trees, but it matters for distance scores)
scores = -iso.score_samples(X_new) # larger means more unusual
alarm = iso.predict(X_new) == -1 # True for flagged pointsscore_samples is the negative of the paper’s . Set random_state (P1.G3): the trees are random.
Check your understanding
With the mean and covariance matrix of the two-sensor example above, which reading is more unusual: or ?
The Mahalanobis distance measures distance in units of the data’s own spread. lies along the long direction of the cloud, where points are common, and lies across it, where they are rare. The ordinary distance from the origin (4.24 against 3.61) points the wrong way. Equal coordinates do not give equal distances once the features are correlated. No fixed value separates normal from unusual: the cut-off depends on the share you want to flag.
A data scientist sets
contamination=0.05in an isolation forest. What does that setting do?Contamination chooses the threshold as a share of the training scores. It does not estimate anything and does not change the scores. On new data, the same threshold flags whatever share of points exceeds it, which can differ from . Nothing is removed before the trees are grown.
In an isolation forest, a point’s average path length equals , the typical path length for the sample size. What is its anomaly score ?
With the exponent is , so . A score close to needs an average path length close to , and a score close to needs a path as long as the tree allows. The value is a path length, not a score.
Only of transactions are fraud. A model that flags no transaction is therefore right of the time. What should be reported instead of accuracy?
Precision says how many alarms are real, and recall says how many frauds are found, so together they describe the rare class that matters. Accuracy on the normal class alone would also be high for a model that finds no fraud. A mean score and the contamination value say nothing about how well the alarms match the frauds.
Exercises
- In the seven readings , replace by . What is its -score, and does the IQR rule still flag it?
Show answer
The -score is , hardly more than before, and below the largest possible value for , so the rule with cut-off still does not fire. The quartiles ( and ) do not change, so the fences are the same and the IQR rule flags at once. - With the mean and covariance matrix of the two-sensor example, find for , and the share of normal readings that would lie further out (use ).
Show answer
Multiplying by gives again, so . The share is , about , so it would not be flagged by the cut-off . - An isolation forest with has . What score does a point with an average path length of get, and what score does one with get?
Show answer
and . The first is easily isolated and well above ; the second is a little below , the normal side. - In the widget, use the -NN distance at . How many planted anomalies are caught, how many normal points are flagged, and what are the precision and recall?
Show answer
All are caught, with normal points among the flagged. Precision is and recall . Catching the three gap points costs a high alarm rate. - Analysts can check of daily transactions. Which contamination share does that suggest, and why can the number of alarms on a given day still differ from ?
Show answer
. The threshold is fixed from the training scores, so a day with more unusual transactions raises more than alarms and a quiet day fewer.
Next: P3.C6 groups the points instead of scoring them, with hierarchical and density clustering (DBSCAN, which also labels the points that belong to no cluster as noise). P8.2 returns to the autoencoder, and P12.5 returns to monitoring.