Sub topic 2
From One Tree to a Forest
Assume you know basic Python, NumPy, decision trees, and train/test data. Isolation Forest combines many random isolation trees to make anomaly scores more stable.
From one tree to a forest
One isolation tree repeatedly chooses a feature and a split value at random. A point's path length is the number of splits needed to separate it from the other points. An unusual point usually has a short path.
One tree can be unlucky. An Isolation Forest builds many trees, often using different random samples of the data, and averages each point's path length.
Why subsampling helps: swamping and masking
Each tree normally trains on a random subset. This helps in two ways:
- Swamping occurs when an unusual point makes nearby normal points look abnormal.
- Masking occurs when several anomalies resemble one another, so they hide each other.
A smaller sample can leave an anomaly without its masking neighbors. The anomaly is then isolated quickly. Subsampling also reduces computation and makes the trees less alike.
>``callout note > Subsampling is not a guarantee. If anomalies are common, form a dense cluster, or resemble normal data, Isolation Forest may still miss them. >``
The anomaly score formula
If the average path length is E[h(x)] and a reference path length is c(n), the original score is:
s(x) = 2^(-E[h(x)] / c(n))
A shorter path produces a higher score. A path length near c(n) produces a score near 0.5. The reference value adjusts for the sample size.
Running `IsolationForest` in scikit-learn
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(42)
X_normal = rng.normal(size=(500, 2))
X_outliers = rng.uniform(-6, 6, size=(25, 2))
X = np.vstack([X_normal, X_outliers])
model = IsolationForest(
n_estimators=200,
max_samples="auto",
contamination=0.05,
random_state=42,
).fit(X)
labels = model.predict(X) # 1 = inlier, -1 = outlier
decision = model.decision_function(X) # higher = more normal
raw = model.score_samples(X) # lower = more abnormal
print((labels == -1).sum())Preparing data
Scaling is usually unnecessary because Isolation Forest uses random axis-parallel splits, not distances. Apply scaling when another model in the same pipeline requires it.
Impute missing numeric values with a statistic such as the median. Impute categorical values with the most common category, then encode categories as numeric indicator columns with OneHotEncoder. Fit every preprocessing step on training data only.
Exercise
Which scikit-learn output should you use when larger values must mean “more anomalous”?
Show answer
Negate score_samples, because scikit-learn returns lower raw scores for more abnormal points.