Skip to content
Lambdian

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

  1. 1
    For each of t trees: draw a subsample of ψ points (e.g. 256).
  2. 2
    Grow 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 ⌈log⁡2ψ⌉\lceil\log_2\psi\rceil.
  3. 3
    For a point x, path length h(x)h(x) = edges to its leaf + c(leaf size)c(\text{leaf size}).
  4. 4
    Score s=2−hˉ(x)/c(ψ)s = 2^{-\bar h(x)/c(\psi)}; flag the highest scores (or those above a threshold).

The maths

Normaliser

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

Anomaly score

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

Harmonic number

H(i)≈ln⁡i+0.5772156649H(i) \approx \ln i + 0.5772156649

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…

Fraud, intrusion, sensor or manufacturing anomalies in tabular data, especially without labels.

Check your understanding

Question 1

Q1Why do anomalies get short path lengths?

Question 2

Q2A score close to 1 means…

Question 3

Q3Why are isolation trees built on small subsamples?

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 2−hˉ/c(ψ)2^{-\bar h/c(\psi)} for every row.
Open the labPython + NumPy + scikit-learn runs in your browser. Sign-in keeps your code and attempts.