Sub topic 3
Building an isolation tree with random splits
This chapter shows how one isolation tree is built. You will implement the construction in NumPy and see why points in sparse regions end up near the root. It assumes you know Python and NumPy, have seen decision trees, and are comfortable with logarithms. You do not need to know how a forest combines trees. That comes in a later chapter.
What an isolation tree is
An isolation tree (iTree) is a binary tree that recursively splits a sample of data until points are alone in their own leaves. It differs from a supervised decision tree in three ways:
- It has no labels and no target.
- It does not look for the best split. It picks the feature at random and the split value at random.
- It does not try to make leaves pure. It stops when a point is isolated or when a depth limit is reached.
The tree is not a good model of the data by itself. What matters is how deep each point lands. A point in a dense cluster needs many random cuts before it is alone. A point far from the others is often alone after only a few cuts.
The construction procedure
Start with a sample of psi points, held in a matrix with one row per point and one column per feature. Build the tree recursively. At each node, with the points that reached it:
- If the node holds one point or fewer, stop and make it a leaf.
- If the node is at the depth limit, stop and make it a leaf.
- If all points in the node are identical in every feature, stop and make it a leaf. No split could separate them.
- Otherwise pick a feature
qat random. Draw a split valuepuniformly between the minimum and maximum of featureqamong the points in this node. - Send points with
x[q] < pto the left child and the rest to the right child. Recurse on each child with depth increased by one.
The split range uses only the points currently in the node, not the whole dataset. As the tree gets deeper, cuts fall inside ever smaller boxes of feature space.
Why the depth limit exists
The tree is capped at height ceil(log2(psi)), which is the depth of a balanced binary tree with psi leaves. This cap has two purposes.
First, it saves work. Isolating a normal point in the middle of a dense cluster could take many levels, and normal points are not the ones we care about. We only need the tree to tell short paths from long ones.
Second, the cap loses no information, because the path-length formula compensates for it. A leaf that still holds several points is treated as if the tree had continued, and its depth is increased by an estimate of the missing levels. That estimate is the term c(n) for the n points left in the leaf. You will use it in the code below and meet it again in the chapter on the anomaly score.
| Stopping condition | Why it applies |
|---|---|
| One point or fewer | The point is isolated. |
| Depth equals `ceil(log2(psi))` | Normal points would only get deeper. The cap bounds cost. |
| All rows identical | No split value can separate them. |
Implementation from scratch
The code below builds one tree and measures the path length of a query point. The helper c(n) is the average path length of an unsuccessful search in a binary search tree of n points. It is the same formula used in the original Isolation Forest paper.
import numpy as np
EULER_GAMMA = 0.5772156649
def c(n):
"""Expected extra depth for a leaf that still holds 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
class Node:
def __init__(self, size, feature=None, split=None, left=None, right=None):
self.size = size
self.feature = feature
self.split = split
self.left = left
self.right = right
@property
def is_leaf(self):
return self.left is None
def build_tree(X, depth, max_depth, rng):
n = X.shape[0]
if n <= 1 or depth >= max_depth:
return Node(size=n)
lo = X.min(axis=0)
hi = X.max(axis=0)
candidates = np.flatnonzero(hi > lo) # features that can still be split
if candidates.size == 0: # all rows identical
return Node(size=n)
feature = rng.choice(candidates)
split = rng.uniform(lo[feature], hi[feature])
mask = X[:, feature] < split
return Node(
size=n,
feature=feature,
split=split,
left=build_tree(X[mask], depth + 1, max_depth, rng),
right=build_tree(X[~mask], depth + 1, max_depth, rng),
)
def path_length(x, node, depth=0):
if node.is_leaf:
return depth + c(node.size)
child = node.left if x[node.feature] < node.split else node.right
return path_length(x, child, depth + 1)
rng = np.random.RandomState(0)
X = rng.normal(size=(500, 2))
psi = 256
max_depth = int(np.ceil(np.log2(psi))) # 8
normal_point = np.array([0.0, 0.0])
outlier = np.array([6.0, 6.0])
normal_depths, outlier_depths = [], []
for _ in range(200):
sample = X[rng.choice(len(X), size=psi, replace=False)]
tree = build_tree(sample, 0, max_depth, rng)
normal_depths.append(path_length(normal_point, tree))
outlier_depths.append(path_length(outlier, tree))
print("mean path, point at the center:", np.mean(normal_depths))
print("mean path, far outlier: ", np.mean(outlier_depths))One tree gives a noisy answer. The code averages over 200 trees, each built on a fresh random sample, so you can see the pattern. The point at the center should show a clearly larger mean path length than the far point. Exact values depend on the seed. This is a small version of the forest idea in a later chapter.
Walking through why the outlier lands early
Consider the root of a tree built on the data above. The root node covers the whole sample, so the range on each feature is about -3 to +3. The outlier at (6, 6) is outside the sampled range, but a query point can still be routed. At each split it goes to whichever side of the cut it falls on. Because it lies beyond the maximum on both features, it always goes right.
The decisive point is what happens to the data points near it. Any sample points that sit on the far edge of the cloud are few. A random cut has a high chance of falling between them and the bulk of the data. Once a cut separates them, the child holding them is small and soon becomes a leaf. A query point that falls into that small leaf gets a short path.
The dense center behaves the opposite way. Cuts through the cluster keep leaving many points on both sides, so the center needs close to the full depth.
Edge-of-cloud points get short paths because the range of each cut is set by the minimum and maximum. A few extreme points stretch that range, so many random cuts fall in the empty gap and shave off the extreme points at once.
Edge cases and gotchas
- Duplicates. If many rows are identical, they can never be separated. The "all rows identical" rule makes them one leaf of size
n. Thec(n)adjustment then gives them a longer path, which is what you want for repeated normal values. - Constant features. A feature with the same value in a node is excluded from the choice. Without that filter you would draw
pfrom an empty range and waste splits. The code above filters withhi > lo. - Empty children.
rng.uniform(lo, hi)can return exactlylo, which would send every point right. This is extremely unlikely with floats. The depth cap still ends the recursion, and a size-0 leaf getsc(0) = 0. - Scale does not matter for choosing the split value. The cut is uniform within each feature's own range, so rescaling one feature does not change where the cut falls relative to the points. Feature choice is uniform, not weighted by range.
- Cuts are axis-parallel. Each cut involves one feature. This shapes the regions the tree can carve and causes artifacts that a later chapter on limitations covers.
- Recursion depth. The depth cap keeps recursion shallow, so Python's recursion limit is not a concern here.
The scikit-learn IsolationForest follows the same recipe. Each tree is trained on a subsample, picks one random feature per split, draws a uniform split value in the node's range, and stops at ceil(log2(max_samples)) depth. Its internals are compiled code rather than a Python class like the one above, but the logic is the same.
Summary of the key ideas
- An isolation tree splits a subsample using a random feature and a uniform random value within the node's current range.
- It stops at isolation, identical rows, or depth
ceil(log2(psi)). - A point's path length is the number of edges from the root to its leaf, plus
c(leaf size)when the leaf holds more than one point. - Points in sparse regions tend to reach leaves after fewer cuts. A single tree is noisy, so many trees are combined.
Exercise
You build an isolation tree on a subsample of psi = 128 points and a query point ends in a leaf at depth 5 that holds 4 training points because the other stopping rules did not apply. (a) What is the depth cap? (b) What is the path length you should report, using c(4) ≈ 2.0 (ln 3 + 0.5772) - 2.0 3 / 4?
Show answer
(a) The cap is ceil(log2(128)) = 7. (b) Since the leaf holds more than one point, add c(4) to the depth. c(4) = 2.0 (1.0986 + 0.5772) - 1.5 = 2.0 1.6758 - 1.5 ≈ 1.85. The path length is 5 + 1.85 ≈ 6.85. The adjustment accounts for the splits that would have been needed to separate the 4 points.
Exercise
In the code above, a feature has hi == lo among the points at a node. Why is it removed from the candidate list instead of being chosen and used for a split anyway?
Show answer
The split value is drawn uniformly between lo and hi. When they are equal, every point has the same value on that feature, so any cut sends all points to one side and leaves the other child empty. The split wastes a level and does not separate anything. Filtering to features with hi > lo guarantees that each split can divide the data. If no such feature exists, all rows are identical and the node becomes a leaf.