Sub topic 10
Tuning n_estimators, max_samples and max_features
This chapter assumes you can fit an IsolationForest in scikit-learn, know that the anomaly score comes from average path length, and understand why each tree is trained on a subsample. Here you will learn what the three main size parameters change and how to choose them.
How the parameters fit together
Each isolation tree is built from a random subsample of the data. Three parameters control the shape of the forest.
| Parameter | Default | Controls |
|---|---|---|
| `n_estimators` | 100 | Number of trees averaged into the score |
| `max_samples` | `"auto"` (min(256, n_samples)) | Rows drawn for each tree |
| `max_features` | 1.0 | Share of columns drawn for each tree |
The tree depth limit follows from max_samples. It is set to about ceil(log2(max_samples)), because anomalies are expected to isolate early and deeper splits add little.
n_estimators: variance, not bias
More trees reduce the noise in the average path length. They do not change what the model can detect. The paper reports that path lengths converge well before 100 trees, so the default is usually enough.
The practical test is stability. Fit the model with different seeds and check whether the ranking of points changes. If it does, add trees.
import numpy as np
from sklearn.ensemble import IsolationForest
from scipy.stats import spearmanr
rng = np.random.RandomState(0)
X = np.vstack([rng.normal(size=(1000, 4)),
rng.uniform(-6, 6, size=(50, 4))])
for n in (10, 50, 100, 400):
runs = []
for seed in (1, 2):
clf = IsolationForest(n_estimators=n, random_state=seed).fit(X)
runs.append(-clf.score_samples(X))
rho = spearmanr(runs[0], runs[1]).correlation
print(f"n_estimators={n:4d} rank agreement between seeds: {rho:.3f}")Agreement should rise with n_estimators and flatten. Pick the smallest value where it flattens, since training and scoring time grow linearly with the number of trees.
max_samples: the most influential setting
max_samples sets how many rows each tree sees. It can be an integer (a row count) or a float (a fraction of the data).
Small subsamples work because they reduce two problems:
- Swamping: normal points near anomalies get mistaken for anomalies.
- Masking: a dense cluster of anomalies looks normal because it needs many splits to separate.
Raising max_samples is not a safe default for "more accuracy". With a very large subsample, anomalies form clusters that mask each other and the trees grow deeper without gaining information. With a very small one, the trees see too little of the normal structure and scores get noisy.
Start with 256. Try larger values only if the data has many distinct normal modes, or if anomalies are rare and tiny samples often contain none of the normal structure around them.
max_features: use with care
The default of 1.0 gives every tree all columns. Lowering it makes each tree split on only some columns, which adds diversity. This can help when many features are noise, because a tree that never sees an informative column contributes uninformative path lengths.
Note that the original algorithm picks a feature at random at every split. In scikit-learn max_features limits the columns drawn for each tree, and each split then picks among those. With few columns, reducing it usually hurts.
Comparing settings
With labels, compare settings by average precision, as in the evaluation chapter. Without labels, use rank stability across seeds. Do not compare raw score values between settings, because the normalization depends on max_samples.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import average_precision_score
rng = np.random.RandomState(0)
X = np.vstack([rng.normal(size=(1000, 4)),
rng.uniform(-6, 6, size=(50, 4))])
y = np.r_[np.zeros(1000), np.ones(50)]
for ms in (32, 64, 256, 1024):
clf = IsolationForest(max_samples=ms, random_state=0).fit(X)
ap = average_precision_score(y, -clf.score_samples(X))
print(f"max_samples={ms:5d} average precision={ap:.3f}")Exercise
Your model gives different top-10 anomalies each time you change randomstate. Which parameter do you adjust first, and why not maxsamples?
Show answer
Increase nestimators. Seed-to-seed variation is variance from averaging too few trees. maxsamples changes what each tree can see and therefore the model itself, so changing it would alter the results instead of stabilizing them.
Exercise
Why is the raw score from scoresamples not comparable between a model with maxsamples=64 and one with max_samples=1024?
Show answer
The score divides the average path length by c(n), which depends on the subsample size. Each model therefore uses a different normalization, so only rankings or metrics such as average precision should be compared.