Foundations to Frontier
Tests
D. Classical Machine Learning › D10 Anomaly and Outlier Detection

Isolation Forest

Isolation Forest (Liu, Ting and Zhou, 2008) detects anomalies without modelling normal data at all. It grows random trees that split on a random feature at a random value until each point is isolated, and anomalies, being few and different, are isolated after far fewer splits than normal points. Averaging the path length over many trees built on small subsamples gives a score s = 2^(−E[h]/c(ψ)), normalised by the average path length of a binary search tree. The method is linear-time, needs no distance computations, handles high dimensions and is the default unsupervised detector in many toolkits. Its quirks follow from its design: axis-parallel cuts produce blocky score maps that miss anomalies hidden along diagonal structure (fixed by extended isolation forest's random hyperplanes), and the subsample size ψ trades protection against clustered anomalies for resolution of fine structure. This page covers isolation trees, the score and its normalisation, subsampling, masking and swamping, the extended variant, and choosing ψ, the number of trees and the contamination threshold. In the exercises you implement isolation and extended isolation forests; then you show that the best ψ depends on the kind of anomaly.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Anomalies are easy to cut off

Play a guessing game: pick a point in a cloud of data, then keep slicing the space with random straight cuts until that point sits alone in its slice. A point deep inside the crowd needs many cuts, because its neighbours keep sharing its slice. A lonely point far from the crowd is usually alone after two or three cuts. Isolation Forest plays this game many times with random cuts and calls the points that are isolated quickly anomalies.

Isolation forest: anomalies are easy to cut off
AUC 0.946 · mean score: anomalies 0.564, normal points 0.485 (0.5 = an average path)
Shading shows the score everywhere; crosses are the planted anomalies. Standard trees cut parallel to the axes, so on the diagonal band the score map has a blocky "plus"-shaped bias: points just off the band but inside its x- and y-ranges look normal. Random-direction splits (extended) follow the band and raise the AUC. The subsample size ψ cuts both ways. For the dense cluster a small ψ helps: fewer cluster points land in each tree, so the cluster no longer protects itself. For the band a small ψ hurts: 16 points cannot describe a thin band, and the AUC falls to about 0.5.
Why engineers care

Isolation Forest is fast (linear in the data size), needs no distance metric or density model, copes with many features, and has two meaningful settings. That makes it a standard first detector for telemetry health monitoring, fraud, intrusion and manufacturing data. Its blind spots, structure along diagonals and the subsample-size trade-off, are easy to fall into without knowing them.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Isolation Forest flags points that are…
  2. 2. Does Isolation Forest need a distance metric?
  3. 3. Why use many trees?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Trees, path lengths and the score

Isolation tree. Draw a subsample of ψ points. Recursively pick a random feature q and a split value uniformly between that feature’s minimum and maximum in the node, until a node holds one point or the depth limit ⌈log₂ ψ⌉ is reached: 8 for ψ = 256.

Path length h(x). The number of edges from the root to the leaf x falls in. If the leaf still holds m > 1 points, add c(m), the expected remaining depth, so that truncated trees are not biased.

Normalisation. c(n) = 2H(n − 1) − 2(n − 1)/n, with H(i) ≈ ln i + 0.5772 the harmonic number. It is the average path length of an unsuccessful search in a binary search tree of n points:

  • c(256) = 10.24;
  • c(16) = 4.70.

Score. s(x) = 2^(−E[h(x)]/c(ψ)):

  • E[h] → 0 gives s → 1 (clearly anomalous);
  • E[h] = c(ψ) gives s = 0.5 (average);
  • E[h] = 2c(ψ) gives s = 0.25 (deep inside the data).

With ψ = 256, an average path of 5 gives s = 2^(−5/10.24) = 0.713, and a path of 15 gives 0.362.

The steps in plain English:

  1. Choose ψ (256 by default) and the number of trees (100 is usually enough).
  2. Grow each tree on a fresh random subsample, with random splits up to depth ⌈log₂ ψ⌉.
  3. Score every point by its average path length across trees, then s = 2^(−E[h]/c(ψ)).
  4. Flag the top fraction expected to be anomalous (the contamination), or choose a threshold on held-out labelled data.
📝 Quick check (Level 1)
0/3 answered
  1. 1. The depth limit for ψ = 64 is…
  2. 2. An average path length equal to c(ψ) gives a score of…
  3. 3. c(n) is the average path length of…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

Subsampling, masking and axis-parallel bias

Why subsample? Small subsamples make every tree cheap, and they reduce masking (a cluster of anomalies shielding itself) and swamping (normal points near anomalies getting high scores). With fewer points per tree, a dense anomaly cluster contributes only a few points, which are then isolated quickly. Liu et al. recommend ψ = 256 for most data.

Expected path lengths. In one dimension, a point at the edge of n uniform points is isolated after about ln n random cuts, while a point in the middle needs about 2 ln n. The ratio is what the score measures.

Axis-parallel bias. Each cut is perpendicular to an axis. A point just off a diagonal band lies inside the band’s range along both x and y, so axis cuts struggle to separate it from the band. Score maps show blocky, cross-shaped artefacts. Extended Isolation Forest (Hariri, Kind and Brunner, 2021) cuts along random directions, removing this bias.

Exercise 1 (500 Gaussian points plus 20 scattered anomalies, ψ = 256, 100 trees):

  • c(256) = 10.24;
  • AUC 0.999;
  • mean scores 0.683 for the anomalies against 0.419 for normal points.
from sklearn.ensemble import IsolationForest
iso = IsolationForest(n_estimators=100, max_samples=256, contamination="auto", random_state=0).fit(X)
scores = -iso.score_samples(X)          # higher = more anomalous (sklearn returns the negated score)
🐍 Exercise 1: isolation forest from scratch
Implement c(n), random isolation trees that push evaluation points down as they grow (with optional random-direction splits), the anomaly score 2^(−E[h]/c(ψ)), and a rank-based AUC; test on a Gaussian cloud with scattered anomalies.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Subsampling helps against…
  2. 2. Extended Isolation Forest splits…
  3. 3. In 1-D, edge points need about … random cuts compared with 2 ln n for central points.

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why short paths mean anomalies. A random split separates point x from the others in proportion to the empty space around x along the chosen feature. Isolated points have large empty margins, so each split is likely to cut them off. The expected number of random cuts to isolate a point is roughly logarithmic in the number of points “between” it and the boundary, which is why scores can be compared through c(ψ).

Relation to density. Isolation depth is a monotone proxy for density only in one dimension. In several dimensions, axis cuts measure marginal separation, which is why anomalies that are unusual only in combination, such as off a diagonal, are hard for standard trees. Random-direction cuts behave like random projections and see such combinations.

Settings and cost. Training costs O(t ψ log ψ) and scoring O(n t log ψ), independent of the dimension except for reading the chosen feature. Scores converge quickly in the number of trees t; about 100 trees is standard. Irrelevant features dilute the cuts: with many noise features, most cuts are wasted, so feature selection or SCiForest-style split selection helps.

Interview questions.

  • How do you choose the contamination? If you know the anomaly rate, use it. Otherwise inspect the score distribution for a gap, or calibrate on a small labelled set. Report scores, not just flags.
  • When does Isolation Forest fail? With anomalies that are unusual only in a feature combination along correlated structure (use the extended version or rotate the data), local anomalies inside dense multimodal data (try LOF), and many irrelevant features.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Isolation Forest's training cost depends mainly on…
  2. 2. Many irrelevant features tend to…
  3. 3. For local anomalies near a dense cluster in multimodal data, a better choice may be…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Is there a best subsample size?

History.

  • F. T. Liu, K. M. Ting and Z.-H. Zhou (2008, 2012) introduced Isolation Forest, and SCiForest (2010) for clustered anomalies.
  • S. Hariri, M. C. Kind and R. J. Brunner (2021) introduced Extended Isolation Forest.
  • Isolation-based ideas spread to streams (RRCF, Guha et al., 2016) and to deep variants.

Exercise 2. AUC averaged over 3 datasets, with 50 trees.

  • (a) A dense cluster of 50 anomalies near 1000 standard normal points, at four subsample sizes.
  • (b) 20 anomalies one unit off a thin diagonal band of 1000 points, comparing standard and extended trees.
ψ (a) dense cluster (b) band, standard (b) band, extended
16 1.000 0.515 0.764
64 1.000
256 0.982 0.941 0.984
1020–1050 (all data) 0.944 0.991 0.994
  • Small subsamples defeated the anomaly cluster: AUC 1.000 at ψ ≤ 64 against 0.944 with all the data. With all the data, the 50 cluster points shield each other, which is masking.
  • Small subsamples destroyed detection near fine structure: at ψ = 16, the band could not be resolved and standard trees performed at chance (0.515). Larger ψ steadily helped.
  • Random-direction splits mattered most when the trees were coarse (0.764 against 0.515 at ψ = 16, 0.984 against 0.941 at 256). With all the data the gap almost vanished (0.994 against 0.991), because enough axis cuts eventually trace the band.
  • The default ψ = 256 is a compromise, not an optimum. Clustered anomalies favour smaller ψ, and subtle anomalies near structure favour larger ψ.
🐍 Exercise 2 (research): subsample size and split direction
Measure the AUC of isolation forests for (a) a dense cluster of anomalies at ψ = 16 … all, and (b) anomalies just off a thin diagonal band at ψ = 16, 256, all, with standard and extended trees.

Isolation Forest in AI, robotics and aerospace

  • Telemetry health monitoring: score windows of engineered features (means, slopes, spectral peaks) per subsystem, and alert on the highest scores.
  • Manufacturing inspection: flag unusual process parameter combinations, using the extended version when parameters are strongly correlated.
  • Data cleaning before training: remove gross anomalies from training sets for perception or control models.

References

  1. F. T. Liu, K. M. Ting, Z.-H. Zhou (2008). “Isolation forest.” Proc. IEEE ICDM.
  2. F. T. Liu, K. M. Ting, Z.-H. Zhou (2012). “Isolation-based anomaly detection.” ACM Transactions on Knowledge Discovery from Data 6(1).
  3. S. Hariri, M. C. Kind, R. J. Brunner (2021). “Extended isolation forest.” IEEE Transactions on Knowledge and Data Engineering 33(4).
  4. S. Guha, N. Mishra, G. Roy, O. Schrijvers (2016). “Robust random cut forest based anomaly detection on streams.” Proc. ICML.