Anomaly detection with isolation forests
Outliers are few and different, so random cuts isolate them quickly: short paths mean anomalies.
Animated explanation
The idea
Most anomaly detectors first model what "normal" looks like, then flag what doesn't fit. Isolation forests flip this around: anomalies are few and different, so they are easy to separate from everything else.
Build a tree by picking a random feature and a random split value, again and again, until every point sits alone in its own leaf. A point far from the crowd gets cut off after a handful of splits; a point in a dense cluster needs many. Average the number of splits (the path length) over a forest of such random trees and normalise it: short average paths mean anomalies. No distances, no densities, linear time, and it works well in many dimensions.
Using it in practice
Each tree is built on a small random subsample (256 points by default). Small samples actually help, since they reduce masking (many anomalies hiding each other) and swamping. The contamination parameter only sets the score threshold for labelling; the scores themselves rank points. Evaluate with labelled incidents if you have any (precision at the top k), and inspect the flagged cases.
Limits
Axis-parallel random cuts struggle with anomalies that only show in feature combinations along diagonals (Extended Isolation Forest uses random hyperplanes). Categorical features need encoding. And "unusual" is not "bad": anomaly scores need domain review.
The algorithm, step by step
- 1For each of t trees: draw a subsample of ψ points (e.g. 256).
- 2Grow an isolation tree: recursively choose a random feature and a uniform split between its min and max, until each leaf has one point or a depth limit .
- 3For a point x, path length = edges to its leaf + .
- 4Score ; flag the highest scores (or those above a threshold).
The maths
Normaliser
Anomaly score
Harmonic number
Strengths and weaknesses
Strengths
- Linear time and small memory; scales to big data
- No distance or density estimates; fine in many dimensions
- Few parameters; works unsupervised
Weaknesses
- Axis-aligned cuts miss some diagonal anomalies
- Scores need a threshold (contamination)
- Unusual ≠ harmful: results need review
Reach for it when…
Check your understanding
Lambdian Lab
Isolation forest from scratch
Implement the original algorithm.
- c(n): the average path length normaliser (c(1) = 0, c(2) = 1).
- build_tree(X, depth, max_depth, rng): nested dicts; a leaf is {"size": n}; a node is {"f", "v", "left", "right"}.
- path_length(tree, x, depth=0): edges to the leaf plus c(leaf size).
- iforest_scores(X, n_trees, sample_size, seed): anomaly scores for every row.