Design a system to detect anomalies in a stream using the Isolation Forest algorithm from scratch. Build random binary trees from streaming data points and flag points with short path lengths as anomalies.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Proposed a streaming Isolation Forest that incrementally builds random binary trees by buffering points at leaves, splitting when buffer full and depth allows, and routing new points down tree to compute path lengths for anomaly scoring. This design maintains small buffers per leaf, splits on random features and thresholds from buffer ranges, and uses average path length across the forest to flag anomalies, all built from streaming data without storing full datasets.Refining streaming Isolation Forest with scoring and update separation
Clarified path length calculation by adding expected adjustment for leaf size, distinguishing detection from update steps so scoring uses existing trees before inserting new points. Proposed computing anomaly score with harmonic-based normalization and deferring tree updates after scoring to support accurate streaming detection, with a concrete Python design including path_length and insert methods and streaming usage example.
One of the nice properties of an isolation forest is that you do not have to fit a dense parametric model; you build a set of very simple, random trees and use the number of splits it takes to “isolate” a point as a proxy for how rare it is. Points that are rare tend to get separated from the bulk of the data by very few splits, so their path length from the root to a leaf is short.
On a static data set you would draw (t) random subsamples of size (\psi), recursively split them on random features at random thresholds between the current minimum and maximum until each node contains one point or a maximum depth, and then score new points by walking them down each tree. For a stream you can keep exactly the same scoring mechanism and make the tree building incremental.
A simple streaming design has three components:
A node structure that either holds a split (feature index and threshold) and has two children, or is an “external” node that buffers a few points and their min/max per feature.
A tree that knows its maximum depth and when to turn a buffered external node into an internal split by choosing a random feature and a random threshold between the buffered points’ min and max.
A forest that maintains (t) of these trees, routes incoming points through them to compute a path length, computes an anomaly score, and then updates the trees with the new point.
The standard isolation forest anomaly score for a point (x) is
[
s(x) = 2^{-\frac{E[h(x)]}{c(\psi)}},
]
where (E[h(x)]) is the average path length over your trees, (\psi) is the subsample size used to grow the trees, and (c(\psi)) is the average path length of an unsuccessful search in a binary search tree of size (\psi):
python
import math
def c(n: int) -> float:
if n <= 1:
return 0.0
return 2.0 * sum(1.0 / i for i in range(1, n)) - 2.0 * (n - 1) / n
A simple “from scratch” implementation in Python that builds and updates random binary trees as points stream past could look like this:
python
This implementation starts each tree with a single external node. Each incoming point is first scored by traversing each tree to compute its path length; a short average path yields a score near 1.0. If the score exceeds your chosen threshold, you flag the point as anomalous. Regardless, you then insert the point into each tree. When a leaf’s small buffer exceeds max_buffer and the maximum depth has not been reached, the leaf is turned into an internal split with a randomly chosen feature and split threshold between the buffered points’ minimum and maximum, and the buffered points are pushed down to the children. Because all splits are random, you do not need to store all past data at internal nodes.
To keep up with concept drift in a true unbounded stream you can add ageing/replacement (e.g. rebuild trees periodically from a sliding window or use reservoir sampling to limit the effective sample size per tree), but the core mechanism—building random binary trees from streaming points and flagging points with unusually short path lengths—is captured in the design above.
import random
import math
from typing import List, Optional
class IsolationTreeNode:
def __init__(self, depth: int, max_depth: int, max_buffer: int):
self.depth = depth
self.max_depth = max_depth
self.max_buffer = max_buffer
# split parameters
self.feature: Optional[int] = None
self.threshold: Optional[float] = None
# children
self.left: Optional[IsolationTreeNode] = None
self.right: Optional[IsolationTreeNode] = None
# buffer of points stored at an external node
self.buffer: List[List[float]] = []
def path_length(self, x: List[float]) -> float:
"""Compute the path length of x without modifying the tree."""
if self.left is None and self.right is None:
# external node
if len(self.buffer) <= 1 or self.depth >= self.max_depth:
return float(self.depth)
else:
# if there are n points buffered here, adjust by c(n)
return self.depth + c(len(self.buffer))
# internal node
if x[self.feature] < self.threshold:
return self.left.path_length(x)
else:
return self.right.path_length(x)
def insert(self, x: List[float]):
"""Insert a new point, creating a split when the buffer is too large."""
if self.left is None and self.right is None:
# currently an external node
self.buffer.append(x)
# decide if we should split
if self.depth < self.max_depth and len(self.buffer) > self.max_buffer:
# choose random feature and random threshold based on buffered points
f = random.randrange(len(x))
vals = [p[f] for p in self.buffer]
lo, hi = min(vals), max(vals)
if lo == hi:
# cannot split on this feature; stay as leaf
return
thr = random.uniform(lo, hi)
# create children
self.feature = f
self.threshold = thr
self.left = IsolationTreeNode(self.depth + 1, self.max_depth, self.max_buffer)
self.right = IsolationTreeNode(self.depth + 1, self.max_depth, self.max_buffer)
# redistribute buffered points
for p in self.buffer:
if p[f] < thr:
self.left.insert(p)
else:
self.right.insert(p)
self.buffer = [] # clear buffer
else:
# internal node, delegate insertion
if x[self.feature] < self.threshold:
self.left.insert(x)
else:
self.right.insert(x)
class IsolationTree:
def __init__(self, max_depth: int, max_buffer: int):
self.root = IsolationTreeNode(depth=0, max_depth=max_depth, max_buffer=max_buffer)
def path_length(self, x: List[float]) -> float:
return self.root.path_length(x)
def insert(self, x: List[float]):
self.root.insert(x)
class StreamingIsolationForest:
def __init__(self, n_trees: int = 50, sample_size: int = 256, max_buffer: int = 4):
self.n_trees = n_trees
self.sample_size = sample_size
# maximum tree depth as in the original paper
self.max_depth = math.ceil(math.log2(sample_size))
self.trees = [IsolationTree(self.max_depth, max_buffer) for _ in range(n_trees)]
self.c_psi = c(sample_size)
self.n_seen = 0
def score(self, x: List[float]) -> float:
"""Compute anomaly score of x based on current forest."""
if self.n_seen == 0:
return 0.0
path_lengths = [tree.path_length(x) for tree in self.trees]
avg_path = sum(path_lengths) / len(path_lengths)
return 2.0 ** (-avg_path / self.c_psi)
def update(self, x: List[float]):
"""Insert x into all trees."""
for tree in self.trees:
tree.insert(x)
self.n_seen += 1
def process(self, x: List[float], threshold: float = 0.7) -> bool:
"""Compute score for x, flag if above threshold, then update forest."""
s = self.score(x)
is_anomaly = s > threshold
self.update(x)
return is_anomaly, s
# Example usage
forest = StreamingIsolationForest(n_trees=25, sample_size=128)
for point in stream_of_points():
is_anom, score = forest.process(point, threshold=0.6)
if is_anom:
print("Anomaly:", point, "score", score)