Algorithm Search⌘K

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.

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
Properties
randomizednot exactofflinerecursive
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 XX of nn points in Rd\mathbb{R}^d, a number of trees tt and a subsample size ψ\psi. The output is a score s(z)∈(0,1]s(z) \in (0, 1] for any point zz. A score close to 1 means zz 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 c(m)c(m), the average path length of an unsuccessful search in a binary search tree of mm keys:

c(m)=2H(m−1)−2(m−1)m,H(i)≈ln⁡i+0.5772156649,c(m) = 2 H(m - 1) - \frac{2 (m - 1)}{m}, \qquad H(i) \approx \ln i + 0.5772156649,

with c(2)=1c(2) = 1 and c(m)=0c(m) = 0 for m≤1m \le 1. Then s(z)=2−E[h(z)]/c(ψ)s(z) = 2^{-E[h(z)] / c(\psi)}, where h(z)h(z) is the path length of zz in one tree and the mean is over the trees.

The algorithm

  1. ITREE(X, e, l) ▷ X is a set of points, e the current depth, l the height limit
  2. 1if e ≥ l or |X| ≤ 1 or all points of X are equal then
  3. 2return a leaf with size |X|
  4. 3q ← a random attribute among those that are not constant on X
  5. 4p ← a uniform random value in (min of attribute q on X, max of attribute q on X]
  6. 5return a node (q, p, ITREE({x ∈ X : x_q < p}, e + 1, l), ITREE({x ∈ X : x_q ≥ p}, e + 1, l))
  7. IFOREST(X, t, ψ)
  8. 6l ← ⌈log2 ψ⌉
  9. 7for i ← 1 to t do
  10. 8X' ← ψ points of X drawn without replacement
  11. 9T_i ← ITREE(X', 0, l)
  12. 10return T_1, …, T_t
  13. PATH-LENGTH(z, T, e)
  14. 11if T is a leaf then return e + c(T.size)
  15. 12if z_q < p for the node (q, p) of T then return PATH-LENGTH(z, T.left, e + 1)
  16. 13return PATH-LENGTH(z, T.right, e + 1)
  17. SCORE(z, T_1, …, T_t, ψ)
  18. 14h ← the mean of PATH-LENGTH(z, T_i, 0) over i
  19. 15return 2^(-h / c(ψ))

Lines L1 to L5 build one isolation tree. The tree stops at depth l=⌈log⁡2ψ⌉l = \lceil \log_2 \psi \rceil, the height of a balanced tree on ψ\psi 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 c(size)c(\text{size}) 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 dd 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 ψ>n\psi > n, the code uses ψ=n\psi = n.

Example

Take ψ=8\psi = 8 points on a line: 1,2,3,4,5,6,7,201, 2, 3, 4, 5, 6, 7, 20. The height limit is l=⌈log⁡28⌉=3l = \lceil \log_2 8 \rceil = 3, and c(8)=3.2963c(8) = 3.2963. One random tree, built by the code with random.Random(2), splits at 18.2618.26, then the left part at 1.991.99, then {2,…,7}\{2, \ldots, 7\} at 5.745.74. The leaves are {20}\{20\} at depth 1, {1}\{1\} at depth 2, and {2,3,4,5}\{2, 3, 4, 5\} and {6,7}\{6, 7\} at depth 3, where the height limit stops the tree.

  • The point 20 goes right at the root and is alone: h=1h = 1.
  • The point 1 goes left twice and is alone: h=2h = 2.
  • The point 4 ends at depth 3 in the leaf {2,3,4,5}\{2, 3, 4, 5\}: h=3+c(4)=3+1.8517=4.8517h = 3 + c(4) = 3 + 1.8517 = 4.8517.

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 2−E[h]/c(8)2^{-E[h]/c(8)}.

point zz E[h(z)]E[h(z)] 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 13/1913/19. 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 (min⁡,max⁡](\min, \max] of a non-constant attribute. So each child is strictly smaller than its parent, the recursion stops, and a tree on ψ\psi points has at most ψ\psi leaves, at most ψ−1\psi - 1 internal nodes and height at most min⁡(l,ψ−1)\min(l, \psi - 1). 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 c(ψ)c(\psi). When E[h(z)]=c(ψ)E[h(z)] = c(\psi) the score is exactly 0.50.5. When E[h(z)]E[h(z)] goes to 0 the score goes to 1, and a mean path longer than c(ψ)c(\psi) gives a score below 0.5. With ψ=256\psi = 256, c(256)=10.2448c(256) = 10.2448.

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 h(z)h(z) and s(z)s(z).

Lemma 1 (each split is proper). At a node built by lines L3 to L5 on a set XX, both children receive at least one point of XX, so each child has fewer points than XX.

Proof. Line L3 picks an attribute qq that is not constant on XX, so a=min⁡x∈Xxq<b=max⁡x∈Xxqa = \min_{x \in X} x_q < b = \max_{x \in X} x_q. Line L4 picks pp with a<p≤ba < p \le b. The point that attains the minimum has xq=a<px_q = a < p, so it goes left. The point that attains the maximum has xq=b≥px_q = b \ge p, so it goes right. □\square

Lemma 2 (termination and size). ITREE(X,0,l)(X, 0, l) stops. The tree has at most ∣X∣|X| leaves and at most ∣X∣−1|X| - 1 internal nodes, and its height is at most min⁡(l,∣X∣−1)\min(l, |X| - 1) for ∣X∣≥1|X| \ge 1.

Proof. By induction on ∣X∣|X|. If line L1 returns a leaf, there is one leaf, no internal node and height 0. Otherwise ∣X∣≥2|X| \ge 2 and e<le < l. By Lemma 1 the children have sizes m1,m2≥1m_1, m_2 \ge 1 with m1+m2=∣X∣m_1 + m_2 = |X|, so each is smaller than ∣X∣|X| and the recursion stops by induction. The leaves number at most m1+m2=∣X∣m_1 + m_2 = |X|, and the internal nodes at most (m1−1)+(m2−1)+1=∣X∣−1(m_1 - 1) + (m_2 - 1) + 1 = |X| - 1. A child at depth e+1e + 1 has height at most ∣X∣−2|X| - 2 below it by induction, and line L1 stops every branch at depth ll, so the height is at most min⁡(l,∣X∣−1)\min(l, |X| - 1). □\square

Lemma 3 (partition). The multisets of points that reach the leaves partition XX, and the leaf that a point x∈Xx \in X reaches has size equal to the number of points of XX that reach it.

Proof. At each internal node, the test xq<px_q < p sends each point to exactly one child. By induction from the root, each point of XX reaches exactly one leaf, and line L2 records the size of the set at that leaf, which is the set of points routed there. □\square

Lemma 4 (path length). For any point zz and tree TT, PATH-LENGTH(z,T,0)(z, T, 0) returns e+c(m)e + c(m), where ee is the depth of the leaf that zz reaches by the tests zq<pz_q < p and mm is the size of that leaf.

Proof. Lines L12 and L13 apply the same test as line L5 and increase ee by one at each step. By Lemma 2 the path has at most ll steps, so the recursion stops at a leaf, and line L11 returns e+c(m)e + c(m). For a training point, Lemma 3 says the leaf is the one that holds it in the construction. □\square

Lemma 5 (the score). SCORE returns 2−hˉ/c(ψ)2^{-\bar h / c(\psi)}, where hˉ\bar h is the mean path length over the tt trees. For ψ≥2\psi \ge 2 this value is in (0,1](0, 1], it equals 1/21/2 exactly when hˉ=c(ψ)\bar h = c(\psi), and it decreases strictly as hˉ\bar h grows.

Proof. Line L14 is the mean and line L15 the formula. For ψ≥2\psi \ge 2, c(ψ)>0c(\psi) > 0: c(2)=1c(2) = 1, and for m≥3m \ge 3, c(m)=2(ln⁡(m−1)+0.5772156649)−2(m−1)/m≥2(0.6931+0.5772)−2>0c(m) = 2(\ln(m - 1) + 0.5772156649) - 2(m - 1)/m \ge 2(0.6931 + 0.5772) - 2 > 0, and cc increases with mm since the derivative 2/(m−1)−2/m22/(m - 1) - 2/m^2 is positive. Since hˉ≥0\bar h \ge 0, the exponent is at most 0, so the value is in (0,1](0, 1]. The map u↦2−u/cu \mapsto 2^{-u/c} with c>0c > 0 is strictly decreasing and is 1/21/2 at u=cu = c. □\square

Forest. Line L6 sets l=⌈log⁡2ψ⌉l = \lceil \log_2 \psi \rceil. The loop of lines L7 to L9 runs tt times, each time on a sample of ψ\psi points drawn without replacement, which exists because the code uses ψ≤n\psi \le n. By Lemmas 1 to 4 each tree is finite and well formed, and by Lemma 5 the score is the one defined. ■\blacksquare

Complexity

The cost is in the real-RAM model, with s=ψs = \psi.

  • Training. Each level of a tree touches at most ss points, and each touch reads dd attributes to find the non-constant ones and to split. A tree has at most l=⌈log⁡2s⌉l = \lceil \log_2 s \rceil levels, so it takes O(sdlog⁡s)O(s d \log s) time, and the forest takes O(tsdlog⁡s)O(t s d \log s). This does not depend on nn, except for drawing the samples.
  • Scoring. One path has at most ll steps, so scoring nn points takes O(ntlog⁡s)O(n t \log s) time.
  • Space. Each tree has fewer than 2s2 s nodes, so the forest takes O(ts)O(t s) space.

Properties

  • Randomized. The score is a random variable. Its mean over the trees converges to E[h(z)]E[h(z)] as tt grows, by the law of large numbers. The default t=100t = 100 comes from measurements in the paper, not from a bound.
  • Small samples help. The paper reports that small subsamples, with ψ=256\psi = 256 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 H(i)=1+1/2+⋯+1/iH(i) = 1 + 1/2 + \cdots + 1/i, the formula gives c(2)=1c(2) = 1 without a special case. The approximation ln⁡i+0.5772\ln i + 0.5772 is close for large ii 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 O(d)O(d) 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 ee and not e+c(size)e + c(\text{size}), every point in a leaf cut off at depth ll gets the same short path, and dense regions look as anomalous as sparse ones near the limit. Line L11 must add c(size)c(\text{size}).
  • The wrong normalizer. The score must divide by c(ψ)c(\psi), the subsample size, not by c(n)c(n). With c(n)c(n) for n≫ψn \gg \psi, 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 nn points in each tree, ψ=n\psi = n, gives taller trees and more swamping and masking, and costs more. Start from ψ=256\psi = 256.
  • Duplicates. Many copies of one record make a leaf that cannot be split. Line L1 stops there, and line L11 counts the copies through c(size)c(\text{size}).

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.

isolation_forest.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example