Sub topic 8
Running IsolationForest in scikit-learn
This chapter assumes you know basic Python and NumPy, can read a feature matrix of shape (n_samples, n_features), and have met the idea from earlier chapters that short average path lengths mean abnormal points. Here you will fit sklearn.ensemble.IsolationForest and read what its methods return. The sign conventions are the most common source of mistakes.
Fitting a model
IsolationForest follows the usual scikit-learn pattern. You build the estimator, call fit(X) on the feature matrix, then call scoring methods. There is no y argument, because the method is unsupervised. If you pass y, it is ignored.
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
print((labels == -1).sum(), "points flagged as anomalies")The data is 500 points from a Gaussian cluster plus 25 points scattered uniformly over a wide square. Setting random_state makes the result repeatable. Each tree draws its own random subsample, features and split values, so two unseeded runs give slightly different scores.
Three outputs, three conventions
The estimator gives you three views of the same quantity. Mixing them up is a common source of silent bugs.
| Method | Returns | Meaning |
|---|---|---|
| `predict(X)` | `1` or `-1` | `-1` is an outlier, `1` is an inlier |
| `score_samples(X)` | negative floats | Lower means more abnormal |
| `decision_function(X)` | floats | `score_samples(X) - offset_`. Negative means outlier, positive means inlier |
score_samples is the negative of the paper's score s(x, n). The paper's score is near 1 for anomalies, so scikit-learn's value is near -1 for them. An unremarkable point has a paper score of about 0.5 and a score_samples value of about -0.5.
The attribute offset_ is the cut-off that turns scores into labels. A point is labeled -1 when its decision_function value is below 0, which means its score_samples value is below offset_.
You can check these relationships on new data. The model is fit on 500 normal points. The three new points are one typical point and two far-away points.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(42)
X_train = rng.normal(size=(500, 2))
X_new = np.array([[0.1, -0.2], [5.0, 5.0], [-4.0, 3.0]])
clf = IsolationForest(random_state=42).fit(X_train)
raw = clf.score_samples(X_new)
dec = clf.decision_function(X_new)
pred = clf.predict(X_new)
print("offset_:", clf.offset_)
print("score_samples:", raw)
print("decision_function:", dec)
print("predict:", pred)
assert np.allclose(dec, raw - clf.offset_)
assert np.array_equal(pred, np.where(dec < 0, -1, 1))The two assertions hold for any fitted model, so they are a quick way to confirm you have the signs right. With the default settings you should see the first point labeled 1 and the other two labeled -1.
How `contamination` sets the offset
contamination controls only the threshold. It does not change the trees or the scores. Two settings matter.
contamination="auto"(the default).offset_is fixed at -0.5. This follows the paper: points whose paper score is above 0.5 are called anomalies. The number of flagged points depends on the data and is not controlled.- A float in (0, 0.5].
offset_is set to that percentile of the training scores. If you pass0.05, about 5% of the training points are flagged.
The float setting guarantees a flagged fraction on the training data. It does not tell you how many true anomalies exist. If the real rate is 1% and you pass 0.05, most of your flags will be false alarms. If you do not know the rate, prefer "auto" or choose the threshold yourself, as described in the thresholding chapter.
Scoring new data
You usually fit on historical data and score data that arrives later. The fitted model keeps the trees and the offset, so predict, decision_function and score_samples all work on unseen rows. The number of columns must match the training data.
A practical pattern is to rank by score instead of relying on the labels. This gives you a review queue ordered by how abnormal each point looks.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(1)
X_train = rng.normal(size=(1000, 3))
X_batch = np.vstack([rng.normal(size=(200, 3)),
rng.normal(loc=7.0, size=(5, 3))])
clf = IsolationForest(random_state=1).fit(X_train)
order = np.argsort(clf.score_samples(X_batch)) # most abnormal first
top = order[:10]
print("Row indices to review first:", top)
print("Their decision_function values:", clf.decision_function(X_batch[top]))The five shifted rows are at indices 200 to 204. They should appear among the first entries of top. Ranking works the same way whatever contamination is, because the ordering of scores does not depend on the threshold.
Fitted attributes worth knowing
After fit, a few attributes help with inspection and debugging.
offset_: the threshold onscore_samples, as described above.estimators_: the list of fitted trees. Its length equalsn_estimators.max_samples_: the actual subsample size used per tree. With the defaultmax_samples="auto", this ismin(256, n_samples).n_features_in_: the number of columns seen infit.estimators_samples_: for each tree, the indices of the rows it was trained on.
The default subsample of 256 rows is deliberate and is not a memory shortcut. The paper shows that small subsamples keep detection quality high, and they make training cost nearly independent of dataset size. Fitting on one million rows is therefore not much slower per tree than fitting on ten thousand, although prediction still scans every row you score.
Common errors
- Reading
score_samplesas "higher is more anomalous". In scikit-learn the opposite is true. If you pass the raw values to a metric that expects higher-is-positive, such asroc_auc_score, negate them first. The evaluation chapter covers this. - Treating
predictas a probability. It is a hard label based on one threshold. Use the scores when you need ranking or your own cut-off. - Fitting on data that already contains many anomalies and expecting the model to ignore them. Isolation Forest tolerates some contamination, but a large share of anomalies in training shifts the scores and the offset.
- Passing a DataFrame with strings or
NaNvalues. Recent scikit-learn versions can handle some missing values in tree models, but you should not rely on it here. Encode categorical columns and decide how to treat missing values before fitting. The preparation chapter covers both. - Comparing raw scores across separately fitted models. Each model has its own trees and its own score distribution. Compare ranks or use one model for both datasets.
- Forgetting to seed the model when you compare settings. Differences between runs may come from randomness rather than from the parameter you changed.
Exercises
Exercise
A fitted model with the default settings has offset equal to -0.5. A new point has scoresamples equal to -0.62. What does decision_function return, and what does predict return?
Show answer
decision_function returns -0.62 - (-0.5) = -0.12. The value is negative, so predict returns -1 and the point is labeled an outlier.
Exercise
You fit IsolationForest(contamination=0.02) on 5000 training rows. About how many training rows does predict flag, and why is that number not evidence that the data contains exactly 2% anomalies?
Show answer
About 100 rows (2% of 5000). The offset_ is set to the 2nd percentile of the training scores, so about 2% of the training rows fall below it however many true anomalies exist. The flagged fraction reflects the parameter you chose, not the data.
Exercise
You want to compute rocaucscore using scores from a fitted IsolationForest. Which array do you pass as the scores argument, and why?
Show answer
Pass -clf.scoresamples(X), or equivalently -clf.decisionfunction(X). The raw values are lower for anomalies, but rocaucscore expects higher values for the positive (anomaly) class, so the sign must be flipped.