Sub topic 3
Tuning Isolation Forest in Practice
Assume you know basic Python, NumPy, decision trees, and train/test data. An Isolation Forest uses random trees to give each row an anomaly score. Tune the forest before choosing a threshold.
Tuning the forest
n_estimatorsis the number of trees. More trees make scores more stable but increase training and prediction time. Start with 100–300.max_samplesis the number of rows used by each tree. Smaller samples reduce cost and can make unusual groups easier to isolate. Larger samples give each tree more context."auto"uses at most 256 rows.max_featuresis the number or fraction of columns used by each tree. Smaller values add diversity and can help with many noisy features. Larger values let trees use more evidence.
| Parameter | Increase it when | Main cost |
|---|---|---|
| `n_estimators` | Scores vary between runs | More computation |
| `max_samples` | Context from more rows matters | Slower trees |
| `max_features` | Important signals use many columns | Less tree diversity |
from sklearn.ensemble import IsolationForest
model = IsolationForest(
n_estimators=200,
max_samples=256,
max_features=0.8,
contamination="auto",
random_state=42,
)
model.fit(X_train)
raw_score = model.score_samples(X_test) # lower means more abnormal
labels = model.predict(X_test) # 1 inlier, -1 outlierChoosing a threshold
contamination is the expected fraction of anomalies. Setting contamination=0.02 makes the model label roughly the most abnormal 2% as outliers. It does not make the detector more accurate. Use a domain-based threshold when possible. With no labels, a quantile is a transparent alternative.
import numpy as np
anomaly_score = -model.score_samples(X_test)
threshold = np.quantile(anomaly_score, 0.98)
flagged = anomaly_score >= thresholdEvaluating detected anomalies
When known labels exist, use 1 for an anomaly and 0 for a normal row. Negate score_samples so larger values mean more abnormal. ROC AUC measures ranking across thresholds. Average precision is often more informative when anomalies are rare.
from sklearn.metrics import roc_auc_score, average_precision_score
scores = -model.score_samples(X_test)
print(roc_auc_score(y_test, scores))
print(average_precision_score(y_test, scores))Limitations and alternatives
Isolation Forest makes axis-parallel splits: each split tests one feature. Diagonal or curved anomaly boundaries may therefore need many splits. High-dimensional noise can also hide useful differences. Data drift changes the normal population, so retrain or monitor score distributions over time.
Extended Isolation Forest uses random hyperplanes and can represent oblique boundaries better. Local Outlier Factor and one-class SVM are other alternatives, with different assumptions and costs.
Explaining a flagged point
A flagged row has short paths in many trees. Inspect its feature values against normal ranges, compare it with nearby normal rows, and report the features that most often participate in its short paths. The score ranks abnormality; it does not prove a cause.
Exercise
What does increasing max_samples usually change?
Show answer
Each tree sees more rows, so it gets more context, but training costs more and small isolated groups may be less prominent.