Algorithmcore
Isolation forest
Also called iForest.
Builds random trees that split on random features and values, and scores a point as anomalous when its average path to isolation is short.
- Solves
- Anomaly detection
- Time
- O(t s d log s + n t log s) worst
- Space
- O(t s) extra
- Where
- d = the dimension; n = the number of points scored; s = the subsample size psi; t = the number of trees
- Model
- Real RAM
- Properties
- randomizednot exactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Fei Tony Liu, Kai Ming Ting, Zhi Hua Zhou, 2008
An isolation forest builds many random binary trees on small random samples of the data. Each tree splits the data on a random attribute at a random value until every point is alone. Anomalies are few and different, so they are cut off from the rest after few splits, close to the root. The score of a point comes from its average depth over the trees: a short average path means an anomaly. Liu, Ting and Zhou (2008) proposed it for the anomaly detection problem. It needs no distances and no density, and it trains in time linear in the number of trees and nearly linear in the sample size.
In plain words
Play a guessing game with a table of records. To single out one record, you pick a column at random and a random cut in that column, and keep only the side where the record is. You repeat until the record is alone. A normal record sits among many similar ones, so it takes many cuts to get it alone. An odd record, with a value far from the others in some column, is often alone after one or two cuts.
Do this with many random trees, each built on a small random sample. Average the number of cuts each record needs. Records with a small average are flagged.
The problem
The input is a training set of points in , a number of trees and a subsample size . The output is a score for any point . A score close to 1 means is an anomaly, and a score well below 0.5 means it is normal. Flagging points above a threshold is a separate step, and the threshold is a heuristic.
The score uses the function , the average path length of an unsuccessful search in a binary search tree of keys:
with and for . Then , where is the path length of in one tree and the mean is over the trees.
The algorithm
ITREE(X, e, l) ▷ X is a set of points, e the current depth, l the height limit- 1
if e ≥ l or |X| ≤ 1 or all points of X are equal then - 2
return a leaf with size |X| - 3
q ← a random attribute among those that are not constant on X - 4
p ← a uniform random value in (min of attribute q on X, max of attribute q on X] - 5
return a node (q, p, ITREE({x ∈ X : x_q < p}, e + 1, l), ITREE({x ∈ X : x_q ≥ p}, e + 1, l)) IFOREST(X, t, ψ)- 6
l ← ⌈log2 ψ⌉ - 7
for i ← 1 to t do - 8
X' ← ψ points of X drawn without replacement - 9
T_i ← ITREE(X', 0, l) - 10
return T_1, …, T_t PATH-LENGTH(z, T, e)- 11
if T is a leaf then return e + c(T.size) - 12
if z_q < p for the node (q, p) of T then return PATH-LENGTH(z, T.left, e + 1) - 13
return PATH-LENGTH(z, T.right, e + 1) SCORE(z, T_1, …, T_t, ψ)- 14
h ← the mean of PATH-LENGTH(z, T_i, 0) over i - 15
return 2^(-h / c(ψ))
Lines L1 to L5 build one isolation tree. The tree stops at depth , the height of a balanced tree on points, because only short paths matter: the points of interest are isolated early. Line L3 skips attributes that are constant on the node, so every split separates at least one point from the rest. Line L11 adds at a leaf that still holds several points. This estimates the depth that the rest of an unbuilt subtree would add, so leaves cut off by the height limit are not counted as shallow.
The paper picks the attribute among all attributes. On data with a constant attribute this can produce a node whose split puts all points on one side. Line L3 removes this case. When , the code uses .
Example
Take points on a line: . The height limit is , and . One random tree, built by the code with random.Random(2), splits at , then the left part at , then at . The leaves are at depth 1, at depth 2, and and at depth 3, where the height limit stops the tree.
- The point 20 goes right at the root and is alone: .
- The point 1 goes left twice and is alone: .
- The point 4 ends at depth 3 in the leaf : .
Over many trees the mean path length converges to its expectation. The table gives the exact expectations for one tree on all eight points, computed by a recursion over all the random choices, and the score .
| point | score | |
|---|---|---|
| 20 | 1.3683 | 0.7500 |
| 10 (not in the data) | 2.9466 | 0.5381 |
| 1 | 3.1115 | 0.5198 |
| 7 | 3.4201 | 0.4871 |
| 4 | 4.2209 | 0.4117 |
The point 20 is isolated at the root whenever the first split falls in the gap from 7 to 20, which has probability . Its score 0.75 is the highest. The points at the ends of the cluster, 1 and 7, score near 0.5, and the middle of the cluster scores lowest.
Correctness
The isolation forest is a heuristic detector: there is no theorem that it ranks anomalies first. What can be proved is that the procedures compute what they define. Every split of line L5 sends at least one point to each side, because the split value lies in of a non-constant attribute. So each child is strictly smaller than its parent, the recursion stops, and a tree on points has at most leaves, at most internal nodes and height at most . The leaves partition the sample, and PATH-LENGTH follows the same test as the split, so a training point reaches the leaf that holds it. The proofs section below gives the details.
The score is calibrated by . When the score is exactly . When goes to 0 the score goes to 1, and a mean path longer than gives a score below 0.5. With , .
Proof: Isolation trees terminate, partition the sample, have bounded height, and give the defined path lengths and scoresfull
The isolation forest is a heuristic detector, so the claim here is not that it finds the anomalies. The claim is that the procedures are well defined and compute the quantities of the problem statement: the trees stop, have the stated size and height, partition the sample, and PATH-LENGTH and SCORE return and .
Lemma 1 (each split is proper). At a node built by lines L3 to L5 on a set , both children receive at least one point of , so each child has fewer points than .
Proof. Line L3 picks an attribute that is not constant on , so . Line L4 picks with . The point that attains the minimum has , so it goes left. The point that attains the maximum has , so it goes right.
Lemma 2 (termination and size). ITREE stops. The tree has at most leaves and at most internal nodes, and its height is at most for .
Proof. By induction on . If line L1 returns a leaf, there is one leaf, no internal node and height 0. Otherwise and . By Lemma 1 the children have sizes with , so each is smaller than and the recursion stops by induction. The leaves number at most , and the internal nodes at most . A child at depth has height at most below it by induction, and line L1 stops every branch at depth , so the height is at most .
Lemma 3 (partition). The multisets of points that reach the leaves partition , and the leaf that a point reaches has size equal to the number of points of that reach it.
Proof. At each internal node, the test sends each point to exactly one child. By induction from the root, each point of reaches exactly one leaf, and line L2 records the size of the set at that leaf, which is the set of points routed there.
Lemma 4 (path length). For any point and tree , PATH-LENGTH returns , where is the depth of the leaf that reaches by the tests and is the size of that leaf.
Proof. Lines L12 and L13 apply the same test as line L5 and increase by one at each step. By Lemma 2 the path has at most steps, so the recursion stops at a leaf, and line L11 returns . For a training point, Lemma 3 says the leaf is the one that holds it in the construction.
Lemma 5 (the score). SCORE returns , where is the mean path length over the trees. For this value is in , it equals exactly when , and it decreases strictly as grows.
Proof. Line L14 is the mean and line L15 the formula. For , : , and for , , and increases with since the derivative is positive. Since , the exponent is at most 0, so the value is in . The map with is strictly decreasing and is at .
Forest. Line L6 sets . The loop of lines L7 to L9 runs times, each time on a sample of points drawn without replacement, which exists because the code uses . By Lemmas 1 to 4 each tree is finite and well formed, and by Lemma 5 the score is the one defined.
Complexity
The cost is in the real-RAM model, with .
- Training. Each level of a tree touches at most points, and each touch reads attributes to find the non-constant ones and to split. A tree has at most levels, so it takes time, and the forest takes . This does not depend on , except for drawing the samples.
- Scoring. One path has at most steps, so scoring points takes time.
- Space. Each tree has fewer than nodes, so the forest takes space.
Properties
- Randomized. The score is a random variable. Its mean over the trees converges to as grows, by the law of large numbers. The default comes from measurements in the paper, not from a bound.
- Small samples help. The paper reports that small subsamples, with as the default, work well, because they reduce swamping (normal points near anomalies that look anomalous) and masking (groups of anomalies that hide each other). This is a measurement.
- No distances. Only comparisons of single attributes are used. If one attribute is multiplied by a positive number or shifted, the split values move with it and the distribution of the trees, as partitions of the points, does not change. So there is no need to scale the attributes to the same units.
- Axis parallel. Splits are parallel to the axes. An anomaly that differs from the data only in a combination of attributes, not in any single one, is isolated late.
Variants and improvements
- Exact harmonic numbers. With the exact , the formula gives without a special case. The approximation is close for large and is the one in the paper.
- Random hyperplanes. Split on a random linear combination of the attributes instead of one attribute. This removes the artifacts of axis parallel splits at the cost of work per test.
- Split selection. Choose among a few random candidate splits by a criterion that separates clusters better, which helps for anomalies in groups.
- Streams. Build trees on recent windows and replace old trees, so the model follows a slow change in the normal data.
When to use it
Use it on large tabular data with many numeric attributes where anomalies differ from normal points in at least some single attributes. It is fast, needs few parameters, and works without labels and without a distance. Use the local outlier factor when the anomalies are local, close to dense clusters, and use a one-class SVM when a smooth boundary in a kernel space fits the normal data better.
Pitfalls
- No height limit adjustment. If line L11 returns only and not , every point in a leaf cut off at depth gets the same short path, and dense regions look as anomalous as sparse ones near the limit. Line L11 must add .
- The wrong normalizer. The score must divide by , the subsample size, not by . With for , all scores move toward 1.
- Split value from the whole data. Line L4 must draw the split between the minimum and the maximum of the points at the node, not of the whole data set. A split outside the node's range sends all points to one side and does no work.
- Too large a sample. Using all points in each tree, , gives taller trees and more swamping and masking, and costs more. Start from .
- Duplicates. Many copies of one record make a leaf that cannot be split. Line L1 stops there, and line L11 counts the copies through .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isolation-forest/. The authors are listed in prov/Z6EQPQ.jsonl.
import math
import random
from dataclasses import dataclass
from typing import Sequence, Union
Point = Sequence[float]
EULER_GAMMA = 0.5772156649
@dataclass(frozen=True)
class Leaf:
size: int
@dataclass(frozen=True)
class Node:
attribute: int
value: float
left: "Tree"
right: "Tree"
Tree = Union[Leaf, Node]
@dataclass(frozen=True)
class Forest:
trees: tuple[Tree, ...]
psi: int
def c_factor(n: int) -> float:
"""Average path length of an unsuccessful search in a binary search tree of n keys.
Uses c(n) = 2 H(n - 1) - 2 (n - 1) / n with H(i) = ln i + 0.5772156649, as in
Liu, Ting and Zhou, and the conventions c(2) = 1 and c(n) = 0 for n <= 1.
Cost: O(1).
"""
if n <= 1:
return 0.0
if n == 2:
return 1.0
return 2.0 * (math.log(n - 1) + EULER_GAMMA) - 2.0 * (n - 1) / n
def build_itree(x: Sequence[Point], rng: random.Random, limit: int, e: int = 0) -> Tree:
"""Build one isolation tree on the points x, at depth e, with height limit `limit`.
The split attribute is drawn among the attributes that are not constant on x,
so a node always splits a set of points that are not all equal.
Precondition: all points have the same dimension. Cost: O(|x| limit d) time.
"""
d = len(x[0]) if x else 0
spread = [a for a in range(d) if min(p[a] for p in x) < max(p[a] for p in x)] if len(x) > 1 else []
if e >= limit or len(x) <= 1 or not spread: # @line L1
return Leaf(len(x)) # @line L2
q = spread[rng.randrange(len(spread))] # @line L3
lo = min(p[q] for p in x)
hi = max(p[q] for p in x)
v = hi - rng.random() * (hi - lo) # @line L4
if v <= lo: # rounding guard, so that v stays in (lo, hi]
v = hi
left = [p for p in x if p[q] < v]
right = [p for p in x if p[q] >= v]
return Node(q, v, build_itree(left, rng, limit, e + 1), build_itree(right, rng, limit, e + 1)) # @line L5
def isolation_forest(x: Sequence[Point], t: int = 100, psi: int = 256, seed: int = 0) -> Forest:
"""Build t isolation trees, each on a sample of min(psi, n) points without replacement.
Precondition: n = len(x) >= 1, t >= 1, psi >= 1. Cost: O(t psi log psi) expected
time for the trees and O(t psi) space.
"""
if not x or t < 1 or psi < 1:
raise ValueError("need at least one point, t >= 1 and psi >= 1")
rng = random.Random(seed)
psi = min(psi, len(x))
limit = math.ceil(math.log2(psi)) if psi > 1 else 0 # @line L6
trees = []
for _ in range(t): # @line L7
sample = [x[i] for i in rng.sample(range(len(x)), psi)] # @line L8
trees.append(build_itree(sample, rng, limit)) # @line L9
return Forest(tuple(trees), psi) # @line L10
def path_length(z: Point, tree: Tree) -> float:
"""Path length h(z) of the point z in one tree, with the c(size) adjustment at the leaf.
Cost: O(height) time.
"""
e = 0
while isinstance(tree, Node):
if z[tree.attribute] < tree.value: # @line L12
tree = tree.left
else:
tree = tree.right # @line L13
e += 1
return e + c_factor(tree.size) # @line L11
def anomaly_score(z: Point, forest: Forest) -> float:
"""Return s(z, psi) = 2^(-E[h(z)] / c(psi)), a value in (0, 1].
Values close to 1 mean anomaly; values well below 0.5 mean normal.
Cost: O(t height) time.
"""
h = sum(path_length(z, tr) for tr in forest.trees) / len(forest.trees) # @line L14
cp = c_factor(forest.psi)
if cp == 0.0:
return 1.0
return 2.0 ** (-h / cp) # @line L15
test_isolation_forest.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isolation-forest/. The authors are listed in prov/Z6EQPQ.jsonl.
import math
import random
from functools import lru_cache
import pytest
from isolation_forest import Leaf, Node, anomaly_score, build_itree, c_factor, isolation_forest, path_length
def test_c_factor() -> None:
assert c_factor(0) == 0.0 and c_factor(1) == 0.0 and c_factor(2) == 1.0
assert math.isclose(c_factor(256), 10.244770920, abs_tol=1e-8)
assert math.isclose(c_factor(8), 3.296251628, abs_tol=1e-8)
# The score is 0.5 when the mean path length equals c(psi).
assert math.isclose(2 ** (-c_factor(256) / c_factor(256)), 0.5)
def test_defaults_and_edges() -> None:
x = [(float(i),) for i in range(300)]
f = isolation_forest(x, t=3, seed=1)
assert f.psi == 256 and len(f.trees) == 3
assert all(depth(tr) <= 8 for tr in f.trees) # ceil(log2 256) = 8
one = isolation_forest([(1.0, 2.0)], t=2)
assert one.trees == (Leaf(1), Leaf(1)) and anomaly_score((0.0, 0.0), one) == 1.0
same = isolation_forest([(3.0, 3.0)] * 5, t=2)
assert same.trees == (Leaf(5), Leaf(5))
with pytest.raises(ValueError):
isolation_forest([], t=1)
def depth(tree) -> int:
if isinstance(tree, Leaf):
return 0
return 1 + max(depth(tree.left), depth(tree.right))
def check_tree(tree, pts, limit, e=0) -> None:
"""Brute force: refilter the points at every node and compare with the tree."""
if isinstance(tree, Leaf):
assert tree.size == len(pts)
assert e >= limit or len(pts) <= 1 or all(p == pts[0] for p in pts)
return
assert e < limit and len(pts) >= 2
col = [p[tree.attribute] for p in pts]
assert min(col) < tree.value <= max(col)
left = [p for p in pts if p[tree.attribute] < tree.value]
right = [p for p in pts if p[tree.attribute] >= tree.value]
assert left and right
check_tree(tree.left, left, limit, e + 1)
check_tree(tree.right, right, limit, e + 1)
def leaf_of(z, tree, pts, e=0):
if isinstance(tree, Leaf):
return e, len(pts)
a, v = tree.attribute, tree.value
if z[a] < v:
return leaf_of(z, tree.left, [p for p in pts if p[a] < v], e + 1)
return leaf_of(z, tree.right, [p for p in pts if p[a] >= v], e + 1)
def test_random_trees_against_refiltering() -> None:
rng = random.Random(4242)
for _ in range(500):
n = rng.randint(1, 12)
d = rng.randint(1, 3)
pts = [tuple(float(rng.randint(-3, 3)) for _ in range(d)) for _ in range(n)]
limit = rng.randint(0, 6)
tree = build_itree(pts, random.Random(rng.random()), limit)
check_tree(tree, pts, limit)
z = tuple(float(rng.randint(-4, 4)) for _ in range(d))
e, size = leaf_of(z, tree, pts)
assert math.isclose(path_length(z, tree), e + c_factor(size))
def exact_expected_path(pts, z, limit):
"""E[h(z)] for one tree on all of pts, by exact recursion over the random choices."""
n = len(pts)
d = len(pts[0])
@lru_cache(maxsize=None)
def rec(members, e):
sub = [pts[i] for i in members]
spread = [a for a in range(d) if min(p[a] for p in sub) < max(p[a] for p in sub)]
if e >= limit or len(members) <= 1 or not spread:
return e + c_factor(len(members))
total = 0.0
for a in spread:
lo = min(p[a] for p in sub)
hi = max(p[a] for p in sub)
cuts = sorted({p[a] for p in sub} | ({z[a]} if lo < z[a] < hi else set()))
for b0, b1 in zip(cuts, cuts[1:]):
# For a split value in (b0, b1] the left part is {x_a <= b0}.
go_left = z[a] <= b0
side = frozenset(i for i in members if (pts[i][a] <= b0) == go_left)
total += (b1 - b0) / (hi - lo) / len(spread) * rec(side, e + 1)
return total
return rec(frozenset(range(n)), 0)
def test_mean_path_matches_exact_expectation() -> None:
rng = random.Random(9)
for _ in range(12):
n = rng.randint(2, 6)
d = rng.randint(1, 2)
pts = [tuple(rng.uniform(0, 10) for _ in range(d)) for _ in range(n)]
z = tuple(rng.uniform(-2, 12) for _ in range(d))
limit = rng.randint(1, 5)
want = exact_expected_path(pts, z, limit)
trees = 2000
tr_rng = random.Random(rng.random())
got = sum(path_length(z, build_itree(pts, tr_rng, limit)) for _ in range(trees)) / trees
# Each path length is in [0, 7]; by Hoeffding the mean of 2000 is within 0.4 except with probability below 1e-5.
assert abs(got - want) <= 0.4
def test_three_points_on_a_line() -> None:
# Points 0, a, 1: the point 0 is isolated at depth 1 with probability a, else at depth 2.
a = 0.3
want = exact_expected_path(((0.0,), (a,), (1.0,)), (0.0,), 10)
assert math.isclose(want, 2 - a)
def test_planted_outlier_scores_highest() -> None:
rng = random.Random(17)
x = [(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(500)]
f = isolation_forest(x, t=50, psi=128, seed=3)
outlier = anomaly_score((6.0, 6.0), f)
normal = [anomaly_score(p, f) for p in x[:100]]
assert outlier > 0.6
assert outlier > max(normal)
assert sum(normal) / len(normal) < 0.5
History
Liu, Ting and Zhou presented the isolation forest at ICDM 2008. Earlier detectors built a model of the normal data, by distance, density or a boundary, and flagged points that the model fits badly. The isolation forest instead measures how easy it is to isolate a point, which needs neither a distance nor a density. The 2012 journal version in ACM TKDD added more analysis of the subsample size and the score. Later work added splits on random hyperplanes and versions for data streams.
References
- Fei Tony Liu, Kai Ming Ting and Zhi-Hua Zhou, Isolation-based anomaly detection, ACM Transactions on Knowledge Discovery from Data 6(1), article 3, 2012, the isolation tree, the training and evaluation stages, the path length adjustment c(n), the anomaly score s(x, n), and the measured effect of the subsample size and the number of trees
- Fei Tony Liu, Kai Ming Ting and Zhi-Hua Zhou, Isolation forest, IEEE ICDM 2008, pages 413 to 422, the first version of the method, with the definitions of the isolation tree, the path length and the anomaly score
- Varun Chandola, Arindam Banerjee and Vipin Kumar, Anomaly detection, a survey, ACM Computing Surveys 41(3), article 15, 2009, Sections 4 to 9 (the families of anomaly detection techniques that model the normal data)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Z6EQPQ Edit this page History Report an error Markdown