Sub topic 5
From One Tree to a Forest
This chapter assumes you know how a single isolation tree is built from random feature and split-value choices, and that path length is the number of edges from the root to the node where a point ends up. You should also be comfortable with Python and NumPy, and with the idea that an ensemble averages many weak models. Here you will see why one tree is not enough and how a forest of them gives a stable score.
Why a single tree is not reliable
An isolation tree chooses every split at random. It picks a feature at random, then picks a split value uniformly between the minimum and maximum of that feature among the points at the current node. This randomness is what makes the method fast, but it also makes any one tree noisy.
Suppose a normal point sits near the center of a cluster. In most trees it needs many splits to be isolated. In one unlucky tree, the first random split may happen to land right beside it, and it is isolated after two steps. That one tree would call the point an anomaly. The reverse can also happen: a true outlier may survive a few splits because the random cuts fell in empty space.
The path length of a point is therefore a random variable. A single draw from it tells you little. The expected path length, which is the mean over many random trees, tells you much more.
The ensemble idea
An Isolation Forest is a set of t independent isolation trees. Each tree is grown on its own random sample of the training data. For a query point x, you compute the path length h_i(x) in every tree i, then average:
E[h(x)] = (1 / t) * (h1(x) + h2(x) + ... + h_t(x))
This average is the quantity that the anomaly score uses. Points with a small average path length are easy to isolate and are likely anomalies. Points with a large average path length are hard to isolate and are likely normal.
Averaging works for the same reason it works in a random forest. The trees make independent random errors, so the errors tend to cancel. The variance of the mean falls roughly in proportion to 1/t. Unlike a random forest classifier, though, there are no labels and nothing is being fit to a target. Each tree is just an independent random partition of the space, so the forest estimates a property of the data distribution, namely how isolated each region is.
Building the forest
Training has two nested loops: one over trees, and inside each, a recursive split procedure.
- Choose the number of trees t and the subsample size psi.
- For each tree, draw psi points from the training data.
- Set a height limit of ceil(log2(psi)). Grow the tree by random splits until a node holds one point, all its points are identical, or the height limit is reached.
- Store the trees. No other model state is needed.
The height limit is a deliberate shortcut. Anomalies have short paths, so you only care about the top of the tree where they are separated. Growing the tree to full depth would spend time on the dense regions that you already know are normal. The limit is about the depth of a balanced tree on psi points, so average-depth points end up near it.
When a path stops at a node that still holds more than one point because of the height limit, the path length is adjusted. You add c(size), the expected extra depth that a full tree would need to separate that many points. The chapter on the anomaly score gives the formula for c. Without this correction, a point in a dense, truncated leaf would look easier to isolate than it really is.
Scoring a point
To score a query point, send it down each tree following the stored split rules. Count the edges to the leaf, add the c(size) correction if the leaf holds several points, and collect one number per tree. Then average.
Scoring costs O(t log psi) per point, since each path is at most about log2(psi) long. Training costs O(t psi log psi). Neither depends on the full dataset size n, which is why Isolation Forest scales well to large data.
A runnable comparison: one tree versus many
The following code uses scikit-learn's IsolationForest with different values of n_estimators and measures how much the scores change between runs with different seeds. A forest with more trees should give more stable scores.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(42)
X_normal = rng.normal(loc=0.0, scale=1.0, size=(500, 2))
X_outliers = rng.uniform(low=-6.0, high=6.0, size=(25, 2))
X = np.vstack([X_normal, X_outliers])
for n_trees in [1, 5, 25, 100, 400]:
runs = []
for seed in range(10):
clf = IsolationForest(n_estimators=n_trees, random_state=seed).fit(X)
runs.append(clf.score_samples(X))
runs = np.array(runs) # shape (10, n_points)
spread = runs.std(axis=0).mean() # mean std of each point's score across seeds
print(f"n_estimators={n_trees:4d} mean score std across seeds = {spread:.4f}")The printed spread shrinks as the number of trees grows. With one tree, the score of a point changes a lot from seed to seed. With a few hundred trees, it barely moves. Exact numbers depend on your scikit-learn version, but the downward trend is reliable.
How many trees are enough?
The original paper observed that path lengths converge quickly, often before 100 trees, and that 100 trees is a sound default. This matches the scikit-learn default of n_estimators=100. The cost of more trees is linear in time and memory, while the gain falls off, so the curve flattens.
Practical guidance:
- Start at 100. Increase to 200 or 500 if scores for borderline points change between random seeds.
- If you need to rank points and the top of the ranking matters, check stability by fitting with two seeds and comparing the top-k sets.
- If you only need a coarse flag, fewer trees can be enough.
- Set
random_statefor reproducible results, and say so in reports.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Judging a point from one tree's path | Very noisy flags | Always average over the forest |
| Using too few trees on a small dataset | Scores differ between runs | Raise `n_estimators`, set `random_state` |
| Growing trees to full depth in your own implementation | Wasted time, no accuracy gain | Apply the height limit of ceil(log2(psi)) |
| Forgetting the c(size) correction in a custom version | Truncated leaves look too easy to isolate | Add c(size) to the path length |
| Assuming more trees fix a bad subsample size or poor features | Scores stay biased | Tune `max_samples` and features separately |
More trees reduce variance but not bias. If the data has structure that axis-parallel random splits cannot capture, a larger forest only gives you a more stable version of the same flawed answer. Later chapters on limitations return to this point.
Independence between trees
The variance argument assumes trees are close to independent. In an Isolation Forest this holds well. Each tree has its own subsample and its own random splits, and no tree depends on another's errors, as happens in boosting. Because trees are independent, training and scoring parallelize easily. In scikit-learn you can set n_jobs to use several cores.
Trees are not fully independent, since they are drawn from the same dataset. A single extreme point that appears in many subsamples affects many trees. The next chapter explains why drawing small subsamples reduces this overlap and helps detection.
Exercise
A forest has 4 trees. For a query point, the path lengths are 3, 5, 4 and 8. What is the mean path length E[h(x)], and why is it a better basis for scoring than the first tree's path of 3 alone?
Show answer
The mean is (3 + 5 + 4 + 8) / 4 = 5. A single tree's path is one random draw and can be short or long by chance, because splits are random. The average over trees reduces that variance, so the score reflects how isolated the point typically is rather than how it fared in one random partition.
Exercise
Why does an Isolation Forest limit tree height to ceil(log2(psi)), and what must you add to a path that ends at a truncated leaf holding several points?
Show answer
Anomalies are isolated near the top of a tree, so deeper splits mostly describe dense normal regions and add cost without improving detection. When a path ends at a leaf that still holds several points, add c(size), the expected path length needed to separate that many points, so the truncated leaf is not mistaken for an easily isolated point.