TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Anomaly Detection with Isolation Forests

Anomaly Detection with Isolation Forests

A card payment at 3 a.m. in a country the customer has never visited, a sensor reading far outside its usual range, a server whose memory use suddenly doubles: anomalies are rare, varied, and usually unlabelled. Most detectors model what normal looks like (a density, a distance to neighbours) and flag what does not fit. The isolation forest (Liu, Ting and Zhou, 2008) turns the question around: anomalies are few and different, so they are easy to isolate. Cut the data with random splits and an anomaly ends up alone after a few cuts, while a normal point deep inside the crowd needs many.

The idea

An isolation tree is built on a random subsample by repeatedly picking a random feature and a random threshold between that feature's minimum and maximum in the current node, until each point is alone (or a depth limit is hit). The path length h(x)h(\mathbf{x}) is the number of splits needed to isolate x\mathbf{x}. Averaged over many random trees, short paths mean anomalies.

To compare path lengths across sample sizes, they are normalised by c(m)c(m), the average path length of an unsuccessful search in a binary search tree of mm points:

c(m)=2(ln⁡(m−1)+γ)−2(m−1)m,s(x)=2−E[h(x)]/c(m)c(m) = 2\big(\ln(m - 1) + \gamma\big) - \frac{2(m - 1)}{m}, \qquad s(\mathbf{x}) = 2^{-\mathbb{E}[h(\mathbf{x})]/c(m)}

with γ≈0.5772\gamma \approx 0.5772 (Euler's constant). The score ss is near 1 for clear anomalies, around 0.5 or below for normal points. When a tree stops at its depth limit ⌈log⁡2m⌉\lceil \log_2 m \rceil with several points left in a leaf, c(leaf size)c(\text{leaf size}) is added as the expected remaining depth.

From scratch

A cloud of 300 normal points and a dozen planted outliers far from it. Each tree is grown on a subsample of 256 points, and all points are routed down the tree as it is grown:

python · try it yourself
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score

rng = np.random.default_rng(0)
normal = rng.normal(size=(300, 2))
outliers = rng.uniform(-6, 6, size=(15, 2))
outliers = outliers[np.linalg.norm(outliers, axis=1) > 3.5]        # keep only points far from the bulk
X = np.vstack([normal, outliers])
is_out = np.r_[np.zeros(300), np.ones(len(outliers))]

def c(n):
    """Average path length of an unsuccessful search in a binary search tree of n points."""
    return 2 * (np.log(n - 1) + np.euler_gamma) - 2 * (n - 1) / n if n > 2 else (1.0 if n == 2 else 0.0)

def isolate(S, X, idx, depth, rng, h, max_depth):
    """Grow one isolation tree on the subsample S and route the query rows X[idx] down it at the same time."""
    if len(S) <= 1 or depth >= max_depth or np.all(S == S[0]):
        h[idx] += depth + c(len(S))                    # leaf: depth plus the expected depth still to go
        return
    j = rng.integers(S.shape[1])                       # a random feature ...
    t = rng.uniform(S[:, j].min(), S[:, j].max())      # ... and a random split between its min and max
    go_left = X[idx, j] < t
    isolate(S[S[:, j] < t], X, idx[go_left], depth + 1, rng, h, max_depth)
    isolate(S[S[:, j] >= t], X, idx[~go_left], depth + 1, rng, h, max_depth)

def iforest_scores(X, n_trees=100, sample=256, seed=0):
    rng = np.random.default_rng(seed)
    h = np.zeros(len(X))
    for _ in range(n_trees):
        S = X[rng.choice(len(X), sample, replace=False)]           # each tree sees a subsample
        isolate(S, X, np.arange(len(X)), 0, rng, h, max_depth=int(np.ceil(np.log2(sample))))
    return 2 ** (-(h / n_trees) / c(sample))           # anomaly score s in (0, 1): near 1 = anomalous

s = iforest_scores(X)
sk = -IsolationForest(n_estimators=100, random_state=0).fit(X).score_samples(X)   # sklearn: higher = more anomalous
print("outliers planted:", len(outliers))
print("mean score  normal points", round(s[is_out == 0].mean(), 3), "  outliers", round(s[is_out == 1].mean(), 3))
print("ROC AUC ours", round(roc_auc_score(is_out, s), 3), " sklearn", round(roc_auc_score(is_out, sk), 3))
top = np.argsort(-s)[:len(outliers)]
print("planted outliers among our top", len(outliers), "scores:", int(is_out[top].sum()))
print("rank correlation with sklearn's scores:", round(np.corrcoef(np.argsort(np.argsort(s)), np.argsort(np.argsort(sk)))[0, 1], 3))
outliers planted: 12
mean score  normal points 0.419   outliers 0.686
ROC AUC ours 0.998  sklearn 0.999
planted outliers among our top 12 scores: 11
rank correlation with sklearn's scores: 0.967

Normal points average a score of 0.419 and the planted outliers 0.686. Ranking all points by score separates the two groups almost perfectly (ROC AUC 0.998), and 11 of the 12 highest-scoring points are planted outliers (the remaining one ranks just below a few extreme normal points). The trees are random, so our scores and scikit-learn's are not identical, but they rank the points almost the same way (rank correlation 0.967). score_samples in scikit-learn returns −s-s, which is why the code negates it.

The method needs no distances and no density estimate, and each tree only sees 256 points, so training is nearly independent of nn and very fast.

On real data: rare malignant tumours

Anomaly detectors are judged on data where the anomalies are known. Here the benign tumours of the breast-cancer data are "normal" and 20 malignant ones are mixed in as rare anomalies (about 5 %); no detector sees the labels. Four detectors, scored by ROC AUC and by average precision, which focuses on the top of the ranking:

python · try it yourself
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.covariance import EllipticEnvelope
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score, average_precision_score

# benign tumours are "normal"; keep only 20 malignant ones as rare anomalies (about 5 %)
X, y = load_breast_cancer(return_X_y=True)
rng = np.random.default_rng(0)
keep = np.r_[np.flatnonzero(y == 1), rng.choice(np.flatnonzero(y == 0), 20, replace=False)]
X, anomaly = StandardScaler().fit_transform(X[keep]), (y[keep] == 0).astype(int)
print("rows:", len(X), " anomalies:", anomaly.sum())

scores = {
    "isolation forest": -IsolationForest(n_estimators=300, random_state=0).fit(X).score_samples(X),
    "local outlier factor": -LocalOutlierFactor(n_neighbors=20).fit(X).negative_outlier_factor_,
    "elliptic envelope": -EllipticEnvelope(random_state=0, support_fraction=0.9).fit(X).score_samples(X),
    "distance to mean": np.linalg.norm(X - X.mean(axis=0), axis=1),
}
for name, s in scores.items():
    print(f"{name:21s} ROC AUC {roc_auc_score(anomaly, s):.3f}  average precision {average_precision_score(anomaly, s):.3f}")
rows: 377  anomalies: 20
isolation forest      ROC AUC 0.945  average precision 0.575
local outlier factor  ROC AUC 0.921  average precision 0.453
elliptic envelope     ROC AUC 0.953  average precision 0.475
distance to mean      ROC AUC 0.949  average precision 0.562

All four rank most malignant tumours above most benign ones (ROC AUC 0.92 to 0.95), and the isolation forest has the best average precision (0.575): its top-ranked cases are most often real anomalies. A plain distance to the mean is nearly as good here, because malignant tumours are mainly larger; always include such a simple baseline. The scaler is fitted on all rows, which is fine for unsupervised scoring of a fixed batch; a deployed detector would be fitted on past data and applied to new data. The other detectors: local outlier factor compares a point's local density with its neighbours' (good for clusters of different densities), the elliptic envelope fits a robust Gaussian (good when normal data is roughly Gaussian), and a Gaussian mixture or an autoencoder can flag low density or high reconstruction error.

Hyperparameters

Hyperparameter Effect
n_estimators number of trees; 100 to 300 is usually enough
max_samples subsample per tree (default 256); small samples help isolate anomalies hidden in dense data (masking)
contamination expected share of anomalies; only sets the threshold of predict, not the scores
max_features features drawn per tree

Strengths, weaknesses, when to use it

Isolation forests are fast, scale to large and high-dimensional data, need no scaling (splits are per feature) and few assumptions. Their axis-parallel splits produce artefacts along the axes, they find "global" anomalies better than points that are only unusual relative to a dense local cluster, and like every unsupervised detector they flag what is rare, which is not always what is interesting. Use them as a default first detector on tabular data; validate on whatever labelled incidents you have, and set the alert threshold by the number of alerts people can review.

Pitfalls

  • Treating contamination as a learned quantity. It is your guess; it decides how many points predict flags.
  • Evaluating with accuracy. With 5 % anomalies, "nothing is anomalous" is 95 % accurate; use ROC AUC, average precision or precision at the top kk.
  • Duplicated anomalies. Many identical fraud attempts form a dense cluster and stop looking rare (masking).

Practice

  1. Compute c(256)c(256) and the score of a point whose average path length is 4.
Answer

c(256)=2(ln⁡255+0.5772)−2⋅255/256=2(5.541+0.577)−1.992=10.24c(256) = 2(\ln 255 + 0.5772) - 2 \cdot 255/256 = 2(5.541 + 0.577) - 1.992 = 10.24. Then s=2−4/10.24=2−0.391≈0.76s = 2^{-4/10.24} = 2^{-0.391} \approx 0.76: an anomaly.

  1. Why are anomalies isolated after fewer random splits?
Answer

A random threshold drawn between a feature's minimum and maximum is more likely to fall in a big empty gap than inside a dense region. A point far from the rest is separated by any threshold in that gap, so it is cut off early; a point in the dense bulk needs many splits before it is alone.

Test yourself

What makes a point look anomalous to an isolation forest?

  1. A long average path length
  2. A short average path length: it is isolated after few random splits
  3. A large distance to its cluster's centroid
  4. A low density estimate

What does the contamination parameter change?

  1. The trees that are grown
  2. The anomaly scores
  3. Only the threshold used by predict to label points as anomalies
  4. The subsample size

A data set has 1 % anomalies. Which metric is least useful for judging a detector?

  1. ROC AUC
  2. Average precision
  3. Accuracy
  4. Precision among the top 50 scores