Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 52

Isolation Forest

Spot anomalies by how quickly random splits separate a point, because odd points are isolated in few cuts. One example is on this page.

Intermediate12 min
Isolation Forest MahiDev

What You Will Learn

  • Idea
  • Example
  • When to use it

Idea

An isolation forest builds random trees. At each node it picks a feature and a random cut. A point that sits alone is separated near the root. A point inside a crowd needs many cuts. Short paths are the anomaly score. A prediction of -1 marks the odd row.

Example

python
import numpy as np
from sklearn.ensemble import IsolationForest

X = np.array([[1, 1], [1.1, 0.9], [0.9, 1.2], [1.2, 1.0], [8, 8]], dtype=float)
pred = IsolationForest(random_state=0, contamination=0.2).fit_predict(X)
print(pred.tolist())

Output:

text
[1, 1, 1, 1, -1]

When to use it

  • Use it on tables where anomalies are few and different from the crowd.
  • contamination is your guess of the anomaly fraction. It sets the cutoff.
  • A label of -1 is the anomaly. 1 is a normal row.

Loading playground…