Isolation Forest: how many cuts separate this record?
孤立森林
Build a small random isolation forest and audit corrected path lengths, score direction and the limits of geometric anomaly rankings.
isolation-forestCount the cuts needed to separate a record
A workshop logs two sensor readings. Most recorded pairs lie between zero and two, while one pair is (9,9). A randomly placed horizontal or vertical cut often separates that distant pair immediately. Distinguishing two nearby readings usually takes more cuts.
Isolation Forest turns this observation into a ranking: grow randomly partitioned trees, route each record through them, and give shorter average paths a higher anomaly score. There are no class labels or fitted leaf means. The approach introduced by Liu, Ting and Zhou at ICDM 2008 uses isolation itself rather than an explicit distance or density estimate. Original paper
An anomaly is still defined by the task. A rare sensor reading could be a fault, a new operating mode or a transcription error. The algorithm cannot distinguish those explanations from geometry alone. In our example, (9,9) and (90,90) receive exactly the same score: both follow the same branches in every fitted tree. That is a useful first clue about what the score measures.
The decision-tree chapter explains partitions. Here the split is sampled, not chosen to improve a supervised loss. Extra Trees also samples thresholds, but then compares candidate splits using targets; this detector does neither that comparison nor leaf regression.
Path length, unfinished leaves and a reference scale
Each tree receives ψ original-row indices sampled without replacement. Repeating identical measurements is allowed: different row indices remain different observations. At an internal node our teaching implementation selects a nonconstant feature uniformly, then selects one of G equally spaced interior grid points uniformly:
Values at most t go left; larger values go right. Both children are nonempty because t lies strictly inside a nonconstant range. This finite grid and explicit exclusion of constant features make the implementation reproducible and well-defined. They are specified teaching choices; the original paper describes random numerical thresholds and uses a strict-less-than left branch.
Growth stops at a singleton, an unsplittable set of identical vectors, or a depth limit. The default limit is the ceiling of log₂ψ. A stopped leaf can contain several training rows. Treating its raw depth as complete isolation would make early stopping look artificially anomalous.
The reference correction uses harmonic numbers. For integer m,
Thus c(2)=1, c(3)=5/3 and c(4)=13/6. This comes from the unsuccessful-search reference for random binary search trees, used by the paper to normalize isolation paths. It is a reference correction, not the exact expected number of further geometric cuts for every dataset. Numeric gaps affect the probabilities of isolation-tree partitions; identical vectors cannot be separated by any available feature at all. We retain the same correction for such a terminal leaf, with that limitation explicit. Paper, §2 and Algorithm 3
One way to check the harmonic expression independently is the random-rank-split recurrence. A reference node with m leaves chooses a split size k uniformly from 1 to m−1, while a uniformly selected leaf goes to each side in proportion to its size:
This recurrence gives the same harmonic formula. It describes that reference tree law; our finite numerical-grid sampler is not uniform over rank split sizes.
For a query x, let e_b be its actual edge depth in tree b, and m_b the size of the reached leaf. Average the corrected paths, then normalize using the tree sample size ψ, not the size of the original dataset:
For ψ at least two, c(ψ) is positive. Smaller mean paths give larger scores; mean path c(ψ) gives 1/2. Average paths before exponentiation: this score is the geometric mean of the individual tree scores, generally not their arithmetic mean. It is not a calibrated probability of failure. A threshold such as 1/2 is a reference convention, not a measured false-alarm guarantee.
A forest with exact paths and inspectable samples
The complete Python 3.10+ program accepts a nonempty rectangular matrix of integers or Fraction values. It rejects floats, Booleans, missing entries and invalid sizes; ψ must be between two and the number of rows. The seed is an integer, and a zero depth limit is allowed. A prediction query may be empty. Returned models must remain unmodified.
The two pseudorandom streams separate sample selection from node cuts, so changing depth preserves the sampled bags at the same seed. corrections computes exact harmonic values once. Path lengths and the base-two log score remain rational; only the final exponentiation uses floating point. For extreme cases it can round or underflow, so exact path values remain the appropriate ranking reference.
from collections import namedtuple
from fractions import Fraction as F
from random import Random
Node = namedtuple('Node', 'size feature threshold left right')
def integer(value, minimum):
if type(value) is not int or value < minimum:
raise ValueError('integer parameter below minimum or invalid type')
return value
def rows(X, dimension=None):
if type(X) not in (list, tuple):
raise ValueError('expected a list or tuple of rows')
output = []
for row in X:
if type(row) not in (list, tuple) or not row:
raise ValueError('nonempty rows required')
if any(type(v) not in (int, F) for v in row):
raise ValueError('coordinates must be integers or Fractions')
if dimension is None:
dimension = len(row)
if len(row) != dimension:
raise ValueError('dimension mismatch')
output.append(tuple(F(v) for v in row))
return tuple(output)
def corrections(size):
integer(size, 0)
result, harmonic = [F(0)], F(0)
for m in range(1, size + 1):
harmonic += F(1, m)
result.append(2 * harmonic - 2)
return tuple(result)
def fit(X, trees=7, sample_size=6, max_depth=None, grid=32, seed=9):
X = rows(X)
trees, sample_size, grid = integer(trees, 1), integer(sample_size, 2), integer(grid, 1)
if sample_size > len(X) or type(seed) is not int:
raise ValueError('sample_size exceeds data or seed is not integer')
depth_limit = (sample_size - 1).bit_length() if max_depth is None else integer(max_depth, 0)
dimension = len(X[0])
bag_rng, split_rng = Random(seed), Random(seed + 1)
bags, roots = [], []
def build(indices, depth):
size = len(indices)
if size == 1 or depth >= depth_limit:
return Node(size, None, None, None, None)
ranges = tuple((min(X[i][j] for i in indices), max(X[i][j] for i in indices))
for j in range(dimension))
active = tuple(j for j, (lo, hi) in enumerate(ranges) if lo < hi)
if not active:
return Node(size, None, None, None, None)
j = split_rng.choice(active)
lo, hi = ranges[j]
threshold = lo + (hi - lo) * F(2 * split_rng.randrange(grid) + 1, 2 * grid)
left = tuple(i for i in indices if X[i][j] <= threshold)
right = tuple(i for i in indices if X[i][j] > threshold)
return Node(size, j, threshold, build(left, depth + 1), build(right, depth + 1))
for _ in range(trees):
bag = tuple(bag_rng.sample(range(len(X)), sample_size))
bags.append(bag)
roots.append(build(bag, 0))
return {'dimension': dimension, 'sample_size': sample_size, 'max_depth': depth_limit,
'bags': tuple(bags), 'roots': tuple(roots), 'correction': corrections(sample_size)}
def path(root, row, correction):
depth, node = 0, root
while node.feature is not None:
node = node.left if row[node.feature] <= node.threshold else node.right
depth += 1
return F(depth) + correction[node.size]
def score(model, X):
# model must be an unmodified return value of fit.
X = rows(X, model['dimension'])
output = []
for row in X:
lengths = tuple(path(root, row, model['correction']) for root in model['roots'])
mean = sum(lengths, F()) / len(lengths)
exponent = -mean / model['correction'][model['sample_size']]
output.append({'paths': lengths, 'mean_path': mean, 'log2_score': exponent,
'score': 2.0 ** float(exponent)})
return tuple(output)
if __name__ == '__main__':
X = ((0, 0), (0, 1), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (9, 9))
model = fit(X)
print('sample size / depth:', model['sample_size'], model['max_depth'])
print('first bag:', model['bags'][0])
print('c(2), c(3), c(4):', tuple(map(str, corrections(4)[2:])))
for row, result in zip(((1, 1), (9, 9), (90, 90)), score(model, ((1, 1), (9, 9), (90, 90)))):
print(row, 'paths', tuple(map(str, result['paths'])),
'mean', str(result['mean_path']), 'score', round(result['score'], 6))
identical = fit(((4,),) * 6)
print('identical data score:', score(identical, ((4,),))[0]['score'])
stopped = fit(X, max_depth=0)
print('zero-depth score:', score(stopped, ((1, 1),))[0]['score'])
The output is
sample size / depth: 6 3
first bag: (7, 4, 2, 5, 1, 0)
c(2), c(3), c(4): ('1', '5/3', '13/6')
(1, 1) paths ('4', '4', '4', '14/3', '14/3', '4', '4') mean 88/21 score 0.367294
(9, 9) paths ('1', '2', '2', '1', '1', '1', '1') mean 9/7 score 0.735425
(90, 90) paths ('1', '2', '2', '1', '1', '1', '1') mean 9/7 score 0.735425
identical data score: 0.5
zero-depth score: 0.5
For the center (1,1), corrected path lengths of four can occur even though the depth limit is three: a depth-three leaf holding two records contributes 3+c(2)=4. The mean center path is 88/21. The separated point has mean path 9/7 and a higher score, approximately 0.735425. This is a constructed example, not an estimate of a machine’s failure rate.
With depth zero, every query reaches the root, and its corrected path equals c(ψ), giving 1/2. Identical training vectors produce the same result even without a restrictive depth setting. In that case, even a new, different query follows the only leaf; the detector has learned no split that could recognize the difference. With ψ=2, every query also has corrected path one and score 1/2: the two records either remain in one leaf or split into singletons. That legal minimum sample size cannot produce a ranking.
Every actual split decreases the number of rows on a branch, so depth is at most L=min(depth limit,ψ−1), and a tree has at most 2ψ−1 nodes. For n rows and d coordinates, a conservative fit bound for this implementation is O(nd+B(n+dψ(L+1))) operations: the n term allows for sample-selection work, and each level’s node subsets contain at most ψ rows in total. Peak stored items are O(nd+Bψ+(ψ+d)(L+1)), including retained trees/bags and recursive subset/range arrays. Scoring q queries takes O(q(d+B(L+1))+1) operations and O(q(d+B)+1) extra storage because all per-tree paths are returned. These bounds count rational operations and coordinate items; bit sizes, numeric input conversion and Python recursion limits still matter.
A high rank needs an operational interpretation
The fitted tree defines rectangular regions extending beyond the observed ranges. Moving a query farther inside the same regions cannot change its path. Rotation can change axis-aligned cuts, and a nonlinear increasing transform can change numerical gap probabilities despite preserving rank order. Positive affine transformations of individual coordinates preserve our exact finite-grid routing at the same random draws.
Subsampling can change whether a rare group appears in each tree. A dense anomalous group may mask itself, while a legitimate rare subgroup may receive short paths. Adding irrelevant coordinates spends random cuts on geometry unrelated to the operational failure. More trees reduce Monte Carlo instability under an ideal independent-tree model; they do not supply missing labels or guarantee better decisions.
Keep training composition explicit. Outlier detection allows unusual records inside the fitting sample; novelty detection treats the reference sample as the normal operating population and scores later records. These are different data assumptions, even when an estimator can score both. Fixed scikit-learn guide
Library score direction is easy to reverse accidentally. In scikit-learn 1.7.2, score_samples has the opposite direction to the paper’s anomaly score: lower means more abnormal. decision_function subtracts a fitted offset, and predict uses −1 for outliers, +1 for inliers. The contamination setting controls threshold selection; it does not verify that the chosen fraction truly contains faults. Our program returns a high-means-anomalous score and does not impose class labels or a contamination threshold.
For deployment, reserve adjudicated cases or an appropriate temporal validation period, choose an alert budget, inspect false alarms and missed events by subgroup, and monitor changes in operating conditions. A top-ranked record is a candidate for investigation. Local outlier factor offers a different comparison based on local neighborhoods when that notion better matches the task.
Separate the score from its interpretation
- A tree stops at depth two in a leaf containing three rows. What corrected path does the program return? Why is it not just two?
Show answer
Answer: It returns 2+c(3)=11/3. The correction represents an unfinished subtree under a reference random-tree law. Reporting two alone would treat a group of three as if it had already been fully separated.
- A forest was fitted to 1,000 records using ψ=4 rows per tree. If a query’s mean corrected path is 13/6, what is its score?
Show answer
Answer: Use c(4)=13/6, so the score is 2⁻¹=1/2. Using c(1000) changes the scale incorrectly: the actual isolation trees were built with four rows each.
- Why do (9,9) and (90,90) have identical outputs in the example? Does a score of 0.735425 mean roughly 74% probability of a fault?
Show answer
Answer: Every fitted threshold lies within a training-coordinate range, and both queries choose the same side at every reached node. Their paths and scores match. The score is a transformed isolation length; the program contains no model connecting it to fault probabilities.
- Two trees give corrected paths c(ψ)/2 and 3c(ψ)/2. Compare the forest score with the arithmetic average of the individual scores. What if all trees have depth zero?
Show answer
Answer: The mean path is c(ψ), so the forest score is 1/2. The individual scores are 2⁻¹ᐟ² and 2⁻³ᐟ²; their arithmetic average is approximately 0.53033, not 1/2. At depth zero, every corrected path is c(ψ), so every query gets 1/2 and the forest cannot rank them.
Isolation is a modeling choice
The 2008 paper makes short isolation paths the central statistic and uses subsampling to build partial trees. Its harmonic normalization connects those paths to a reference search-tree model. The distinction between that reference and the geometry of actual features explains why the correction is useful without being a universal identity about anomalies.
The fixed library API adds a practical contract for sample sizes, score direction and thresholding. The novelty/outlier guide supplies the complementary question: what population did the training sample represent? Read those choices together before treating a ranked list as an automated decision system.
Make a prediction, then check
Each tree uses four of 1,000 records. A query has mean corrected path 13/6. What is its paper-style anomaly score?
Learning objectives
- Explain random isolation without supervised split scoring and inspect original-row subsamples.
- Calculate corrected paths, harmonic reference scales and score direction with explicit duplicate/depth behavior.
- Separate geometric ranking, threshold choice and operational anomaly meaning.
Prerequisites & connections
Explore related knowledge →References
- Isolation Forest
Fei Tony Liu; Kai Ming Ting; Zhi-Hua Zhou · 2008 - IsolationForest — scikit-learn 1.7.2
scikit-learn developers - Novelty and Outlier Detection — scikit-learn 1.7.2
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Root AI cross-review suggested explicitly stating that sample size two cannot rank queries and distinguishing corrected length four from four actual edges. Both languages now state the size-two degeneracy; the English edge wording was corrected. No algorithm change.
- Eight tests pass. The harmonic table through c(10) is checked by the independently derived uniform-rank-split recurrence. Terminal orthotope enumeration independently verifies six models, 24 fitted trees, 48 query reports and 192 per-tree paths, including bag membership counts and boundary routing, without following the production query traversal.
- Two scores checked with 70-digit Decimal logarithm/exponential. The main center path is 88/21, remote path 9/7; scores round to 0.367294 and 0.735425. The remote point and a ten-times farther point have identical complete outputs. Verified arithmetic versus geometric score aggregation, zero-depth and all-identical score 1/2 (including a novel query), and exact <= routing at a stored threshold.
- Checked distinct indices within bags, separate sample/cut streams across depth changes, repeated seeds, input/model preservation, empty prediction queries, five default-depth sample sizes and exact positive-affine invariance. Rejects seven invalid matrix forms, eleven parameter combinations, five invalid query forms and four invalid correction arguments. Remaining duplication and finite-grid differences are explicit in prose.
- Complete bilingual original articles share one complete Python program and eight stdout lines. Strict MDX/KaTeX and actual React HTML pass with four identical displays, six anchors and four answered exercises; all four math annotations match. Full Humanizer technical reread completed. Source-access history remains metadata; research prose concerns contributions and model choices. Review written, AI author checks only; no human review, external-library training, browser acceptance or whole-site build.
- Reread both full articles, four displays, four answers, input contracts and complexity; eight author tests pass. Verified reference-tree harmonic correction versus geometric expectation, average-before-exponentiation, sample-size normalization and score direction; no algorithm defects found.
- Independent external-path identity sums internal subtree sizes plus terminal size times correction and matches36 trees, without a second per-query depth oracle. Another108 queries with five trees each verify sample-size-two paths1, log2 score−1 and score1/2 across repeated vectors, grids and depths.
- Revision explicitly notes that valid sample size two gives every query1/2 and cannot rank. English now says corrected path length four rather than four edges, avoiding confusion with actual depth three. Code/tests unchanged; final bilingual strict MDX/KaTeX/actual HTML passes and five SHA values bind revised files.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Isolation Forest · The author web requests to NJU HTTPS/HTTP and the LAMDA mirror failed. Root subsequently downloaded the listed NJU URL: local isolation-forest-2008.pdf is 258040 bytes, 10 pages; root also extracted page-labelled text. Actually read local text pages 1–4 for authors, isolation definition, stopping, proper binary trees, equations 1–2, BST reference and sampling without replacement; pages 5–6 for Algorithms 1–3, ceil(log2 psi), leaf adjustment and evaluation ranking. The Monash institutional publication record independently gives ICDM 2008, pages 413–422; no conference-day or publication-day assertion in the article. No benchmark reproduction or full-paper visual audit. Paper descriptions are distinguished from our active-feature, interior-grid and <=-left choices.
- IsolationForest — scikit-learn 1.7.2 · Actually opened the fixed 1.7 API, rendered 1.7.2. Read lines 623–680 for randomized feature/threshold construction, max_samples, contamination and without-replacement default; 732–734 for score_samples-offset relation; 766–777 for depth/reference; 789–809 and 945–965 for corrected paths and low-means-abnormal score direction. The article uses the paper-style positive score and does not copy ambiguous prose suggesting arithmetic averaging of individual exponentiated scores. No sklearn execution or exact source-code/numeric-approximation compatibility claim.
- Novelty and Outlier Detection — scikit-learn 1.7.2 · Actually read fixed 1.7.2 guide lines 69–94, especially fitting-sample contamination versus clean-reference novelty assumptions and -1/+1 labels/thresholds. Lines 111–123 provide method/data context. The article does not treat the guide’s general density-language or confidence wording as a calibrated-probability guarantee for Isolation Forest.
- Isolation Forest · Root downloaded listed NJU original with TLS verification (258040 bytes,10 pages), extracted local page-labelled text and read §2 path length/BST reference/equations1–2 plus Algorithms1–3 and evaluation stage on pp.3–6. Checked ceil(log2 sample size), external-node correction and averaging paths before exponentiation. Continuous/strict-left original differs from explicit finite-grid/active-feature/<= teaching choices. No full visual or benchmark audit.
- IsolationForest — scikit-learn 1.7.2 · Independently opened fixed1.7.2 API, read lines732–734 for decision_function=score_samples-offset and contamination-controlled training threshold, plus945–965 for opposite paper-score direction and lower-means-more-abnormal. No library execution or source-code/approximation equivalence claim.
- Novelty and Outlier Detection — scikit-learn 1.7.2 · Independently read fixed1.7.2 outlier guide lines71–94: fitting-sample contamination versus clean novelty reference, prediction labels and threshold role. Article does not adopt generalized density wording as universal anomaly semantics or interpret a score as calibrated probability.
Related topics