Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningUnsupervised Learning

Anomaly detection

P3.C540 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Rare, unusual examples such as a fraud, a failing machine or an intrusion are often the ones that matter most, and there are usually too few labelled cases to train a classifier. Anomaly detection learns what usual looks like and scores how far each example is from it.

  • A bank flags card payments that do not resemble a customer's usual ones, when only a handful of confirmed frauds exist. (P3.A10: Calibration and class imbalance)
  • A factory monitors sensors on a machine and raises an alarm before a failure, using readings of healthy operation only. (P12.5: Monitoring and drift, coming soon)
  • A neural network trained to rebuild normal inputs (an autoencoder) rebuilds unusual inputs badly, and the rebuilding error becomes the anomaly score. (P8.2: Autoencoders, coming soon)
  • Evaluation of a rare-event detector needs precision, recall and the precision-recall curve, because accuracy hides the rare class. (P3.A9: Evaluation metrics)

Before this: Random variables, Covariance and the multivariate Gaussian, Evaluation metrics, Bagging and random forests

After this lesson you can

  • Tell outliers, novelties and anomalies apart, name the three kinds of anomaly (point, contextual, collective), and say when to use unsupervised, semi-supervised or supervised detection
  • Turn a score into an alarm with a threshold, and say what the contamination setting of scikit-learn does and does not mean
  • Score points with a z-score or IQR fence, the Mahalanobis distance, the distance to the k-th neighbor, and an isolation forest, and say where each one fails
  • Judge a detector when labels are rare, using precision, recall and average precision instead of accuracy

A sensor on a pump reports its temperature every second. For months the readings wander between 6060 and 7070 degrees. Then one reads 9595. 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 −999-999 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 9595 degrees.
  • A contextual anomaly is unusual only in its context: 3030 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 5%5\% 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 1%1\%, a setting of 0.050.05 flags five times as many points as there are anomalies; if the real share is 10%10\%, at least half of them are missed. On new data the fixed threshold flags whatever share exceeds it, which can be quite different from 5%5\%.

Defaults differ between the estimators. For IsolationForest and LocalOutlierFactor the default is contamination="auto", which does not use a share: IsolationForest flags scores above 0.50.5 (the neutral value of the paper’s score), and LocalOutlierFactor flags a factor above about 1.51.5. EllipticEnvelope defaults to 0.10.1. 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 2,3,3,5,7,8,302,3,3,5,7,8,30. The zz-score of 3030 is 30−xˉs=2.21\frac{30-\bar x}{s}=2.21, and the zz rule flags ∣z∣>3|z|\gt3. It does not fire: one extreme value inflates ss and shifts xˉ\bar x, which shrinks its own zz (masking), and for n=7n=7 no zz can exceed n−1n=2.27\frac{n-1}{\sqrt n}=2.27. The IQR rule uses the quartiles: the fences are Q1−1.5 IQR=−3.75Q_1-1.5\,\text{IQR}=-3.75 and Q3+1.5 IQR=14.25Q_3+1.5\,\text{IQR}=14.25, and 3030 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 μ\boldsymbol{\mu} and a covariance matrix Σ\boldsymbol{\Sigma} 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,

d2=(x−μ)⊤Σ−1(x−μ),d^2=(\mathbf{x}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu}),

so d2d^2 itself is the score: a large d2d^2 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 μ=0\boldsymbol{\mu}=\mathbf{0} and (made up)

Σ=(2112),Σ−1=13(2−1−12).\begin{aligned} \boldsymbol{\Sigma}&=\begin{pmatrix}2&1\\1&2\end{pmatrix},\\ \boldsymbol{\Sigma}^{-1}&=\frac13\begin{pmatrix}2&-1\\-1&2\end{pmatrix}. \end{aligned}

Four readings:

  • (1,1)(1,1) lies along the cloud’s long direction: d2=23d^2=\frac23, d=0.82d=0.82. Common.
  • (1,−1)(1,-1) lies across it: d2=2d^2=2, d=1.41d=1.41. The same ordinary distance from the center, but rarer.
  • (3,3)(3,3): d2=6d^2=6, d=2.45d=2.45, even though it is 4.244.24 from the origin.
  • (3,−2)(3,-2): d2=12.67d^2=12.67, d=3.56d=3.56, with an ordinary distance of only 3.613.61. It is far less ordinary than (3,3)(3,3) 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 d2d^2 follows a known distribution whose upper tail is simply e−d2/2e^{-d^2/2} (this exact form holds for two features only). So a cut-off at d2=9.21d^2=9.21 flags the outer 1%1\%, (3,3)(3,3) is exceeded by about 5%5\% of normal readings and stays unflagged, and (3,−2)(3,-2), exceeded by only 0.18%0.18\%, is flagged. The first cell below checks these numbers.

Try it: z-score, fences and Mahalanobis distance

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The cell prints z=2.21z=2.21 (the largest possible is 2.272.27), the fences −3.75-3.75 and 14.2514.25 with 3030 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 kk-th nearest neighbor distance of a point is the distance to its kk-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 kk, 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 (30 years, 50 000 dollars)(30\text{ years},\,50\,000\text{ dollars}), and two stored people are A=(31, 53 000)A=(31,\,53\,000) and B=(90, 50 500)B=(90,\,50\,500). The raw distance to AA is 30003000 and to BB is 504504: the income, with its huge numbers, decides, and the person who is 6060 years older counts as the nearer one. After dividing each feature by a standard deviation (1515 years and 10 00010\,000 dollars, made up), the distances are 0.310.31 and 4.04.0. 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 11 means “as crowded as my neighbors”, clearly above 11 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 2,3,3,5,7,8,302,3,3,5,7,8,30. 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 3030, a cut anywhere from 88 to 3030 (most of the range) separates it at once. For 55, 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 hh.

One tree is noisy, so build many and average the path lengths E[h]E[h], 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 ψ\psi points (the paper uses small samples, such as 256256), which keeps normal points from crowding out anomalies, and the trees are grown only to a depth of about log⁡2ψ\log_2\psi.

To turn an average path length into a score between 00 and 11, compare it with a typical path length. In a binary search tree built on nn points, the average length of an unsuccessful search is

c(n)=2H(n−1)−2(n−1)n,c(n)=2H(n-1)-\frac{2(n-1)}{n},

where H(i)≈ln⁡i+0.5772H(i)\approx\ln i+0.5772 (the number 0.57720.5772 is Euler’s constant).

(For n=256n=256, c(n)=10.24c(n)=10.24; for n=7n=7, c(n)=3.02c(n)=3.02.) The isolation score is

s(x,ψ)=2−E[h(x)]/c(ψ).s(\mathbf{x},\psi)=2^{-E[h(\mathbf{x})]/c(\psi)}.

Read it at three points. If a point is isolated at once, E[h]→0E[h]\to0 and s→1s\to1. If its average path equals the typical length, E[h]=c(ψ)E[h]=c(\psi) and s=0.5s=0.5. If it takes very long to isolate, ss falls toward 00. So a score well above 0.50.5 marks an anomaly, scores clearly below 0.50.5 mark safe normal points, and if all points score near 0.50.5, no point stands out. scikit-learn’s score_samples returns the negative of ss, so that lower means more abnormal.

The second cell plays the game with random cuts, 40004000 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 33 cannot be told apart).

Try it: isolate a reading with random cuts

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The value 3030 needs 1.231.23 cuts on average and scores 0.750.75. The others need between 3.03.0 and 3.73.7 cuts and score 0.430.43 to 0.500.50, close to the neutral 0.50.5 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 200200 made-up points in two features: a large tilted cloud of 150150 normal points, a small round cloud of 4242 normal points, and 88 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.

−4−20246−4−20246feature 1feature 2

● normal (made up), ▲ planted anomaly, ◇ flagged. Stronger background shade = a point there would score higher than a larger share of the 200 points. The line is the alarm threshold.

flagged: 8 of 200
planted caught: 5 of 8
normal flagged: 3
precision: 63% · recall: 63%

Gaussian (Mahalanobis) with 4% flagged: 8 points flagged, 5 of 8 planted anomalies caught, 3 normal points flagged. Alarm threshold: squared Mahalanobis distance at least 4.64.

Contamination slider. 200 made-up points: 192 normal (circles, two clouds) and 8 planted anomalies (triangles; five far away, three in the gap between the clouds). Pick a score: the squared Mahalanobis distance from the mean of all 200 points, the distance to the 5th nearest other point, or the isolation score of 50 trees (scikit-learn, 64 points per tree). The slider flags the top share of points by score, from 0.5% to 20% (1 to 40 points), and the readouts count how many planted anomalies are caught and how many normal points are flagged. The grey background shades every location in five bands by how many of the 200 points have a lower score than a point there would have (a stronger shade means a higher share, and the strongest band is above 95% of the points). It does not change with the slider. The black line encloses the area at or above the alarm threshold, and it does move. Flagged points are drawn with a diamond outline, so the picture does not rely on color.

Try these.

  1. Gaussian at 4%. The 88 top scores are five planted points and three normal ones: 55 of 88 caught. The three gap points rank 9797th to 153153rd of 200200: their d2d^2 is between 0.30.3 and 1.01.0, since the mean of all the points sits in the gap. Move the slider to 20%20\% and the Gaussian still catches only 55 of 88, while flagging 3535 normal points.
  2. Distance to the 5th neighbor. At 4%4\% it catches 66 of 88, at 6%6\% it catches 77, and at 20%20\% all 88. The three gap points are close to each other, so with k=5k=5 they partly hide each other (masking), and they need a threshold that flags more normal points as well.
  3. Isolation forest. At 2%2\% it flags 44 points and catches 22; at 4%4\%, 55 of 88.
  4. Precision and recall. Going from 0.5%0.5\% to 20%20\% raises recall and, here, lowers precision from 100%100\% (one flagged point, a real anomaly) to between 12.5%12.5\% and 20%20\%. The best case at 20%20\% is 88 of 88 caught with 3232 normal points among 4040 flagged: recall 100%100\%, precision 20%20\%.

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 b=2ab=2a. A typical point on the line has error 0.010.01. A point off the line, (1,−1)(1,-1), has error 1.331.33 and a squared Mahalanobis distance of 93.193.1. A point on the line but far along it, (4,8)(4,8), has an error of only 0.020.02: PCA rebuilds it perfectly, because the line is all it knows. Its Mahalanobis distance of 17.217.2 does flag it. The reconstruction error only sees the distance from the subspace, and not how far along the subspace the point lies.

Try it: reconstruction error and scaling

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 4%4\% (so 88 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 88 flags match the widget at 4%4\% (55 of 88 caught). OneClassSVM flagged 99 and not 88, because nu only controls the share approximately. The last line shows the threshold at work: it was fixed on the training scores (where 4%4\% were flagged), and on 20002000 new normal points about 2%2\% are flagged, not 4%4\%, 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 6363 of the 200200 training points: that threshold means “score above 0.50.5”, and on this data far more than 4%4\% of the points exceed it. A default is a starting point.

How good is the detector?

Suppose 88 of the 200200 points are anomalies. A detector that flags nothing is right on 192192 of them, an accuracy of 96%96\%, 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 0.780.78 (Gaussian), 0.990.99 (kk-NN distance) and 0.960.96 (isolation forest), but average precisions of 0.650.65, 0.840.84 and 0.550.55: 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 3030 cases a day out of 30003000 transactions, the threshold is the one that flags the top 1%1\%, and the question to ask of a detector is how many true cases are in those 3030.

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: d2=(x−μ)⊤Σ−1(x−μ)d^2=(\mathbf{x}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu}). For Gaussian data in mm dimensions, d2d^2 follows a chi-squared distribution with mm degrees of freedom, and for m=2m=2 the tail is P(d2>t)=e−t/2P(d^2\gt t)=e^{-t/2}.

kk-NN score: score(x)=∥x−x(k)∥\text{score}(\mathbf{x})=\lVert\mathbf{x}-\mathbf{x}_{(k)}\rVert, where x(k)\mathbf{x}_{(k)} is the kk-th closest other point.

Isolation score: s(x,ψ)=2−E[h(x)]/c(ψ)s(\mathbf{x},\psi)=2^{-E[h(\mathbf{x})]/c(\psi)} with c(n)=2H(n−1)−2(n−1)/nc(n)=2H(n-1)-2(n-1)/n and H(i)≈ln⁡i+0.5772H(i)\approx\ln i+0.5772. In an implementation, a leaf that still holds nℓn_\ell points at depth ee gives the path length e+c(nℓ)e+c(n_\ell), to account for the part of the tree that was not grown.

Threshold from a contamination share α\alpha: flag a point when its score is at or above about the (1−α)(1-\alpha) 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 points

score_samples is the negative of the paper’s ss. Set random_state (P1.G3): the trees are random.

Check your understanding

  1. With the mean and covariance matrix of the two-sensor example above, which reading is more unusual: (3,3)(3,3) or (3,−2)(3,-2)?

  2. A data scientist sets contamination=0.05 in an isolation forest. What does that setting do?

  3. In an isolation forest, a point’s average path length equals c(ψ)c(\psi), the typical path length for the sample size. What is its anomaly score s=2−E[h]/c(ψ)s=2^{-E[h]/c(\psi)}?

  4. Only 0.5%0.5\% of transactions are fraud. A model that flags no transaction is therefore right 99.5%99.5\% of the time. What should be reported instead of accuracy?

Exercises

  1. In the seven readings 2,3,3,5,7,8,302,3,3,5,7,8,30, replace 3030 by 30003000. What is its zz-score, and does the IQR rule still flag it?
    Show answerThe zz-score is 2.2682.268, hardly more than before, and below the largest possible value 2.272.27 for n=7n=7, so the zz rule with cut-off 33 still does not fire. The quartiles (33 and 7.57.5) do not change, so the fences are the same and the IQR rule flags 30003000 at once.
  2. With the mean and covariance matrix of the two-sensor example, find d2d^2 for (−2,2)(-2,2), and the share of normal readings that would lie further out (use e−d2/2e^{-d^2/2}).
    Show answerMultiplying Σ−1\boldsymbol{\Sigma}^{-1} by (−2,2)(-2,2) gives (−2,2)(-2,2) again, so d2=(−2)(−2)+2⋅2=8d^2=(-2)(-2)+2\cdot2=8. The share is e−4=0.018e^{-4}=0.018, about 1.8%1.8\%, so it would not be flagged by the 1%1\% cut-off d2=9.21d^2=9.21.
  3. An isolation forest with ψ=256\psi=256 has c(256)=10.24c(256)=10.24. What score does a point with an average path length of 33 get, and what score does one with 1212 get?
    Show answer2−3/10.24=0.822^{-3/10.24}=0.82 and 2−12/10.24=0.442^{-12/10.24}=0.44. The first is easily isolated and well above 0.50.5; the second is a little below 0.50.5, the normal side.
  4. In the widget, use the kk-NN distance at 20%20\%. How many planted anomalies are caught, how many normal points are flagged, and what are the precision and recall?
    Show answerAll 88 are caught, with 3232 normal points among the 4040 flagged. Precision is 8/40=20%8/40=20\% and recall 100%100\%. Catching the three gap points costs a high alarm rate.
  5. Analysts can check 3030 of 30003000 daily transactions. Which contamination share does that suggest, and why can the number of alarms on a given day still differ from 3030?
    Show answer30/3000=1%30/3000=1\%. The threshold is fixed from the training scores, so a day with more unusual transactions raises more than 3030 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.

Key takeaways

  • An anomaly is an example that does not resemble the rest. Unsupervised methods learn usual from unlabelled data, semi-supervised methods learn it from data believed to be normal, and supervised methods need labelled anomalies, which are rare. An outlier is a fact about the numbers, and whether to delete it, fix it or study it depends on what produced it.
  • Every method here gives each point a score, and a threshold turns scores into alarms. The threshold sets the alarm rate: a numeric contamination setting in scikit-learn is the share of the training points that will be flagged (the default "auto" uses a fixed score instead), not an estimate of how many anomalies exist.
  • The squared Mahalanobis distance (x−μ)⊤Σ−1(x−μ)(\mathbf{x}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu}) measures distance in units of the data's own spread and correlation. It describes the data with one ellipse, so it misses unusual points that sit between two clouds.
  • The distance to the k-th nearest neighbor works for any shape of data but depends on the scale of each feature, so scale first (P3.A11). Local outlier factor compares a point's density with its neighbors' density.
  • An isolation forest cuts the space with random splits. Anomalies are isolated in fewer cuts, and the score is s=2−E[h]/c(ψ)s=2^{-E[h]/c(\psi)}: near 1 for easily isolated points, about 0.5 when no point stands out.
  • With rare labels, accuracy is useless (flag nothing and be right 96% of the time on this lesson's data). Use precision, recall and average precision at an alarm rate you can afford. A reconstruction error from PCA or an autoencoder is another score, and it has blind spots too.
Found a mistake? Tell us