Sub topic 11
Choosing a Threshold and the Contamination Parameter
This chapter assumes you can fit an IsolationForest in scikit-learn and know that score_samples returns raw scores where lower means more abnormal. Here you will turn those scores into yes/no decisions.
Scores are not decisions
An Isolation Forest produces a continuous score for every point. To flag anomalies, you must pick a cutoff. Every choice of cutoff trades missed anomalies (false negatives) against false alarms (false positives).
scikit-learn gives you three related outputs:
| Method | Meaning | Anomaly if |
|---|---|---|
| `score_samples(X)` | Raw score, the negated anomaly score from the paper | lower |
| `decision_function(X)` | `score_samples(X) - offset_` | below 0 |
| `predict(X)` | 1 for inlier, -1 for outlier | equals -1 |
The offset_ attribute is the cutoff that predict uses. The contamination parameter decides where offset_ falls.
What contamination does
contamination is your estimate of the fraction of anomalies in the training data. When you set it to a number such as 0.05, fit computes the scores of the training points and sets offset_ to the 5th percentile of those scores. Exactly about 5% of the training points are then labeled -1.
The default is "auto". It sets offset_ to -0.5, which follows the original paper: a score of 0.5 (average path length equal to c(n)) is the boundary. With "auto", the fraction flagged depends on the data and is not fixed.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(0)
X = np.vstack([
rng.normal(size=(1000, 2)),
rng.uniform(low=-6.0, high=6.0, size=(50, 2)),
])
for contamination in ["auto", 0.01, 0.05, 0.10]:
clf = IsolationForest(contamination=contamination, random_state=0).fit(X)
n_flagged = (clf.predict(X) == -1).sum()
print(f"contamination={contamination!s:>5} offset_={clf.offset_:.3f} flagged={n_flagged}")Running this shows offset_ moving as contamination changes. The number flagged tracks the value you set.
Choosing a threshold yourself
You are not forced to use predict. Often a better approach is to work with the scores directly. Three common strategies:
- Quantile threshold. Flag the top k% most abnormal scores. This is what contamination does, and you can do it on new data too with
np.quantile. - Budget-based threshold. If analysts can review 20 alerts a day, flag the 20 highest scores. The threshold follows from capacity, not from a guess about the data.
- Labeled validation threshold. If you have some labels, sweep thresholds and pick the one that maximizes F1, or that meets a minimum precision or recall.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import precision_recall_curve
rng = np.random.RandomState(0)
X_normal = rng.normal(size=(1000, 2))
X_outliers = rng.uniform(low=-6.0, high=6.0, size=(50, 2))
X = np.vstack([X_normal, X_outliers])
y_true = np.r_[np.zeros(len(X_normal)), np.ones(len(X_outliers))]
clf = IsolationForest(random_state=0).fit(X)
anomaly_scores = -clf.score_samples(X) # higher = more anomalous
precision, recall, thresholds = precision_recall_curve(y_true, anomaly_scores)
f1 = 2 * precision[:-1] * recall[:-1] / (precision[:-1] + recall[:-1] + 1e-12)
best = thresholds[np.argmax(f1)]
print("Best threshold:", round(best, 3), "F1:", round(f1.max(), 3))Note that precision_recall_curve expects higher scores to mean the positive class, so the sign is flipped first.
Common errors
- Reading the sign wrong.
score_samplesis lower for anomalies. Libraries for metrics expect higher for anomalies. Negate before calling them. - Treating contamination as a tuning knob for accuracy. It only moves the cutoff. It changes the labels, not the ranking, so it does not change ROC AUC.
- Setting it from a guess. A float contamination always flags that fraction of the training data, even if the data holds no anomalies.
- Fixing the cutoff and ignoring drift. If the data distribution changes, a percentile computed at training time no longer matches the same share of new points.
Exercise
You set contamination=0.02 and train on 5,000 points. About how many training points does predict label as -1, and does changing contamination to 0.10 change the ROC AUC of -score_samples?
Show answer
About 100 points (2% of 5,000) are labeled -1. Changing contamination to 0.10 would flag about 500, but the ROC AUC stays the same because it depends only on the score ranking, and contamination only moves the cutoff.