Sub topic 13
Limitations: Axis-Parallel Splits, High Dimensions, Drift
This chapter assumes you can fit an IsolationForest, read score_samples, and compute ROC AUC, as covered in the earlier chapters. It also assumes you know how a tree splits a node on one feature at a time.
Isolation Forest is fast and needs little tuning. Those strengths come from design choices: random axis-aligned cuts, subsampling, and a model fixed at fit time. Each choice also produces a failure mode. You need to recognize these failures before you trust a score in production.
Axis-parallel splits
Every split in an isolation tree has the form feature_j < threshold. Each cut is parallel to a coordinate axis, so a node always covers a rectangle (a box in higher dimensions). Regions of the score surface therefore follow axis-aligned boxes, even when the data's shape is diagonal or curved.
Two consequences follow:
- Ghost regions. When two clusters sit on a diagonal, the empty corners of their bounding box are cut by the same splits that separate the clusters. Points in those corners can look less abnormal than their distance from the data suggests.
- Rotation sensitivity. Rotating the feature space changes which points are easy to isolate. A distance-based method gives the same answer after a rotation. Isolation Forest does not.
The next script places two blobs on a diagonal and scores four probe points. For each probe it prints the share of training points that the forest considers more abnormal.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(0)
blob_a = rng.normal(loc=[-3.0, -3.0], scale=0.5, size=(300, 2))
blob_b = rng.normal(loc=[3.0, 3.0], scale=0.5, size=(300, 2))
X = np.vstack([blob_a, blob_b])
clf = IsolationForest(n_estimators=200, random_state=0).fit(X)
train_scores = clf.score_samples(X)
probes = {
"inside blob (3, 3)": [3.0, 3.0],
"midpoint (0, 0)": [0.0, 0.0],
"empty corner (3, -3)": [3.0, -3.0],
"far away (8, -8)": [8.0, -8.0],
}
for name, point in probes.items():
s = clf.score_samples(np.array([point]))[0]
more_abnormal = (train_scores < s).mean()
print(f"{name:22s} score={s:.3f} training points more abnormal: {more_abnormal:.1%}")The corner (3, -3) is 6 units from the nearest blob center. The midpoint (0, 0) is about 4.2 units from both. A distance-based detector would rank the corner as more anomalous. Run the script and check whether the forest agrees. Then rotate X by 45 degrees and rerun it to see how the ranking changes.
High dimensions and irrelevant features
At each node the tree picks a feature uniformly at random. It does not look for informative features. If only 2 of 100 features carry the anomaly signal, about 98% of the splits at any node are spent on noise. Anomalies then take longer to isolate, and their path lengths move toward those of normal points.
Distances also concentrate as dimension grows. Even when a point is extreme in a few features, the forest's average over many noisy splits washes out the difference.
The script below adds pure-noise columns and measures ROC AUC. The anomalies are shifted only in the first two features.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score
rng = np.random.RandomState(1)
n_normal, n_anom = 1000, 50
for n_noise in [0, 10, 50, 200]:
normal = rng.normal(size=(n_normal, 2 + n_noise))
anomalies = rng.normal(size=(n_anom, 2 + n_noise))
anomalies[:, :2] += 4.0 # signal lives in the first two features only
X = np.vstack([normal, anomalies])
y = np.r_[np.zeros(n_normal), np.ones(n_anom)]
clf = IsolationForest(random_state=1).fit(X)
auc = roc_auc_score(y, -clf.score_samples(X))
print(f"noise features: {n_noise:3d} ROC AUC: {auc:.3f}")Expect AUC to decline as n_noise grows. The exact numbers depend on the seed.
What helps:
- Feature selection. Remove columns with no link to the behavior you want to detect. This is the most effective fix.
- Dimensionality reduction. PCA or an autoencoder can compress correlated features before the forest. Check that the reduction does not discard the signal.
- Several detectors. Train separate forests on feature groups that belong together, such as one for network features and one for timing features. Combine their scores.
max_features. Lowering it below 1.0 does not fix the dilution. It only changes which features each tree sees.
Drift and a fixed model
IsolationForest learns its trees and a score cutoff (offset_) once, at fit. It has no mechanism to update them. When the data distribution changes after training, which is called drift, two things go wrong:
- Normal new behavior falls outside the old boxes and gets flagged. The alert rate rises without any real anomalies.
- A new kind of anomaly may sit inside a region that was dense in the training data and go unnoticed.
The next script fits on one window and applies the model to a window whose mean has shifted.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(7)
train = rng.normal(loc=0.0, size=(2000, 2))
same = rng.normal(loc=0.0, size=(2000, 2))
drifted = rng.normal(loc=1.5, size=(2000, 2)) # normal behavior, but the mean moved
clf = IsolationForest(contamination=0.05, random_state=7).fit(train)
print("flag rate, same distribution:", (clf.predict(same) == -1).mean())
print("flag rate, drifted data: ", (clf.predict(drifted) == -1).mean())The first rate stays near 5%, as set by contamination. The second is much higher, even though nothing in the drifted window is abnormal for the new regime.
Practical responses:
- Retrain on a rolling window of recent data, and exclude confirmed anomalies from it.
- Monitor the score distribution (for example its median and 5th percentile) on each incoming batch. A steady shift means drift, not a burst of anomalies.
- Avoid recomputing the threshold as a quantile of each new batch. That hides drift, because it forces a fixed percentage of alerts whatever the data look like.
- Keep a held-out set of labeled incidents and re-evaluate after each retrain.
Other failure modes
The three limits in the title are not the only ones. These also come up often in practice.
| Problem | Why it happens | Mitigation |
|---|---|---|
| Local anomalies | A point near a dense cluster but outside it may take as many splits as points in a sparse cluster, so density differences are missed. | Try Local Outlier Factor, or run per-segment models. |
| Clustered anomalies | Many similar anomalies behave like a small normal cluster. Subsampling reduces this masking but cannot remove it. | Lower `max_samples`, or inspect small clusters separately. |
| Contaminated training data | Anomalies in the training set shape the trees and the offset. | Clean obvious incidents first, or fit on a trusted period. |
| Categorical or discrete features | Splits on one-hot or integer codes isolate rare categories quickly, which is often noise. | Encode with care, and drop high-cardinality IDs. |
| Uncalibrated scores | The score is a rank-style measure, not a probability. A score of 0.6 has no fixed meaning across datasets. | Compare scores only within one fitted model, and calibrate with labels if you have them. |
| Duplicates | Many identical rows cannot be split apart, so their path length is capped by the depth limit. | Deduplicate or weight rows before fitting. |
A diagnostic flow
Summary of what to check
Before deploying, answer four questions. Does the structure of your data fit axis-aligned boxes? Do most of your features carry signal? Will the data distribution stay stable between retrains? Do you have labels, even a few, to check the ranking? A "no" to any of them points to the mitigation in the matching section above.
Exercise
You deploy an Isolation Forest with contamination=0.02. Two weeks later the alert rate is 11%, and a manual review finds the extra alerts are ordinary traffic from a new customer segment. Name the cause and give two actions that fix it without hiding the problem.
Show answer
The cause is drift. The new segment lies outside the regions seen at fit time, so the fixed trees and the fixed offset flag it. Fixes: retrain on a recent window that includes the new segment, and monitor the batch score distribution to detect such shifts early. Recomputing the threshold as a per-batch quantile would force a 2% alert rate but would hide the drift, so avoid it.
Exercise
A data set has 3 informative features and 300 pure-noise features. ROC AUC is poor. Explain mechanically why, and name the most effective remedy.
Show answer
At each node the tree picks a feature uniformly at random, so roughly 99% of splits use noise features. Those splits do not separate anomalies from normal points, so anomaly path lengths look like normal ones. The most effective remedy is to remove the noise features, by feature selection or by dimensionality reduction that keeps the signal.