Sub topic 8
Running IsolationForest in scikit-learn
This chapter assumes you know basic Python and NumPy, and that you have seen the path-length score from the previous chapter. Here you fit a model and read its three outputs.
Fitting the model
IsolationForest is unsupervised. You call fit(X) with a feature matrix and no labels. The code below builds 500 normal points and 25 scattered outliers, then fits a forest.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(42)
X_normal = rng.normal(loc=0.0, scale=1.0, size=(500, 2))
X_outliers = rng.uniform(low=-6.0, high=6.0, size=(25, 2))
X = np.vstack([X_normal, X_outliers])
clf = IsolationForest(n_estimators=100, contamination=0.05, random_state=42)
clf.fit(X)
labels = clf.predict(X) # 1 = inlier, -1 = outlier
scores = clf.score_samples(X) # lower = more abnormal
decision = clf.decision_function(X)
print((labels == -1).sum(), "points flagged as anomalies")
print("offset_:", clf.offset_)
print(np.allclose(decision, scores - clf.offset_)) # True
print(np.array_equal(labels == -1, decision < 0)) # TrueSetting random_state makes the run repeatable, because the splits are random.
The three outputs
Each method answers a different question.
| Method | Returns | Meaning |
|---|---|---|
| `score_samples(X)` | Float per row | Negative of the paper's anomaly score. Lower is more abnormal. |
| `decision_function(X)` | Float per row | `score_samples(X) - offset_`. Negative means outlier. |
| `predict(X)` | 1 or -1 | 1 for inlier, -1 for outlier. |
The paper's score s is near 1 for anomalies. scikit-learn returns -s, so a point with s = 0.5 has a score_samples value of -0.5.
The attribute offset_ is the cut point. With a numeric contamination, offset_ is set to that percentile of the training scores. With the default contamination="auto", offset_ is fixed at -0.5, which corresponds to s = 0.5.
Common errors
- Sign confusion. Ranking by
score_samplesand taking the largest values returns the most normal points. Negate it, or sort ascending. - Treating
contaminationas a learned value. It is your assumption about the outlier fraction. It only movesoffset_. It does not change how the trees are built or how points are ranked. - Expecting exactly that fraction on new data.
offset_is computed on the training data. On new data,predictmay flag more or fewer points thancontaminationsuggests. - Reading
predictas a probability. It is a hard label. Usedecision_functionorscore_sampleswhen you need to rank points or choose your own threshold. - Passing missing values. Check your scikit-learn version's documentation. If it rejects NaN, impute first. The next chapters cover preparation.
Scoring new data
Fit on data that is mostly normal, then call predict or decision_function on new rows.
X_new = np.array([[0.1, -0.2], [5.5, 5.8]])
print(clf.predict(X_new)) # typically [ 1 -1]
print(clf.decision_function(X_new))The first row sits in the dense cluster and should get a positive decision_function value. The second is far outside it and should get a negative value. Because the forest is random, treat the exact numbers as approximate. Do not rely on them for borderline points.
If you call fit_predict(X), you get labels for the training rows in one step. Use it only when the training set is the data you want to score.
Exercise
After fitting, a row has score_samples of -0.62 and the model's offset_ is -0.55. What are its decision_function value and its predict label?
Show answer
decision_function = -0.62 - (-0.55) = -0.07. The value is negative, so predict returns -1 and the row is flagged as an outlier.