Sub topic 6
Why Subsampling Helps: Swamping and Masking
This chapter assumes you know how an isolation tree is built, what path length means, and how the anomaly score s(x, n) = 2^(-E[h(x)] / c(n)) is computed. It explains why Isolation Forest trains each tree on a small random subsample (256 points by default) instead of the full dataset. The reason is not only speed. Subsampling makes the detector more accurate.
Two failure modes of dense data
Isolation works because anomalies are few and different. Real datasets break both assumptions in two ways.
- Swamping is when normal points are wrongly flagged as anomalies. It happens when normal points lie close to anomalies. Random splits that separate an anomaly also tend to cut away its normal neighbors, so those neighbors get short paths too.
- Masking is when anomalies hide each other. It happens when many anomalies form a dense cluster. The cluster behaves like a small group of "normal" points. A tree needs many splits to separate any one member from the rest, so each member gets a long path and a low score.
Both problems grow with the number of points in the region around the anomalies. A large sample gives a large cluster, and a large cluster takes more splits to break up.
What subsampling changes
Each tree in the forest is built from a sample of ψ points (max_samples in scikit-learn) drawn from the n training points. Two effects follow.
- A dense anomaly cluster shrinks. If a cluster has m points among N total, a sample of ψ points contains about m·ψ/N of them. A cluster of 300 points in 10,000 becomes about 7 or 8 points in a sample of 256. Seven points are easy to isolate, so masking weakens.
- The normal points near an anomaly thin out. The normal neighbors that would be cut away along with an anomaly are mostly absent from the sample. Swamping weakens too.
The sample is also random, so each tree sees a different thinned-out version of the data. Averaging path lengths over the forest smooths out the noise from any single sample.
The side benefits: cost and depth
Subsampling also bounds the cost of the algorithm.
- Tree depth is capped. The original paper limits each tree to a height of
ceil(log2(ψ)). Isolating a point that ends up deep in a tree is a sign of normality, so the algorithm does not need to grow the tree further. For ψ = 256 the limit is 8 splits. - Training cost does not depend on N. With t trees, training is roughly O(t · ψ · log ψ). Doubling the dataset does not double the training time.
- Memory is small. Each tree stores at most about 2ψ nodes.
- Scoring uses the same ψ. The normalizing term
c(ψ)in the score formula uses the sample size, not the dataset size. Theanomaly_scorefunction from the earlier chapter takesnas its second argument. In a trained forest that value is ψ.
Because every tree is capped at the same depth, the paths are comparable across trees. The score for a point is the mean of path lengths that were all measured under the same rules.
Seeing the effect in code
The following script builds a dataset with a dense anomaly cluster, which is the masking case. It trains forests with different max_samples values and compares ROC AUC. Run it and compare the numbers on your machine. The exact values depend on the random seed and the scikit-learn version.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score
rng = np.random.RandomState(0)
# 5000 normal points around the origin
X_normal = rng.normal(loc=0.0, scale=1.0, size=(5000, 2))
# 300 anomalies packed into a tight cluster far from the origin (masking risk)
X_cluster = rng.normal(loc=5.0, scale=0.3, size=(300, 2))
# 50 scattered anomalies
X_scatter = rng.uniform(low=-8.0, high=8.0, size=(50, 2))
X = np.vstack([X_normal, X_cluster, X_scatter])
y_true = np.r_[np.zeros(len(X_normal)), np.ones(len(X_cluster) + len(X_scatter))]
for max_samples in [32, 256, 1024, len(X)]:
clf = IsolationForest(
n_estimators=200,
max_samples=max_samples,
random_state=0,
).fit(X)
anomaly_scores = -clf.score_samples(X) # higher = more anomalous
auc = roc_auc_score(y_true, anomaly_scores)
print(f"max_samples={max_samples:5d} ROC AUC={auc:.3f}")When max_samples equals the full dataset, the cluster of 300 points is present in every tree at full size. Each cluster member sits in a group of about 300 close neighbors, so it needs more splits to isolate than a lone anomaly does. In the smaller samples the same cluster has far fewer members, so its points are isolated sooner. Expect the smaller settings to separate the cluster better. Expect the smallest setting to show some loss from the other direction, which the next section covers.
Subsampling is not free
Smaller is not always better. A sample can be too small to represent the normal region.
- Noisy structure. With ψ = 8 or 16, the tree only sees a rough outline of the normal data. A few normal points in the tails can look isolated by chance. Scores become noisy, and you need more trees to average the noise out.
- Rare normal modes disappear. If the data has a small but legitimate group of normal points (for example 1% of traffic from a rarely used device), a small sample may include zero or one of them. Those points then look like anomalies. This is a form of swamping caused by sampling.
- Cap by dataset size.
max_samplescannot exceed the number of training points when given as an integer. The default"auto"usesmin(256, n_samples).
The default of 256 comes from the original paper, which found that path lengths converge at around that size for many datasets, so a larger sample adds cost without improving detection. Treat it as a good starting point and not a rule. Datasets with several distinct normal modes, or many dimensions, may benefit from a larger value. Check this with a labeled validation set when you have one, as in the evaluation chapter.
Practical settings
| Situation | Suggested adjustment |
|---|---|
| Default behavior, unknown data | Keep `max_samples="auto"` (256) |
| Suspected dense anomaly cluster (masking) | Try smaller values such as 64 or 128 and compare with labels or manual review |
| Many legitimate rare normal groups (swamping) | Try larger values such as 512 or 1024 |
| Scores differ between runs | Increase `n_estimators`, or fix `random_state` |
| Dataset has fewer than 256 rows | `"auto"` uses all rows, so there is no thinning effect |
Two further details matter in practice.
max_samplesalso accepts a float between 0 and 1, which means a fraction of the training rows. A fraction scales with N, which weakens the cost benefit. An integer keeps the sample size fixed as the data grows.- By default
bootstrap=False, so each tree samples without replacement, which matches the paper. Sampling with replacement can place the same point in a sample twice, and a duplicated point is harder to isolate.
Summary
Swamping flags normal points near anomalies. Masking lets anomaly clusters hide themselves. Training each tree on a small random sample reduces both, because the sample contains fewer cluster members and fewer neighbors. It also caps tree depth and makes training cost independent of dataset size. The price is noisier trees, which the ensemble average mostly absorbs, and a risk of missing rare normal modes when ψ is too small.
Exercise
A dataset has N = 20,000 rows. It contains a dense cluster of 400 anomalies. You train an Isolation Forest with maxsamples=256. On average, how many cluster points does each tree see, and why does that reduce masking? What risk comes from making maxsamples much smaller, such as 8?
Show answer
Each tree sees about 400 × 256 / 20,000 = 5.12 cluster points. Five points in a sample are easy to separate with a few random splits, so they get short paths and high scores. In the full data, a cluster of 400 would take many more splits to break up, so its members would get long paths and look normal. With max_samples=8, a tree sees only a rough outline of the normal data. Normal points in the tails, and members of rare normal groups, can look isolated by chance. This causes swamping and noisy scores, so more trees are needed to average the noise out.