Sub topic 7
The Anomaly Score Formula
This chapter assumes you know how an isolation tree is built, what path length means, and how a forest averages over many trees. It also assumes you are comfortable with logarithms and with basic NumPy. Here you will turn an average path length into a single score between 0 and 1, and learn how to read that score.
Why path length alone is not enough
Each tree gives a path length h(x) for a point x. This is the number of edges from the root to the leaf where x ends up. Averaging over the trees in the forest gives E[h(x)].
You cannot compare E[h(x)] directly across datasets, because the depth that counts as "short" depends on how many points each tree was built from. A tree built from 8 points is shallow no matter what. A tree built from 256 points is deeper. So the path length has to be normalized by the typical path length for a tree of that size.
The normalizing term c(n)
An isolation tree has the same shape as a binary search tree (BST). Finding where a point lands in the tree is like an unsuccessful search in a BST. The average path length of such a search over n points is:
c(n) = 2 H(n−1) − 2(n−1)/n
H(i) is the i-th harmonic number. It is approximated by ln(i) + γ, where γ ≈ 0.5772156649 is the Euler–Mascheroni constant. This gives the form used in code:
c(n) = 2 (ln(n−1) + γ) − 2(n−1)/n
Two special cases apply. For n = 2, c(n) = 1, because one split separates the two points. For n ≤ 1, c(n) = 0, because there is nothing to split.
c(n) grows only logarithmically. Doubling the subsample size adds about 2 ln 2 ≈ 1.39 to the typical depth. This is why isolation trees can stay small.
The score
The original Isolation Forest paper defines the anomaly score of a point x for a subsample size n as:
s(x, n) = 2^(−E[h(x)] / c(n))
The exponent is the average path length divided by the normalizer. Because the base is 2 and the exponent is negative, the score falls between 0 and 1. Short paths give a ratio near 0, so the score approaches 1. Long paths give a larger ratio, so the score approaches 0.
Three reference points anchor the interpretation:
| Average path length | Ratio E[h(x)] / c(n) | Score | Reading |
|---|---|---|---|
| E[h(x)] → 0 | 0 | → 1 | Isolated almost immediately. Very likely an anomaly. |
| E[h(x)] = c(n) | 1 | 0.5 | Typical path length. Nothing stands out. |
| E[h(x)] → n − 1 | large | → 0 | Very deep. Clearly normal, in a dense region. |
The paper's rules of thumb follow from this table:
- If most scores are close to 0.5, the data has no clear anomalies.
- If a point scores well above 0.5, it is likely an anomaly.
- If a point scores well below 0.5, it is safely normal.
These are guides, not hard cutoffs. A score of 0.6 does not mean a 60% chance of being an anomaly. The score is a ranking tool, not a probability.
Computing the score by hand
The code below implements c(n) and the score. It shows that a point with average path length c(n) scores exactly 0.5, and that a very short path scores near 1.
import numpy as np
EULER_GAMMA = 0.5772156649
def c(n):
"""Average path length of an unsuccessful search in a binary search tree of n points."""
if n <= 1:
return 0.0
if n == 2:
return 1.0
return 2.0 * (np.log(n - 1) + EULER_GAMMA) - 2.0 * (n - 1) / n
def anomaly_score(mean_path_length, n):
"""Score in (0, 1]; values near 1 are anomalous, around 0.5 are unremarkable."""
return 2.0 ** (-mean_path_length / c(n))
n = 256
print(anomaly_score(c(n), n)) # a point with average path length c(n) scores 0.5
print(anomaly_score(3.0, n)) # a very short path gives a score close to 1For n = 256, c(n) is about 10.2. A point isolated in 3 splits on average has a ratio of about 0.29, which gives a score of about 0.82. A point with a path of 10 has a ratio near 0.98 and a score near 0.51.
Edge cases in the path length
Two details affect the path length that goes into the formula.
Depth limit. Trees are not grown until every point is alone. They stop at a maximum depth of about ceil(log2(n)). Anomalies are expected to be isolated early, so deep branches add cost and little information. A leaf that still holds several points, because the depth limit was reached first, gets an adjustment. The path length is the depth reached plus c(size), where size is the number of points in that leaf. This estimates the extra splits that would have been needed to separate them. For a leaf with one point, c(1) = 0 and no adjustment is made.
Duplicates. Identical points can never be separated by a split. The same adjustment c(size) applies to a leaf of identical points, so a large cluster of duplicates ends up with a long adjusted path and a low score.
Scores in scikit-learn
scikit-learn's IsolationForest computes the paper's score internally, but it exposes it with different signs and offsets. This often causes confusion.
| Method | What it returns | Direction |
|---|---|---|
| `score_samples(X)` | The negative of the paper's score, −s(x, n) | Lower means more abnormal |
| `decision_function(X)` | `score_samples(X) − offset_` | Negative means outlier, positive means inlier |
| `predict(X)` | 1 for inliers, −1 for outliers | Based on `decision_function` |
The attribute offset_ is the threshold on score_samples. With the default contamination="auto", offset_ is −0.5. This matches the paper's 0.5 reference point: a point whose score exceeds 0.5 is called an outlier. With a numeric contamination, offset_ is set to the matching quantile of the training scores, so that the stated fraction of training points falls below it.
The next example fits a forest and recovers the paper's score from score_samples.
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, random_state=42).fit(X)
paper_score = -clf.score_samples(X) # s(x, n) from the paper, in (0, 1]
print("offset_:", clf.offset_) # -0.5 with contamination="auto"
print("max score:", paper_score.max())
print("median score:", np.median(paper_score))
print("points above 0.5:", (paper_score > 0.5).sum())Negating score_samples gives a value you can compare with the table above. Most normal points land below 0.5, and the outliers land above it.
Common errors
- Reading the score as a probability. A score of 0.7 is not "70% anomalous". Use the score to rank points, and choose a cutoff separately (see the chapter on thresholds).
- Forgetting the sign in scikit-learn.
score_samplesreturns values near −0.5 for ordinary points, not values near 0.5. Sorting ascending puts the most abnormal points first. - Expecting 0.5 as the cutoff with a numeric
contamination. The cutoff then comes from a quantile of the training scores, not from 0.5. - Comparing scores from forests with different
max_samples. The score is normalized by c(n), but scores from different subsample sizes are not directly comparable. Compare scores only within one fitted model. - Expecting a score of exactly 1. The score approaches 1 only when the average path length approaches 0, which is not reachable in practice. Real maximum scores are usually well below 1, often around 0.7 to 0.8.
Check your understanding
Exercise
With a subsample size n = 256, c(256) is about 10.2. A point has an average path length of 5.1 across the forest. What is its anomaly score s(x, n), and is it above or below 0.5? What value would score_samples return for it?
Show answer
The ratio E[h(x)] / c(n) is 5.1 / 10.2 = 0.5. The score is 2^(−0.5) ≈ 0.707, which is above 0.5, so the point is more abnormal than typical. score_samples returns the negative of the score, about −0.707.
Exercise
Explain in one or two sentences why the score is divided by c(n) instead of using the raw average path length.
Show answer
The typical depth of a point depends on how many points each tree was built from, so a raw path length of 6 is short for a large subsample and long for a small one. Dividing by c(n), the expected path length for n points, makes the ratio comparable: 1 means typical, below 1 means shorter than typical.