Sub topic 11
Choosing a Threshold and the Contamination Parameter
An Isolation Forest does not produce labels. It produces a score for every point, and a threshold turns scores into the labels "anomaly" and "normal". This chapter covers how scikit-learn sets that threshold, what contamination does, and how to pick a threshold yourself.
This chapter assumes you can fit an IsolationForest, that you know the anomaly score from the earlier chapters (short average path length gives a high score), and that you know basic NumPy and precision/recall.
Scores, offsets, and labels in scikit-learn
scikit-learn exposes three outputs, and they are linked by one number, offset_.
| Method or attribute | Meaning | Sign convention |
|---|---|---|
| `score_samples(X)` | The negated paper score, so values are negative | Lower is more abnormal |
| `offset_` | The cut point on the `score_samples` scale, fixed at fit time | None |
| `decision_function(X)` | `score_samples(X) - offset_` | Negative means anomaly |
| `predict(X)` | `-1` if `decision_function(X) < 0`, otherwise `1` | `-1` is an outlier |
The threshold is therefore offset_. Everything below it is flagged. The contamination parameter only decides how offset_ is computed.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(42)
X = np.vstack([
rng.normal(size=(500, 2)),
rng.uniform(-6.0, 6.0, size=(25, 2)),
])
clf = IsolationForest(contamination=0.05, random_state=42).fit(X)
scores = clf.score_samples(X)
print("offset_:", clf.offset_)
print("decision_function == scores - offset_:",
np.allclose(clf.decision_function(X), scores - clf.offset_))
print("offset_ is the 5th percentile of training scores:",
np.isclose(clf.offset_, np.percentile(scores, 5)))
print("flagged:", (clf.predict(X) == -1).sum(), "of", len(X))The two checks print True. About 5% of the 525 training points are flagged, which is roughly 26.
The two modes of `contamination`
contamination is the expected share of anomalies in the training data. It accepts 'auto' or a float in the range (0, 0.5].
'auto'(default).offset_is fixed at-0.5. This comes from the original paper, where a score of 0.5 means "no clear anomaly". A point is flagged when its paper score exceeds 0.5. The share flagged depends on the data and is not controlled.- A float.
offset_is set to the matching quantile of the training scores. Withcontamination=0.05, the lowest 5% of training scores fall below the threshold. By construction, about 5% of the training data is flagged, whatever the data looks like.
auto = IsolationForest(random_state=42).fit(X)
print(auto.offset_) # -0.5
print((auto.predict(X) == -1).sum()) # depends on the data, not on a chosen rateA float contamination is a quantile rule, not a detector of the true anomaly rate. If you set 0.05 and the data has 0.5% anomalies, the model still flags 5% of training points, and most will be false alarms. If you set 0.01 and the data has 5% anomalies, you miss most of them.
Since the chapter requires the diagram in the specified fenced form, here it is:
What happens on new data
offset_ is computed once, on the training set. When you call predict on new data, the same cut point is reused. This has two consequences:
- The share flagged in new data is not fixed at
contamination. If the new batch has more unusual points than the training set, more than 5% are flagged. If it has fewer, fewer are flagged. - Changing
contaminationafter fitting has no effect onscore_samplesordecision_function. In current scikit-learn versions, setting the parameter after fit does not recomputeoffset_. To use a different threshold, compare scores to your own value instead of refitting.
X_new = np.vstack([
rng.normal(size=(200, 2)),
rng.uniform(-6.0, 6.0, size=(20, 2)),
])
new_scores = clf.score_samples(X_new)
flagged = new_scores < clf.offset_
print("share flagged in new batch:", flagged.mean())This is the behaviour you usually want in monitoring. A fixed threshold lets a spike in anomalies show up as a higher flag rate. A threshold recomputed on every batch would hide it.
Choosing a threshold yourself
Because the model only ranks points, you can ignore predict and apply any rule to the scores. Three rules cover most cases.
Rule 1: a fixed alert budget
If a team can review 20 cases per day, flag the 20 most abnormal points. The quantile of scores is chosen from capacity, not from a guess about the anomaly rate.
anomaly_scores = -clf.score_samples(X_new) # higher = more abnormal
k = 20
top_k = np.argsort(anomaly_scores)[::-1][:k]Rule 2: a threshold from a trusted reference period
Fit on a period known to be mostly normal, then take a high quantile of its scores, such as the 1st percentile of score_samples. Use that value as a fixed cut for later data. This ties the false alarm rate on normal-looking data to a number you chose, around 1% in this case.
reference_scores = clf.score_samples(X[:500]) # normal-looking reference rows
cut = np.quantile(reference_scores, 0.01)
print("flag if score <", cut)Rule 3: maximize a metric on labelled data
If you have some labels, pick the threshold that gives the best F1 score, or the best recall at a required precision. Use precision_recall_curve on negated scores.
from sklearn.metrics import precision_recall_curve
from sklearn.model_selection import train_test_split
rng = np.random.RandomState(0)
X_all = np.vstack([rng.normal(size=(1000, 2)),
rng.uniform(-6.0, 6.0, size=(50, 2))])
y_all = np.r_[np.zeros(1000), np.ones(50)] # 1 = anomaly
X_tr, X_val, y_tr, y_val = train_test_split(
X_all, y_all, test_size=0.4, stratify=y_all, random_state=0)
model = IsolationForest(random_state=0).fit(X_tr)
val_scores = -model.score_samples(X_val) # higher = more abnormal
precision, recall, thresholds = precision_recall_curve(y_val, val_scores)
f1 = 2 * precision * recall / (precision + recall + 1e-12)
best = np.argmax(f1[:-1]) # the last precision/recall pair has no threshold
best_threshold = thresholds[best]
print("best F1:", f1[best], "at score >=", best_threshold)The threshold is tuned on X_val, so its F1 is an optimistic estimate. To report an honest number, hold out a third split, or choose the threshold on one split and measure on another.
Common errors
- Setting
contaminationto a guess that you never check. The flag rate on training data will match it exactly, which looks like a result but is not. - Mixing up sign conventions.
score_samplesis lower for anomalies, whileroc_auc_scoreandprecision_recall_curveexpect higher for the positive class. Negate the scores before passing them to metrics. - Reading
predictas a probability. The score is a rank-based measure, not the chance that a point is an anomaly. A score of -0.6 and one of -0.55 cannot be compared as "10% more likely". - Using
contamination=0.5or more. The accepted range stops at 0.5, since flagging half the data is no longer anomaly detection. - Treating the threshold as permanent. If the data drifts, a quantile fixed on old data will drift in meaning. Re-estimate it on a recent reference window.
Summary
offset_is the threshold.decision_functionisscore_samples - offset_, andpredictflags negative values.contamination='auto'uses-0.5. A float uses that quantile of the training scores.- The threshold is fixed at fit time and reused on new data, so the flag rate on new data can move.
- When you have capacity limits, a clean reference period, or labels, apply your own cut to the scores.
Exercise
You fit IsolationForest(contamination=0.02) on 10,000 rows, then call predict on a new batch of 1,000 rows and see 90 flagged. Explain why this is not a bug, and name what the value 90 tells you. Then write the line of code that gives the flagged mask using the fitted model's threshold directly.
Show answer
The offset was fixed at the 2% quantile of the training scores and is reused for new data, so the flag rate on a new batch is not forced to 2%. Flagging 90 of 1,000 (9%) means the new batch has many more low-scoring points than the training data did, which suggests drift or a burst of anomalies worth investigating. The mask is: flagged = clf.scoresamples(Xnew) < clf.offset