Sub topic 2
Anomalies are few and different: the isolation idea
This chapter explains the single observation that Isolation Forest is built on. It assumes you know basic Python and NumPy, know what a decision tree is, and are comfortable with the idea of a feature matrix. Later chapters cover how the trees are built, how path length becomes a score, and how to run the model in scikit-learn. Here we only establish why the approach works, and we check it with a small simulation.
The usual approach: describe normal, then measure distance
Most anomaly detectors start by building a profile of normal data. They then flag points that fit the profile poorly. Common examples:
- Distance-based methods such as k-nearest neighbors flag points far from their neighbors.
- Density-based methods such as Local Outlier Factor flag points in regions of unusually low density.
- Model-based methods such as a Gaussian fit or a one-class SVM flag points with low likelihood or outside a learned boundary.
These methods share a cost. The model spends most of its effort describing normal points, and anomalies are only a side effect of that description. Distance and density methods also need pairwise comparisons, so their cost grows quickly with the number of rows. In high dimensions, distances also become less informative.
The isolation idea
Isolation Forest reverses the question. It does not ask "how well does this point fit normal?" It asks "how easy is it to separate this point from everything else?"
The method rests on two properties of anomalies:
- Anomalies are few. They make up a small share of the data.
- Anomalies are different. Their feature values differ from those of normal points.
Suppose you pick a feature at random, then pick a split value at random between that feature's minimum and maximum. Each split cuts the data into two groups. Repeat on whichever group still contains the point you care about.
- A point inside a dense cluster has many close neighbors. Each random split usually leaves several of them on the same side, so many splits are needed before the point is alone.
- A point far from the cluster sits in a sparse region. A random split often lands between it and the cluster, so very few splits are needed.
Because anomalies are few and different, they tend to be isolated in fewer random splits. The number of splits needed is the quantity the algorithm measures. The chapter on path length defines it precisely.
A simulation you can run
The following script uses one feature only. It draws 200 values from a standard normal distribution and adds one value at 8.0, which is far outside the cluster. It then repeatedly applies random splits, keeping only the side that contains the target, until the target is alone. It counts the splits and averages over many trials.
import numpy as np
def splits_to_isolate(values, target_index, rng):
"""Count random splits needed until the target value is alone."""
current = values.copy()
target = values[target_index]
count = 0
while len(current) > 1:
lo, hi = current.min(), current.max()
if lo == hi: # only duplicates remain; no split can separate them
break
split = rng.uniform(lo, hi)
if target < split:
current = current[current < split]
else:
current = current[current >= split]
count += 1
return count
rng = np.random.RandomState(0)
normal = rng.normal(loc=0.0, scale=1.0, size=200)
values = np.append(normal, 8.0)
anomaly_index = len(values) - 1
n_trials = 1000
anomaly_counts = [
splits_to_isolate(values, anomaly_index, rng) for _ in range(n_trials)
]
normal_counts = [
splits_to_isolate(values, rng.randint(0, 200), rng) for _ in range(n_trials)
]
print("mean splits, anomaly at 8.0:", np.mean(anomaly_counts))
print("mean splits, normal point :", np.mean(normal_counts))The first printed number is small, because the anomaly is isolated after only a few splits. The second is several times larger, because a typical normal point sits among many neighbors. The exact values depend on the seed, but the gap between them is the effect Isolation Forest exploits.
Two details matter in this script:
- The split value is drawn uniformly between the current minimum and maximum, not between the global ones. After the first split, the range shrinks to the surviving group.
- Randomness is the mechanism here. A single trial for one point can be misleading, because a lucky split may isolate a normal point quickly. Averaging over many trials removes that noise. The forest in a later chapter does the same thing by averaging over many random trees.
Why random splits are enough
You might expect a method that chooses splits at random to be too noisy to be useful. It works for two reasons.
The expected number of splits is a stable statistic. One random split sequence is noisy, but the average over many sequences is not. Points in sparse regions have a low average and points in dense regions have a high average.
No split is chosen to be good. A decision tree for classification picks splits that maximize a purity measure such as Gini impurity, and this needs labels. Isolation trees use no labels and no purity criterion. They do not need to learn what normal looks like. They only need to partition the space, and the geometry of the data decides which points are separated first.
This is also why the method is cheap. There is no distance matrix and no density estimate. Each split only needs a minimum and a maximum of one feature in the current node.
What "few and different" means in practice
Both conditions matter, and each fails in a different way.
| Situation | Effect on isolation | Typical result |
|---|---|---|
| Rare and far from the data | Isolated in few splits | Detected well |
| Rare but inside the normal range | Needs many splits, like normal points | Missed |
| Common but different | Many similar points cluster together | Behaves like a small normal cluster |
| Very close to a dense cluster edge | Slightly shorter paths than the interior | Weak signal |
The third row is the problem of masking. If there are many anomalies, they form their own dense group, and they become harder to isolate. The fourth row relates to swamping: normal points near an anomalous region get isolated early and look suspicious. A later chapter explains how subsampling reduces both effects, so we only name them here.
Common mistakes with the intuition
- Treating the anomaly as a class. The method has no concept of an anomalous class. It ranks points by how easily they separate. Whether a point is "an anomaly" depends on where you put a threshold, which is a separate decision.
- Expecting one tree to be reliable. The simulation above averaged 1000 trials for a reason. One isolation sequence can mislead.
- Assuming a high anomaly rate still works. The idea assumes anomalies are a small minority. If 30 percent of the rows are anomalous, they are no longer few, and they mask each other.
- Ignoring feature scale. Splits are drawn within each feature's own range, so scale itself does not distort the split choice. A feature that is mostly noise still takes a share of the random splits, though. Irrelevant features dilute the signal. The preprocessing chapter returns to this.
- Confusing "far" with "isolated". The simulation used a point far from the cluster. A small group of anomalies that sit together far away can still be isolated reasonably fast. Two or three such points are isolated more slowly than one, but still much faster than the cluster interior.
How this compares with distance-based thinking
A distance method needs a notion of "near", which means choosing a metric and often a neighborhood size. Isolation needs neither. A point is anomalous when random axis-aligned cuts quickly place it by itself. The word "axis-aligned" will come back in the limitations chapter, because it is also the method's main weakness. Each cut is perpendicular to one feature axis, so the method sees the data through those axes.
Exercise
In the simulation, you add a second point at 8.0 next to the first, so the data contains two identical outliers. Will the mean number of splits to isolate one of them go up, go down, or stay the same? Explain, and say what happens when lo == hi is reached.
Show answer
It goes up. With two identical points at 8.0, a split can no longer separate them, so the two always end up in the same group. That group is isolated from the cluster in a few splits, but it can never shrink to one element. When only the two duplicates remain, lo == hi, so the loop stops through the break and the count stops. Real implementations also stop at this point. The effect is a mild case of masking: anomalies that are copies of each other are harder to isolate as single points.
Exercise
Why does the method draw the split value between the minimum and maximum of the points currently in the node, rather than between the minimum and maximum of the whole dataset?
Show answer
Drawing from the whole dataset's range would often produce a split that leaves every current point on one side, so the split would do no work and the count would be inflated by empty cuts. Using the node's own range guarantees that each split separates at least one point from the others, so every counted split makes progress toward isolation.
Exercise
A dataset has 1000 normal points and 5 anomalies whose values on every feature lie well inside the normal range. Would you expect Isolation Forest to rank them highly? Why or why not?
Show answer
No. The anomalies are rare, but they are not different in feature space. They sit in dense regions, so random splits separate them no faster than their neighbors. Both conditions, few and different, are needed for short isolation paths.