Reading history

Anomaly Detection in Python: Isolation Forest and the IQR Rule

5 min read 0 views

Learn anomaly detection in Python with scikit-learn's Isolation Forest, the contamination setting, and the IQR and z-score rules for one column.

Anomaly detection finds rows that do not look like the rest: a strange card payment, a faulty sensor reading, a sudden spike in server load. Usually nobody has labelled which rows are odd, so the model has to learn what “normal” looks like on its own. This lesson uses Isolation Forest for many features, and the simple IQR rule for a single column.

In this lesson you will learn

  • How Isolation Forest separates unusual points
  • Flagging anomalies with predict and decision_function
  • What the contamination setting does
  • The IQR and z-score rules for one feature
  • Checking new data against a trained detector

You should know decision trees and basic NumPy.

The Idea: Odd Points Are Easy to Isolate

Isolation Forest builds many random trees. Each split picks a random feature and a random cut between its smallest and largest values. Keep splitting and every point eventually ends up alone in a leaf. A point deep inside a crowd needs many splits to isolate. A point far from the others is often cut off in just a few. So a short average path across all the trees means “probably an anomaly”.

Isolation Forest in scikit-learn

The data holds 297 ordinary card payments, with amounts around 40 made between 8 am and 10 pm, plus three unusual ones.

import numpy as np
from sklearn.ensemble import IsolationForest

rng = np.random.default_rng(5)
# Normal card payments: amount around 40, at hours between 8 and 22
normal = np.column_stack([rng.normal(40, 12, 297), rng.uniform(8, 22, 297)])
odd = np.array([[45, 3.5], [900, 14], [650, 2]])   # 3 unusual payments
X = np.vstack([normal, odd])

iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=0).fit(X)
labels = iso.predict(X)             # 1 = normal, -1 = anomaly
scores = iso.decision_function(X)   # below 0 = anomaly

print("Rows flagged:", (labels == -1).sum(), "of", len(X))
for i in np.where(labels == -1)[0]:
    print(f"  row {i:>3}: amount {X[i, 0]:7.1f}, hour {X[i, 1]:5.1f}, score {scores[i]:.3f}")

new = np.array([[38, 12], [500, 13]])
print("\nNew payments:", iso.predict(new))

Output

Rows flagged: 3 of 300
  row 297: amount    45.0, hour   3.5, score -0.066
  row 298: amount   900.0, hour  14.0, score -0.205
  row 299: amount   650.0, hour   2.0, score -0.223

New payments: [ 1 -1]
  • predict returns 1 for normal rows and −1 for anomalies. All three planted payments are flagged and no ordinary payment is.
  • decision_function gives a score: below 0 means anomaly, and lower means more unusual. The 900 payment at 2 pm (−0.205) and the 650 payment at 2 am (−0.223) are far more unusual than a normal amount at 3:30 am (−0.066).
  • contamination=0.01 tells the model to expect about 1% anomalies, and it sets the cut-off so that 1% of training rows (3 of 300) are flagged.
  • Once trained, the detector checks new rows. A 38 payment at noon is normal (1); a 500 payment is flagged (−1).

Choosing contamination is the hard part. Set it too high and normal rows get flagged; too low and real problems slip through. If you do not know the share, leave the default "auto" and pick your own cut-off on the decision_function scores.

One Column: The IQR Rule

For a single number, such as room temperature, a simple statistical rule is often enough and is easy to explain.

import numpy as np

# Simple statistical rule for one feature: the IQR fence
temps = np.array([21.5, 22.0, 21.8, 22.3, 21.9, 35.2, 22.1, 21.7, 22.4, 8.9, 22.0, 21.6])
q1, q3 = np.percentile(temps, [25, 75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"Q1={q1:.2f}  Q3={q3:.2f}  IQR={iqr:.2f}")
print(f"Normal range: {low:.2f} to {high:.2f}")
print("Outliers:", temps[(temps < low) | (temps > high)])

# z-score rule for comparison
z = (temps - temps.mean()) / temps.std()
print("Values with |z| > 2:", temps[np.abs(z) > 2])

Output

Q1=21.68  Q3=22.15  IQR=0.48
Normal range: 20.96 to 22.86
Outliers: [35.2  8.9]
Values with |z| > 2: [35.2  8.9]
  • Q1 and Q3 are the 25th and 75th percentiles; the IQR is the distance between them.
  • Anything more than 1.5 × IQR below Q1 or above Q3 is called an outlier. This is the same rule a box plot uses for its whiskers.
  • The IQR rule is robust: the outliers themselves barely move the quartiles.
  • The z-score rule measures distance from the mean in standard deviations. It finds the same two values here, but extreme values inflate the mean and standard deviation, so on small samples it can miss outliers.

Choosing a Method

MethodBest forNotes
IQR ruleOne numeric columnSimple, robust, easy to explain
z-scoreOne column, roughly bell-shapedAffected by the outliers themselves
IsolationForestMany features, large dataFast; no scaling needed
LocalOutlierFactorClusters with different densitiesCompares each point with its neighbours
DBSCANFinding clusters and noise togetherPoints in no cluster are labelled −1

Common Mistakes

  1. Treating every flagged row as an error. An anomaly is only unusual; a person should check whether it is a problem.
  2. Setting contamination without thinking. It decides how many rows get flagged, whatever the data looks like.
  3. Training on data full of known problems, so the model learns them as normal.
  4. Using a plain classifier when labels are rare. With only a few labelled anomalies, a detector is often more reliable; with many, see imbalanced classification.

Practice Exercises

Exercise 1. List the five payments with the lowest anomaly scores, from most unusual.

Show answer
order = np.argsort(scores)[:5]
for i in order:
    print(i, X[i].round(1), round(scores[i], 3))

The three planted payments come first, followed by the two most unusual ordinary ones, which still score above 0.

Exercise 2. Write a function iqr_outliers(values, k=1.5) that returns the outliers in a list.

Show answer
def iqr_outliers(values, k=1.5):
    values = np.asarray(values)
    q1, q3 = np.percentile(values, [25, 75])
    iqr = q3 - q1
    return values[(values < q1 - k * iqr) | (values > q3 + k * iqr)]

print(iqr_outliers([10, 12, 11, 13, 12, 50]))   # [50]

Frequently Asked Questions

Is anomaly detection supervised or unsupervised?

Usually unsupervised: the model sees no labels and learns what is normal. If you have many labelled examples of both kinds, an ordinary classifier is often better.

Does Isolation Forest need scaled features?

No. Each split cuts one feature at a random point within that feature’s own range, so units do not matter.

Summary

  • Isolation Forest flags points that random trees cut off in few splits.
  • predict gives 1 or −1; decision_function gives a score where lower is more unusual.
  • contamination sets the expected share of anomalies and so the cut-off.
  • For one column, the IQR rule is a simple, robust choice.

Next: Time Series Forecasting with Machine Learning.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *