Sub topic 14
Extended Isolation Forest and other alternatives
This chapter assumes you have read the earlier chapters on isolation trees, path length, the anomaly score, and the limitations of axis-parallel splits. You should be comfortable with NumPy and scikit-learn. The chapter covers a fix for the main weakness of the standard algorithm, Extended Isolation Forest (EIF). It then surveys other detectors and gives criteria for choosing among them.
The problem EIF addresses
A standard isolation tree picks one feature and one split value at each node, so every cut is parallel to a coordinate axis. Every region the tree creates is an axis-aligned box.
This has a visible side effect. Suppose your normal data lies along a diagonal band. Boxes fit a diagonal poorly. Regions off the band but aligned with the band's x or y range can receive path lengths similar to regions on the band. If you plot the score over the plane, you see faint rectangular "ghost" stripes extending along the axes. A point inside a ghost stripe gets a lower anomaly score than it deserves.
The stripes are an artifact of the split geometry. They are not a property of your data.
How Extended Isolation Forest works
EIF (Hariri, Kind and Brunner, 2018) changes only the split rule. At each node it draws:
- A random normal vector
nwith one Gaussian-distributed component per feature. This sets the slope of a hyperplane. - A random intercept point
p, drawn uniformly within the range of the data at that node.
A point x goes left if (x - p) · n <= 0 and right otherwise. The cut is a tilted hyperplane instead of an axis-aligned line.
Everything else is unchanged. Trees are built on subsamples, grown to a depth limit of about ceil(log2(psi)), and scored with the same formula s(x, n) = 2^(-E[h(x)] / c(n)).
The paper also defines an extension level. It is the number of coordinates of n that are set to zero. A level of d - 1 (fully extended) uses all coordinates. A level of 0 zeroes out all but one coordinate, which gives axis-parallel splits, so level 0 is the standard algorithm.
A minimal implementation
The code below implements fully extended trees in plain NumPy. It then compares the result with scikit-learn on a diagonal band of normal data. The two test points share the same x value. One lies on the band and one lies off it, inside the bounding box of the training data.
import numpy as np
from sklearn.ensemble import IsolationForest
EULER_GAMMA = 0.5772156649
def c(n):
if n <= 1:
return 0.0
if n == 2:
return 1.0
return 2.0 * (np.log(n - 1) + EULER_GAMMA) - 2.0 * (n - 1) / n
def build(X, depth, max_depth, rng):
if depth >= max_depth or len(X) <= 1:
return (depth + c(len(X)),)
normal = rng.normal(size=X.shape[1])
point = rng.uniform(X.min(axis=0), X.max(axis=0))
mask = (X - point) @ normal <= 0
if mask.all() or not mask.any():
return (depth + c(len(X)),)
return (normal, point,
build(X[mask], depth + 1, max_depth, rng),
build(X[~mask], depth + 1, max_depth, rng))
def path_length(x, node):
if len(node) == 1:
return node[0]
normal, point, left, right = node
child = left if (x - point) @ normal <= 0 else right
return path_length(x, child)
def fit_forest(X, n_trees=100, sample_size=256, seed=0):
rng = np.random.default_rng(seed)
psi = min(sample_size, len(X))
max_depth = int(np.ceil(np.log2(psi)))
trees = []
for _ in range(n_trees):
idx = rng.choice(len(X), size=psi, replace=False)
trees.append(build(X[idx], 0, max_depth, rng))
return trees, psi
def score(X, forest):
trees, psi = forest
mean_h = np.array([np.mean([path_length(x, t) for t in trees]) for x in X])
return 2.0 ** (-mean_h / c(psi))
rng = np.random.default_rng(1)
t = rng.normal(size=1000)
X = np.column_stack([t, t + 0.15 * rng.normal(size=1000)]) # diagonal band
tests = np.array([[1.5, 1.5], # on the band
[1.5, -1.5]]) # off the band, same x value
standard = IsolationForest(random_state=0).fit(X)
extended = fit_forest(X)
print("standard:", -standard.score_samples(tests))
print("extended:", score(tests, extended))Both detectors should rate the off-band point as more anomalous. The extended forest usually separates the two points by a wider margin, because its tilted cuts follow the band. Exact numbers depend on the seeds. The two scores are on the same 0 to 1 scale, since scikit-learn's score_samples returns the negative of the paper's score.
This sketch loops in Python and is slow. Use it to understand the method, not for production.
Using a library
You do not need to write your own forest.
eifis the reference implementation from the paper's authors. It exposes an extension level directly.isotreeis a fast C++ implementation with a Python interface. Itsndimparameter controls how many columns each split combines, sondim=1is axis-parallel and larger values give extended splits. It also handles missing values and categorical columns natively, and adds options such as scoring by density.
Check each library's current documentation before relying on argument names. Both are separate installs from scikit-learn, and their APIs differ from IsolationForest.
Trade-offs of extended splits
| Aspect | Standard splits | Extended splits |
|---|---|---|
| Score map | Axis-aligned ghost stripes | Smoother, follows data shape |
| Per-node cost | One feature | Dot product over all features |
| Interpretability | Each split names one feature | Splits mix features, so per-feature explanations are harder |
| Sparse or high-dimensional data | Cheap | More expensive, and random directions may carry little signal |
| Library support | Built into scikit-learn | Needs a separate package |
Other alternatives
Isolation-based methods are one family among several. Each family makes a different assumption about what "abnormal" means.
| Method | Assumption | Strengths | Weaknesses |
|---|---|---|---|
| Local Outlier Factor (LOF) | An outlier is in a region less dense than its neighbors | Handles clusters of different density | Needs neighbor search, scales poorly, sensitive to `n_neighbors` |
| One-Class SVM | Normal data lies inside a learned boundary | Flexible with a kernel | Slow on large data, needs scaling and kernel tuning |
| Elliptic Envelope | Normal data is roughly Gaussian | Fast, simple | Fails on multimodal or skewed data |
| PCA reconstruction error | Normal data lies near a low-dimensional subspace | Good for correlated features | Misses anomalies within the subspace |
| Autoencoder | Normal data can be compressed and rebuilt well | Handles images, sequences, complex structure | Needs training, tuning, and more data |
| Robust Random Cut Forest | Like isolation, but built for streams | Online updates | Different tooling |
| HBOS or ECOD | Features can be scored independently | Very fast, parameter-light | Blind to feature interactions |
In scikit-learn, LocalOutlierFactor, OneClassSVM, and EllipticEnvelope follow the same fit, predict and score_samples pattern you already know. For LocalOutlierFactor, call score_samples only if you create it with novelty=True. Otherwise it scores just the training data through negative_outlier_factor_. The PyOD library collects many detectors, including HBOS and ECOD, behind one interface, which makes side-by-side comparison easy.
Choosing a detector
Start with these questions:
- Do you have labels, even a few? Use them to compare candidates with ROC AUC or average precision, as in the evaluation chapter. Do not pick a detector by taste.
- How large is the data? Isolation Forest scales roughly linearly because of subsampling. LOF and One-Class SVM become costly on large datasets.
- Is the structure local or global? If clusters have very different densities, LOF can beat isolation methods. If anomalies are globally rare, isolation works well.
- Are features correlated? Consider EIF or PCA-based scoring.
- Do you need to explain each flag? Standard isolation trees and per-feature methods are easier to explain than extended splits or autoencoders.
Common mistakes
- Switching to EIF to fix poor results that actually come from a wrong threshold or contamination value. Check the threshold first.
- Comparing raw scores across different detectors. Scales and directions differ, so compare rankings with ROC AUC or average precision.
- Using an unscaled feature matrix with distance-based methods such as LOF or One-Class SVM. Isolation trees are insensitive to feature scale, but these methods are not.
- Evaluating on the same data used to tune the detector, then trusting the number.
Exercise
Your normal data lies along a diagonal band, and a standard Isolation Forest gives low anomaly scores to points off the band that sit in the same x or y range as the data. Explain why, and name one change that addresses it.
Show answer
Standard isolation trees cut along one feature at a time, so they carve the space into axis-aligned boxes. Boxes cannot follow a diagonal band, which produces ghost regions along the axes where off-band points receive path lengths similar to on-band points. Extended Isolation Forest replaces each cut with a random tilted hyperplane, defined by a random normal vector and intercept, so the splits follow the data's orientation.
Exercise
You have 5 million rows, 40 mostly independent numeric features, and no labels. Which detector from this chapter do you try first, and why not LOF?
Show answer
Start with the standard Isolation Forest. It scales roughly linearly with data size because each tree uses a small subsample, and independent features give EIF little advantage. LOF needs neighbor searches over the whole dataset, which is costly at 5 million rows.