Sub topic 4
Path length as a measure of abnormality
This chapter assumes you know how a decision tree partitions feature space and can read short NumPy code. It also assumes you have met the isolation idea and the way an isolation tree picks a random feature and a random split value. Here we turn a tree into a number. That number is the path length, and the anomaly score in later chapters is built from it.
What path length is
An isolation tree keeps splitting a sample until each point sits alone, or until a depth limit is reached. Take a point x and drop it from the root. At every internal node it goes left or right depending on one feature and one split value. The path length h(x) is the number of edges it crosses from the root to the leaf where it ends.
Path length is a proxy for how hard a point is to separate from the rest of the sample:
- A point far from the bulk of the data is cut off by almost any split that lands between it and the data. It reaches a leaf after a few edges.
- A point inside a dense region has many neighbors on every side. Random splits keep leaving it in a group with others, so it descends deeper.
The tree never measures distance or density. Depth reflects both, because a random cut that separates a point from its neighbors is more likely when those neighbors are few or far away.
One tree is noisy
Every split is random, so h(x) is a random variable. A single tree can isolate a normal point in two cuts by luck, or take many cuts to isolate an outlier if the first splits land on the wrong side of the data. The usable quantity is the expected path length E[h(x)], estimated by averaging over many trees. The next chapter covers the forest. For now, remember that only the average is meaningful and that one tree's path is just one draw.
The gap between the two groups is what makes the average useful. Across many random trees, an outlier's average depth is much smaller than a typical point's average depth. It is possible to find an unlucky tree where the order reverses.
The depth limit and the c(n) correction
Growing each tree until every point is alone is wasteful, because only the shallow part of the tree matters for finding anomalies. Isolation trees therefore stop at a maximum depth, set to ceil(log2(ψ)), where ψ is the number of points in the subsample used for that tree. This is roughly the average depth of a balanced tree on ψ points. In scikit-learn, max_samples=256 gives a maximum depth of 8.
Stopping early leaves some leaves with more than one point. If x ends in a leaf holding size training points, the path is incomplete: a full tree would have kept splitting. The paper corrects for this by adding the expected number of further splits needed to isolate one point among size:
h(x) = e + c(size)
Here e is the number of edges actually traversed. The function c(n) is the average path length of an unsuccessful search in a binary search tree built on n points:
c(n) = 2(ln(n − 1) + γ) − 2(n − 1)/n, for n > 2
with c(2) = 1, c(1) = 0, and γ ≈ 0.5772 (the Euler–Mascheroni constant). The correction matters in two ways. A leaf with 1 point adds nothing. A leaf with 30 points adds a substantial amount, which keeps the path length comparable between a point that was fully isolated and one that hit the depth limit.
| Where the traversal ends | e | Correction | h(x) |
|---|---|---|---|
| Leaf with 1 point | edges traversed | c(1) = 0 | e |
| Leaf with 2 points | edges traversed | c(2) = 1 | e + 1 |
| Leaf cut off by depth limit, n points | max depth | c(n) | max depth + c(n) |
Measuring path length by hand
You can estimate E[h(x)] for one point without building a whole tree. A tree only matters for x along the branch that contains x, so you can follow x down recursively and discard the other side at each split. The distribution of h(x) is identical to building the full tree and then walking it.
import numpy as np
EULER_GAMMA = 0.5772156649
def c(n):
"""Average path length of an unsuccessful search in a BST of n points."""
if n <= 1:
return 0.0
if n == 2:
return 1.0
return 2.0 * (np.log(n - 1) + EULER_GAMMA) - 2.0 * (n - 1) / n
def path_length(x, X, rng, depth=0, max_depth=8):
"""Path length of x in one random isolation tree grown on sample X."""
n = len(X)
if depth >= max_depth or n <= 1:
return depth + c(n)
spans = X.max(axis=0) - X.min(axis=0)
candidates = np.flatnonzero(spans > 0) # features that can still be split
if candidates.size == 0: # all remaining points are identical
return depth + c(n)
j = rng.choice(candidates)
split = rng.uniform(X[:, j].min(), X[:, j].max())
go_left = X[:, j] < split
if x[j] < split:
return path_length(x, X[go_left], rng, depth + 1, max_depth)
return path_length(x, X[~go_left], rng, depth + 1, max_depth)
rng = np.random.default_rng(0)
normal = rng.normal(size=(255, 2))
outlier = np.array([6.0, 6.0])
sample = np.vstack([normal, outlier]) # 256 points, so max depth is 8
typical = normal[0]
n_trees = 300
h_outlier = [path_length(outlier, sample, rng) for _ in range(n_trees)]
h_typical = [path_length(typical, sample, rng) for _ in range(n_trees)]
print("mean path length, outlier:", round(float(np.mean(h_outlier)), 2))
print("mean path length, typical:", round(float(np.mean(h_typical)), 2))
print("std path length, outlier:", round(float(np.std(h_outlier)), 2))
print("std path length, typical:", round(float(np.std(h_typical)), 2))The exact numbers depend on the seed, but the pattern is stable. The outlier's mean path length is clearly smaller than the typical point's, and both values have a visible standard deviation. That spread is why a single tree is unreliable.
Reading path lengths
Path length has no fixed meaning on its own. What counts as short depends on the sample size ψ, because c(ψ) grows roughly with ln ψ. This is why the score formula in a later chapter divides by c(ψ). Compare path lengths only between points scored by the same model.
Some patterns you will see:
- Short average path. The point is isolated by few cuts. It is far from the data, or it sits in a very sparse region.
- Path near c(ψ). The point is unremarkable. A random point in a random binary search tree takes about this many comparisons.
- Long average path. The point is in a dense core. In the depth-limited tree, many of these points hit the cap and get the max depth plus c(size).
Edge cases
Duplicates. If many copies of a point exist, they can never be separated. Their leaf holds all of them, and the c(size) term pushes their path length up. A repeated value is judged as normal even when it is far from everything else. If you have 40 identical copies of an extreme reading, the method treats it as a dense cluster.
Constant features. A feature with no spread inside the current node cannot split it. The code above skips such features. A feature that is constant over the whole dataset adds nothing but dilutes the random choice among features.
The depth cap flattens the deep end. Points in the core all end at or near the cap, so path length separates them poorly. This is intended: the method only needs to rank the shallow points, not tell core points apart.
Path length counts splits, not distance. A point that is twice as far away does not get a path half as long. After a point is separated from the main group, extra distance changes nothing. This is a reason the score saturates for extreme outliers.
Features with different scales. The split value is uniform over the feature's range inside the node, so the choice of feature is independent of its units. Rescaling a feature does not change which points get isolated early. Features with wide outliers can still affect how finely the range is cut, since one extreme value stretches the interval of split values.
Checking your understanding
Exercise
A tree is grown on a subsample of 256 points, so the depth limit is 8. A query point follows its branch for 8 edges and lands in a leaf that holds 5 training points. What is its path length h(x), given c(5) = 2(ln 4 + 0.5772) − 2·4/5 ≈ 2.55?
Show answer
The traversal stopped at the depth limit, so e = 8 and the leaf is not fully isolated. The correction is c(5) ≈ 2.55, giving h(x) ≈ 8 + 2.55 = 10.55.
Exercise
In the code above, why is it valid to follow only the branch that contains x instead of building the whole tree?
Show answer
The path of x depends only on the splits made on the points that reach the same node as x. Splits made on the other branch cannot affect where x goes. Discarding the other side at each step therefore gives the same distribution of h(x) as building the full tree and walking it.
Exercise
A dataset contains 30 identical copies of an extreme sensor reading. Explain why Isolation Forest may rate this reading as normal.
Show answer
Identical points cannot be separated by any split, so they stay together in one leaf. That leaf holds 30 points, so the c(30) correction makes the path length long. A long average path means a low anomaly score, so the repeated extreme value looks like part of a dense cluster.