#270Isolation Forest Anomaly ScoreMediumStatisticsDecision TreesAsked atMeta · Amazon · Google
Isolation Forest Anomaly Score
Background
Isolation Forest is a tree-based anomaly detector: random partitions isolate anomalies in shorter path lengths than normal points. The anomaly score is the average path length, normalised by the expected path length under a binary search tree on leaves. Standard tabular fraud / outlier baseline.
Problem statement
Implement isolation_score(x, X, n_trees=50, sample_size=64, seed=0):
- Build
n_treesisolation trees on i.i.d. subsamples of sizesample_sizefromX. - Each tree: random feature, random split in , recurse; track path length to isolate
x. - Average path length across trees. Normalise:
Score near = anomaly; score near = normal.
Input
x— 1-Dnp.ndarrayof length .X— 2-Dnp.ndarrayshape , the training data.n_trees—int, number of trees (default50).sample_size—int, subsample size per tree (default64).seed—int, RNG seed.
Output
Returns a Python float in .
Examples
Example 1 — outlier has higher score than inlier
Input: X ~ N(0, 1) (200 rows, 2 dim); compare x=0 vs x=10
Output: score(x=10) > score(x=0)
Example 2 — bounded in [0, 1]
Input: any valid query against any data
Output: 0.0 <= score <= 1.0
Example 3 — reproducible
Input: same seed
Output: identical score across calls
Constraints
sample_sizeis capped atlen(X).- Recursion depth capped at to avoid infinite splits on constant features.
- Returns Python
float.
Notes
- Subsample size matters. The published default is ; smaller subsamples isolate anomalies faster but are noisier. is a reasonable interview-grade default.
- Multivariate vs univariate. This is the classic axis-aligned version. Extended IsoForest uses random hyperplane splits — better for high-dim correlated features.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference: deterministic score for a fixed outlier query
- •Example: outlier scores higher than an inlier
- •Sample query: score lies in [0, 1]