Machine Learning · 16 of 20

Isolation Forest tutorial

Finds anomalies by measuring how quickly random splits isolate each observation. Learn the concept, implement it from scratch, and apply it with scikit-learn.

Category
Unsupervised learning
Core idea
s(x,n) = 2⁻ᴱ⁽ʰ⁽ˣ⁾⁾⁄ᶜ⁽ⁿ⁾
Typical use
Fraud signals, sensor faults, and rare-event screening.
Practical tool
scikit-learn

What is Isolation Forest?

Isolation Forest is a unsupervised learning technique. Finds anomalies by measuring how quickly random splits isolate each observation. Its central idea is summarized by s(x,n) = 2⁻ᴱ⁽ʰ⁽ˣ⁾⁾⁄ᶜ⁽ⁿ⁾.

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with scikit-learn and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when Isolation Forest is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with scikit-learn and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python functions, NumPy arrays, and basic descriptive statistics.
  • A clear distinction between training data, validation data, and untouched test data.
  • Familiarity with features, targets, preprocessing, and task-appropriate evaluation metrics.
LanguagePython 3
Primary libraryscikit-learn
Learning modeFrom scratch + library

How Isolation Forest works

  1. 1

    Input

    Mostly normal observations with a small number of unusual points.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Build random partition trees and average each point’s path length.

  4. 4

    Output

    An anomaly score; shorter paths indicate more unusual observations.

  5. 5

    Validate

    Use labeled anomalies when available to measure precision and recall at the operating threshold.

Formula and intuition

s(x,n) = 2⁻ᴱ⁽ʰ⁽ˣ⁾⁾⁄ᶜ⁽ⁿ⁾

E(h(x)) is the expected isolation path length for x; c(n) normalizes it for a sample of n observations.

The notation captures the main operation or complexity statement behind Isolation Forest. Read it together with the symbol key above and the step-by-step process in this guide.

When to use Isolation Forest

Fraud signals, sensor faults, and rare-event screening.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

Isolation Forest from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
import numpy as np

rng = np.random.default_rng(0)
X = np.r_[rng.normal(0, 1, (96, 2)), [[4.5, 4.2], [-4.2, 3.8]]]

def path_length(points, query, depth=0):
    if len(points) <= 1:
        return depth
    feature = rng.integers(points.shape[1])
    low, high = points[:, feature].min(), points[:, feature].max()
    if low == high:
        return depth
    split = rng.uniform(low, high)
    side = points[:, feature] < split
    return path_length(points[side == (query[feature] < split)], query, depth + 1)

# Anomalies tend to need fewer random splits to stand alone.
scores = np.array([np.mean([path_length(X, x) for _ in range(50)]) for x in X])
anomalies = np.argsort(scores)[:2]
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build Isolation Forest with scikit-learn

IsolationForest scales random isolation trees to multivariate anomaly screening and provides continuous decision scores.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Install the required package python -m pip install scikit-learn
  1. Prepare the data.Mostly normal observations with a small number of unusual points. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Build random partition trees and average each point’s path length.
  4. Inspect the result.An anomaly score; shorter paths indicate more unusual observations. Then apply the evaluation checks in the next section.
Pythonscikit-learn workflow
import numpy as np
from sklearn.ensemble import IsolationForest

rng = np.random.default_rng(7)
normal = rng.normal(0, 1, (500, 3))
unusual = rng.normal(6, 0.4, (12, 3))
X = np.vstack([normal, unusual])

model = IsolationForest(
    n_estimators=300, contamination=0.025, random_state=42
)
label = model.fit_predict(X)  # -1 means anomaly
score = model.decision_function(X)  # lower is more anomalous
print("detected anomalies:", np.sum(label == -1))
print("lowest scores:", np.sort(score)[:5])

API details and version-specific options: official scikit-learn reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Use labeled anomalies when available to measure precision and recall at the operating threshold.
  • Without labels, inspect the lowest-scoring cases and monitor score drift over time.
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • The contamination setting directly influences the decision threshold.
  • Train primarily on representative normal behavior.
  • Anomaly scores can shift when the data distribution changes.

Before using Isolation Forest in a project

  • Define the prediction or discovery objective before selecting the algorithm.
  • Split data before fitting preprocessing and tune only inside cross-validation.
  • Record data versions, random seeds, features, hyperparameters, and evaluation metrics.
  • Compare against a simple baseline and inspect errors by meaningful subgroups.
  • Monitor input drift and real-world performance after deployment.

Official documentation and next steps

Primary software reference scikit-learn

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See Isolation Forest in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →