Sub topic 10
Tuning n_estimators, max_samples and max_features
This chapter assumes you can run IsolationForest in scikit-learn and read score_samples. It also assumes you know that each isolation tree is built on a random subsample, with random feature and split choices. Here you will learn what the three main size parameters do, how to pick values, and how to check your choice.
What each parameter controls
Each parameter changes a different part of the forest.
| Parameter | Default | Controls | Main effect |
|---|---|---|---|
| `n_estimators` | 100 | Number of trees | Variance of the averaged path length |
| `max_samples` | `"auto"` | Points drawn for each tree | Tree depth, swamping and masking, bias |
| `max_features` | 1.0 | Features drawn for each tree | Which dimensions can drive splits |
max_samples="auto" means min(256, n_samples). An integer is an absolute count. A float is a fraction of the training rows. The tree height limit is ceil(log2(max_samples)), so the subsample size also sets how deep a tree can go.
max_features takes an integer (a feature count) or a float (a fraction of the columns). Features are drawn per tree, not per split. Once a tree has its feature subset, each split picks one of those features at random.
Tuning n_estimators: a variance knob
The anomaly score uses the average path length over all trees. More trees reduce the random noise in that average. They do not change what the model learns on average.
The effect is a diminishing return. Going from 10 to 100 trees helps a lot, and going from 300 to 1000 helps very little. Training and scoring time grow linearly with the number of trees. Because the trees are independent, you can set n_jobs=-1 to build them in parallel.
You can measure this without labels. Fit two forests with different seeds and compare how they rank the points. If the rankings agree closely, extra trees will not change your results.
import numpy as np
from scipy.stats import spearmanr
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(0)
X = np.vstack([rng.normal(size=(2000, 2)), rng.uniform(-6, 6, size=(100, 2))])
for n_estimators in [10, 50, 100, 300, 1000]:
a = IsolationForest(n_estimators=n_estimators, random_state=1).fit(X).score_samples(X)
b = IsolationForest(n_estimators=n_estimators, random_state=2).fit(X).score_samples(X)
rho = spearmanr(a, b).correlation
print(f"n_estimators={n_estimators:5d} rank agreement between seeds: {rho:.4f}")The agreement rises quickly and then flattens. The exact numbers depend on your data. Choose the smallest value where the curve is flat. For most tabular data that is between 100 and 300 trees.
Tuning max_samples: a bias knob
The original paper recommends a subsample of 256. This is a trade-off, not a limit of the algorithm. Subsampling counters two problems:
- Swamping: normal points that lie near anomalies get isolated too early because they look abnormal next to them.
- Masking: a large cluster of anomalies makes each of them harder to isolate, because the points shield each other.
Both problems get worse as the sample grows, because more points fill the gaps between normal data and anomalies. A small sample gives each tree a cleaner picture.
The trade-off cuts the other way too. If the sample is too small, the tree cannot describe the normal region well. This matters most when normal data has several modes or fine structure, or when the anomaly rate is very low. With a very small sample, an anomaly may not appear in the tree's data at all. Rare, subtle anomalies can then score poorly.
Values to try:
- Start with the default (256).
- Try 64 and 128 if you suspect clustered anomalies (masking).
- Try 512 to 2048 if the normal data has complex structure and the dataset is large.
- Using all rows (
max_samples=1.0) rarely helps and costs more time.
Setting max_samples larger than the number of rows triggers a warning, and scikit-learn falls back to using all rows.
Tuning max_features: relevance in high dimensions
With max_features=1.0, every tree can split on every column. If most columns are noise, many splits are wasted on features that carry no signal. Each tree takes longer to isolate real anomalies, and the score gets noisier. Reducing max_features gives each tree fewer, but randomly chosen, columns. The ensemble still covers all features across the forest.
A lower value is not a fix for irrelevant features. It only dilutes them a little. It can also hurt when an anomaly is visible in only one or two columns. Trees that do not draw those columns cannot see it. Removing or down-weighting noise features before training is usually more effective.
A sweep you can run
The script below uses labels to test both parameters. In real use you will often lack labels, so run it on a labeled sample, a synthetic injection test, or a past incident set.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score, average_precision_score
rng = np.random.RandomState(0)
n_normal, n_out = 2000, 100
# Two informative features plus 20 pure-noise features
informative = np.vstack([
rng.normal(size=(n_normal, 2)),
rng.uniform(-6, 6, size=(n_out, 2)),
])
noise = rng.normal(size=(n_normal + n_out, 20))
X = np.hstack([informative, noise])
y_true = np.r_[np.zeros(n_normal), np.ones(n_out)]
def evaluate(**params):
clf = IsolationForest(n_estimators=200, random_state=0, n_jobs=-1, **params).fit(X)
s = -clf.score_samples(X) # higher = more anomalous
return roc_auc_score(y_true, s), average_precision_score(y_true, s)
print("max_samples sweep")
for ms in [16, 64, 256, 1024, n_normal + n_out]:
auc, ap = evaluate(max_samples=ms)
print(f" max_samples={ms:5d} AUC={auc:.3f} AP={ap:.3f}")
print("max_features sweep")
for mf in [1.0, 0.5, 0.25, 0.1]:
auc, ap = evaluate(max_features=mf)
print(f" max_features={mf:4.2f} AUC={auc:.3f} AP={ap:.3f}")Read the output as a comparison, not as a ranking of settings that transfers to other data. In this data the anomalies are scattered uniformly and only two of 22 columns carry signal, so the effect of max_features may be small or even negative. If you see no change, that is a valid result: the default is fine.
A practical tuning order
The parameters interact weakly, so tune them one at a time in a sensible order.
Common errors
- Tuning to a single seed. A difference of 0.002 in AUC between two settings is usually seed noise. Repeat each setting with several
random_statevalues and compare the means. - Judging
n_estimatorsby AUC alone. AUC can look flat while the top-ranked points still reorder between runs. Check rank agreement between seeds, as in the first script. - Treating
max_samplesas a training-set size. It is a per-tree sample. A larger dataset does not require a largermax_samples. Doubling the data may leave the best value unchanged, at around 256. - Changing
contaminationwhile tuning size parameters.contaminationonly moves the cut point used bypredict. It does not changescore_samples, so it has no effect on AUC or AP. Tune the threshold separately. - Forgetting
random_state. Without it, repeated runs give different scores, and you cannot compare settings fairly.
Exercise
You fit two forests with different seeds. The Spearman rank correlation between their scores is 0.82 at nestimators=50 and 0.99 at nestimators=300. A teammate suggests going to 5000 trees. What do you recommend, and what would you tune next if the detector still misses clustered anomalies?
Show answer
Stay near 300 trees. The rankings already agree at 0.99 across seeds, so 5000 trees would cost about 16 times the compute for almost no change in results. If clustered anomalies are still missed, the likely cause is masking, so lower max_samples (for example from 256 to 64 or 128) and re-run the sweep with several seeds, comparing AUC and AP on labeled data.