Outlier detection: isolation forest and LOF
Outlier detection using Isolation Forest and LOF: two complementary methods — Isolation Forest isolates anomalies by random partitioning and path lengths, while Local Outlier Factor (LOF) scores points by how much their local density deviates from neighbours.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
An engineer uses outlier detection to find data points that do not follow expected patterns: to detect fraud, sensor failures, defective parts, or bad samples before training ML models. Isolation Forest and LOF are two widely used, efficient methods: Isolation Forest is fast and works well in high dimensions; LOF is density-based and explains local anomalyness.
Key ideas
Start from first principles and define terms.
Outlier (or anomaly): a data point whose behaviour significantly differs from the majority of the data according to some criterion (distance, density, or generation process). This is a formal concept only relative to the chosen definition and parameters (e.g., neighbourhood size k).
Isolation: the idea that anomalies are few and different, so they are easier to separate (isolate) from the rest of the data by random partitioning. The fewer random splits needed to isolate a point, the more anomalous it is.
Isolation tree (iTree): a binary tree built by recursively partitioning the data. At each internal node, choose a feature and a split value (in the original algorithm: chosen randomly from range). Stop when node size is 1 or tree height reaches a limit. Each leaf corresponds to a subset; the path length from root to a leaf is the number of splits required to isolate examples in that leaf. In Isolation Forest, each tree is built on a subsample of size psi (e.g., 256), and the height limit is l = ceil(log2(psi)).
Average path length E(h(x)): for a point x, compute the path length h(x) in each tree of the forest and take the average. Smaller average path length means more anomalous.
Normalization constant c(n): to make anomaly scores independent of dataset size, use the average path length of unsuccessful search in a binary search tree (BST). For sample size n,
- Harmonic number H(m) = 1 + 1/2 + 1/3 + ... + 1/m.
c(n) = 2·H(n-1) - 2·(n-1)/nis used as expected path length in a random BST of n samples.
Isolation Forest anomaly score s(x): defined so that values near 1 are highly anomalous and values around 0.5 are normal. Exact formula below in Formulas.
Assumptions and remarks for Isolation Forest:
- Assumes anomalies are few and different: if anomalies lie inside dense clusters with many similar points, they may not be isolated early.
- Random splits make the algorithm randomized; use many trees and a random seed for reproducibility.
- Works well in higher dimensions because it does not compute pairwise distances. Complexity: building t trees on subsamples of size psi is O(t * psi * log psi); scoring m points is O(t * m * log psi).
LOF (Local Outlier Factor) — density-based approach (definitions and steps):
k-distance(p): For a point p and integer k, the k-distance(p) is the distance from p to its k-th nearest neighbour. (If multiple points are at same distance and produce >k neighbours, include them in the k-neighbourhood set.)
k-neighbourhood N_k(p): set of points within distance <= k-distance(p) from p (may have size ≥ k due to ties).
Reachability distance reach-dist_k(p, o) = max{ k-distance(o), dist(p, o) }. This prevents extremely small distances (very close points) from making densities extremely large.
Local reachability density (LRD) of p: the inverse of the average reachability distance of p to its k-neighbours.
- lrd_k(p) = 1 / ( (1/|N_k(p)|) · sum_{o in N_k(p)} reach-dist_k(p, o) ).
Local Outlier Factor LOF_k(p): compares the local density of p to the local densities of its neighbours.
- LOF_k(p) = (1/|N_k(p)|) · sum_{o in N_k(p)} ( lrd_k(o) / lrd_k(p) ).
- Interpretation: LOF ≈ 1 means point p has about same local density as neighbours (normal). LOF > 1 indicates p is less dense than neighbours (possible outlier). LOF much larger than 1 is a stronger outlier.
Assumptions and remarks for LOF:
- LOF is local: a point may be normal globally but anomalous locally, or vice versa.
- Choice of k matters: small k detects very local anomalies and is noisy; large k approaches global density comparison.
- Works best with a distance metric that reflects domain meaning (Euclidean for many continuous features). Scale features before using LOF. LOF degrades in high dimensions due to distance concentration; consider dimensionality reduction or isolation-based methods. Complexity: naive computation is O(n^2); with efficient nearest-neighbor search in low dimensions it can be O(n log n) expected.
Diagrams to draw for exam answers:
- For Isolation Forest: draw a binary tree. Label root, first split by feature f1 at value s1, left node containing some points, right node with others; draw path for a typical anomaly needing few splits (short path) and for a normal point needing many splits (longer path). Label heights (path length) as h(x).
- For LOF: draw 2D scatter of points with a small dense cluster and a distant point p. Draw circles to represent k-neighbourhood of p and of a neighbour o; annotate distances, k-distance, reachability distances, show lrd(p) smaller than lrd(o), and compute LOF as ratio average.
Formulas
H(m) = sum_{i=1..m} 1/i — harmonic number; dimensionless; applies when computing c(n).
c(n) = 2·H(n-1) - 2·(n-1)/n — normalization constant for sample size n (n > 1); dimensionless.
s(x) = 2^{ - E(h(x)) / c(n) } — isolation forest anomaly score; 0 < s(x) <= 1; E(h(x)) is average path length for x across trees; dimensionless.
For LOF definitions:
k-distance(p) = distance from p to its k-th nearest neighbour — units are units of the chosen distance (e.g., metres) but treated as unitless in algorithm.
reach-dist_k(p, o) = max{ k-distance(o), dist(p, o) } — units same as distance.
lrd_k(p) = 1 / ( (1/|N_k(p)|) · sum_{o in N_k(p)} reach-dist_k(p, o) ) — inverse distance, dimension 1/distance.
LOF_k(p) = (1/|N_k(p)|) · sum_{o in N_k(p)} ( lrd_k(o) / lrd_k(p) ) — dimensionless; LOF > 1 suggests an outlier.
Python syntax to remember (scikit-learn names):
from sklearn.ensemble import IsolationForest — estimator for isolation forest.
from sklearn.neighbors import LocalOutlierFactor — estimator for LOF (fit_predict returns -1 for outliers, 1 for inliers).
Worked examples
Example 1 — LOF hand calculation (numerical, 1-D) (exam-style): Data (units: arbitrary): A=0, B=1, C=2, D=10. Let k = 2.
- Distances: dist(A,B)=1, dist(A,C)=2, dist(A,D)=10; dist(B,C)=1, dist(B,D)=9; dist(C,D)=8.
- k-distance values (2nd nearest):
- k-distance(A) = 2 (neighbours B and C).
- k-distance(B) = 1 (neighbours A and C, both at distance 1).
- k-distance(C) = 2 (neighbours B and A).
- k-distance(D) = 9 (neighbours C (8) and B (9) → 2nd nearest is B at 9).
- Reachability distances reach-dist_k(p,o) = max{k-distance(o), dist(p,o)}. Compute lrd:
- For A: N_k(A) = {B, C}. reach-dist(A,B) = max(k-distance(B)=1, dist(A,B)=1) = 1. reach-dist(A,C) = max(k-distance(C)=2, dist(A,C)=2) = 2. lrd(A) = 1 / ((1 + 2) / 2) = 1 / 1.5 = 0.6666667.
- For B: N_k(B) = {A, C}. reach-dist(B,A) = max(k-distance(A)=2, dist(B,A)=1) = 2. reach-dist(B,C) = max(k-distance(C)=2, dist(B,C)=1) = 2. lrd(B) = 1 / ((2 + 2) / 2) = 1 / 2 = 0.5.
- For C: symmetric to A: lrd(C) = 0.6666667.
- For D: N_k(D) = {C, B}. reach-dist(D,C) = max(k-distance(C)=2, dist(D,C)=8) = 8. reach-dist(D,B) = max(k-distance(B)=1, dist(D,B)=9) = 9. lrd(D) = 1 / ((8 + 9) / 2) = 1 / 8.5 = 0.11764706.
- LOF_k(p) = average over neighbours of lrd(o) / lrd(p):
- LOF(A) = ( lrd(B) + lrd(C) ) / (2 * lrd(A)) = (0.5 + 0.6666667) / (2 * 0.6666667) = 1.1666667 / 1.3333334 = 0.875.
- LOF(B) = ( lrd(A) + lrd(C) ) / (2 * lrd(B)) = (0.6666667 + 0.6666667) / (2 * 0.5) = 1.3333334 / 1 = 1.3333334.
- LOF(C) = 0.875 (same as A).
- LOF(D) = ( lrd(C) + lrd(B) ) / (2 * lrd(D)) = (0.6666667 + 0.5) / (2 * 0.11764706) = 1.1666667 / 0.23529412 = 4.958333. Final verdict: D is a strong local outlier (LOF ≈ 4.96), B mildly anomalous (LOF ≈ 1.33), A and C normal (LOF < 1).
Example 2 — Simple Python implementation of an Isolation-Forest-like method (small deterministic example). This is a simplified deterministic version for teaching; real IsolationForest uses random splits and many trees.
Python code (runs as-is):
# Simple deterministic "Isolation" by median splits (teaching example)
from math import log2
class Node:
def __init__(self, indices, depth=0):
self.indices = indices
self.left = None
self.right = None
self.split_value = None
self.depth = depth
def build_tree(X, indices, depth=0):
node = Node(indices, depth)
if len(indices) <= 1:
return node
# median split on first feature (1D data here)
vals = [X[i] for i in indices]
vals_sorted = sorted(vals)
mid = len(vals_sorted) // 2
split = (vals_sorted[mid-1] + vals_sorted[mid]) / 2.0
node.split_value = split
left_idx = [i for i in indices if X[i] <= split]
right_idx = [i for i in indices if X[i] > split]
node.left = build_tree(X, left_idx, depth+1)
node.right = build_tree(X, right_idx, depth+1)
return node
def path_length(node, X, idx):
# number of edges from root to leaf for point at index idx
if node.left is None and node.right is None:
return node.depth
if X[idx] <= node.split_value:
return path_length(node.left, X, idx)
else:
return path_length(node.right, X, idx)
# dataset
X = [0.0, 1.0, 2.0, 10.0]
indices = list(range(len(X)))
root = build_tree(X, indices)
# compute path lengths
paths = [path_length(root, X, i) for i in indices]
# normalization c(n) for n=4
H3 = 1.0 + 1.0/2.0 + 1.0/3.0
c4 = 2.0*H3 - 2.0*(3.0)/4.0
scores = [2 ** ( - (h) / c4 ) for h in paths]
print('X =', X)
print('path_lengths =', paths)
print('c(n)=', round(c4, 6))
print('anomaly_scores =', [round(s, 6) for s in scores])
Sample input: (no user input; the program uses the dataset in code)
Exact output when run (each numeric printed as shown):
X = [0.0, 1.0, 2.0, 10.0] path_lengths = [2, 2, 2, 2] c(n)= 2.166667 anomaly_scores = [0.527383, 0.527383, 0.527383, 0.527383]
Interpretation: with this median-split deterministic tree, all points have same path length 2; anomaly scores equal ≈ 0.5263. This illustrates how split strategy affects detection: random small splits that isolate D earlier are needed to get higher anomaly score for D.
Note: the program is a teaching implementation. The real IsolationForest uses random feature and split selection, many trees, and more careful stopping. Use scikit-learn for production.
Common mistakes
- Misinterpreting scores: LOF > 1 suggests anomaly, but threshold choice matters; IsolationForest score near 0 is not always outlier — remember mapping s close to 1 is anomalous.
- Using too small number of trees in IsolationForest or too small k in LOF; both increase variance.
- Not setting random seed during experiments, leading to irreproducible results.
- Treating k as percentage without testing sensitivity: no single correct k for all datasets.
For your exam
Types of questions you will see:
- Definitions: define Isolation Forest, path length, c(n), LOF, local reachability density.
- Short notes: compare isolation-based vs density-based methods and list assumptions and complexity.
- Derivations: show derivation of c(n) from harmonic numbers; show algebra for LOF on a small dataset.
- Numericals: compute LOF step-by-step for small points (as Example 1). Be clear about k-distance, reachability distances, lrd and LOF.
- Programs: write code (or pseudocode) showing how to build isolation trees or compute LOF for small n; mention complexity.
- Diagrams: draw iTree splitting, and LOF neighbourhoods.
What a full-marks answer includes:
- Clear definitions of all terms used (bold if asked), assumptions, and the algorithm steps.
- For derivations: show harmonic number H(m) and algebraic steps for c(n), show how LOF is computed from reachability distances.
- For numericals: show every intermediate value and rounding, label units if relevant, final answer highlighted.
- For comparisons: state time/space complexity and when to prefer one method over the other.
Quick check
- What does a large LOF value mean? 2) In Isolation Forest, are anomalies isolated with short or long path lengths? 3) Why scale features before LOF with Euclidean distance? Answers: 1) point has much lower local density than neighbours (likely an outlier); 2) short path lengths (smaller E(h) → more anomalous); 3) because different feature scales distort Euclidean distances and neighbourhoods, changing LOF results.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?