Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 2

Worked Example: Catching Anomalies with an Isolation Forest

Score 4,000 synthetic card transactions with an isolation forest and a k-nearest-neighbour distance detector, recover path lengths from the scores, see what contamination really changes, and evaluate both detectors at a daily review budget on a small hand-labelled sample.

Contentsand lesson path

What you will learn

  • Detect anomalies with an isolation forest or a distance-based method and evaluate the detector against a small labeled sample.

01. The problem

A card issuer processes about 4,000 transactions a day and has two analysts who can review 120 alerts a day between them, 3% of the traffic. There is no history of confirmed fraud to train a classifier on. What there is: last week the analysts carefully labelled a random sample of 400 transactions, and noted the kind of problem for each anomaly they found. Your job is to build an anomaly detector, a model that gives each row a score for how unusual it is, decide which detector to use, and report how well it would work at the review budget.

An anomaly detector learns what is normal from unlabelled data and scores departures from it. That makes the labelled sample precious: it is not for training, it is the only honest way to measure the detector. You will compare an isolation forest with a distance-based detector that scores each row by how far it lies from its nearest neighbours.

The data is synthetic, generated with a fixed seed, so you can rerun everything: Python 3.12, scikit-learn 1.9, pandas 3.1 and SciPy 1.18. Create a folder, install with the command below (pinned to the versions that produced the outputs), and save each script into it.

Terminal
mkdir anomaly-example && cd anomaly-example
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*" "scipy==1.18.*"

02. Step 1: Generate the transactions and the labelled sample

Most transactions are ordinary: amounts around £33 with a long tail, daytime hours, a few kilometres from home, one or two transactions in the previous day. Three kinds of anomaly are mixed in, 40 of each: large purchases far from home (big_far), bursts of many transactions in a day (burst), and night-time purchases 40 to 150 km from home (night_far). The detectors see only the four feature columns. The labelled sample keeps the analysts' verdict and their note on the kind.

Python · make_transactions.py
"""Write data/transactions.csv (4,000 rows) and data/labelled_sample.csv (400 rows)."""
from pathlib import Path

import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n_normal, n_each = 3880, 40          # 40 anomalies of each of three kinds


def normal(n):
    return pd.DataFrame({
        "amount": rng.lognormal(3.5, 0.8, n).round(2),
        "hour": np.clip(rng.normal(14, 3.5, n), 0, 23.99).round(2),
        "km_from_home": rng.exponential(5, n).round(1),
        "tx_last_24h": rng.poisson(1.5, n),
    })


big_far = normal(n_each)
big_far["amount"] = (big_far["amount"] * rng.uniform(15, 40, n_each)).round(2)
big_far["km_from_home"] = rng.uniform(200, 2000, n_each).round(1)
burst = normal(n_each)
burst["tx_last_24h"] = rng.integers(9, 16, n_each)
night_far = normal(n_each)
night_far["hour"] = rng.uniform(1, 5, n_each).round(2)
night_far["km_from_home"] = rng.uniform(40, 150, n_each).round(1)

df = pd.concat([normal(n_normal), big_far, burst, night_far], ignore_index=True)
df["is_anomaly"] = np.r_[np.zeros(n_normal), np.ones(3 * n_each)].astype(int)
kinds = ["normal", "big_far", "burst", "night_far"]
df["kind"] = np.repeat(kinds, [n_normal] + [n_each] * 3)
df = df.sample(frac=1, random_state=0).reset_index(drop=True)
df.insert(0, "tx_id", np.arange(len(df)))

Path("data").mkdir(exist_ok=True)
df.drop(columns=["is_anomaly", "kind"]).to_csv("data/transactions.csv", index=False)
sample = df.sample(400, random_state=3)[["tx_id", "is_anomaly", "kind"]]
sample.to_csv("data/labelled_sample.csv", index=False)
print("transactions:", len(df), "| true anomaly rate:", df["is_anomaly"].mean())
found = sample.loc[sample["is_anomaly"] == 1, "kind"].value_counts().to_dict()
print("labelled sample:", len(sample), "rows,", sample["is_anomaly"].sum(), "anomalies",
      found)
Terminal
python make_transactions.py
Expected output
transactions: 4000 | true anomaly rate: 0.03
labelled sample: 400 rows, 13 anomalies {'night_far': 5, 'big_far': 4, 'burst': 4}

The sample holds 13 anomalies among 400 rows. Keep that number in mind: every metric computed from it rests on 13 positive cases.

03. Step 2: Fit an isolation forest and read its path lengths

An isolation forest builds many random trees. Each tree takes a small random subsample of rows (256 by default), picks a random feature, picks a random split value between that feature's minimum and maximum, and repeats on each side until every row is alone or a depth limit is reached. A row that is unlike the rest gets separated after a few cuts; a row inside a dense crowd needs many. The path length of a row, the number of cuts needed to isolate it, averaged over all trees, is the signal. scikit-learn turns it into a score with s = 2^(−mean path / c), where c is the average path length expected in a random tree of 256 rows, so the script can recover the path length from the score. score_samples returns the negative of s, so the script flips the sign to make higher mean more anomalous.

Python · iforest.py
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest

FEATURES = ["amount", "hour", "km_from_home", "tx_last_24h"]
df = pd.read_csv("data/transactions.csv")
X = df[FEATURES].to_numpy()

forest = IsolationForest(n_estimators=200, random_state=0).fit(X)
df["iforest"] = -forest.score_samples(X)          # higher = more anomalous
df[["tx_id", "iforest"]].to_csv("data/scores.csv", index=False)

# score = 2 ** (-mean path length / c), so the mean path length can be recovered
psi = forest.max_samples_                            # rows per tree: 256
c = 2 * (np.log(psi - 1) + np.euler_gamma) - 2 * (psi - 1) / psi
path = -c * np.log2(df["iforest"])
print(f"rows per tree {psi} | mean path: most anomalous {path.min():.1f}, "
      f"median row {path.median():.1f}, most normal {path.max():.1f}")
top5 = df.sort_values("iforest", ascending=False).head(5)
print(top5.round(3).to_string(index=False))
Terminal
python iforest.py
Expected output
rows per tree 256 | mean path: most anomalous 3.0, median row 13.8, most normal 15.5
 tx_id  amount  hour  km_from_home  tx_last_24h  iforest
   301 2152.85 16.42        1864.7            1    0.818
  2469 1973.63 12.92        1963.2            3    0.811
  1998 1561.18 14.57        1732.0            2    0.808
  2746 1505.35 11.67        1270.0            1    0.802
  2264 4650.23  9.54         872.5            0    0.800

The most anomalous row is isolated after about 3 cuts on average; the median row needs 13.8. These numbers include scikit-learn's correction for leaves that still hold several rows when the depth limit is reached, so they can exceed the depth limit of 8. The top five are all large purchases more than 800 km from home. Two practical points follow from the mechanism. The forest uses no distances, so it needs no feature scaling. And because each tree sees only 256 rows, a group of similar anomalies is less likely to shelter its members in any one tree, which helps against masking, the effect of anomalies hiding behind each other.

04. Step 3: What contamination changes

IsolationForest has a contamination parameter, and it is easy to misread. Fit the forest three times with different values and compare the scores and the labels from predict, which returns -1 for an anomaly and 1 for a normal row.

Python · contamination.py
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest

FEATURES = ["amount", "hour", "km_from_home", "tx_last_24h"]

X = pd.read_csv("data/transactions.csv")[FEATURES].to_numpy()
reference = None
for contamination in ["auto", 0.01, 0.03]:
    forest = IsolationForest(n_estimators=200, contamination=contamination,
                             random_state=0).fit(X)
    scores = forest.score_samples(X)
    if reference is None:
        reference = scores
    flagged = np.mean(forest.predict(X) == -1)        # predict: -1 anomaly, 1 normal
    print(f"contamination {contamination!s:>4}: offset_ {forest.offset_:.3f}, "
          f"flagged {flagged:.1%}, scores unchanged: {np.allclose(scores, reference)}")
Terminal
python contamination.py
Expected output
contamination auto: offset_ -0.500, flagged 7.4%, scores unchanged: True
contamination 0.01: offset_ -0.706, flagged 1.0%, scores unchanged: True
contamination 0.03: offset_ -0.596, flagged 3.0%, scores unchanged: True

The scores are identical in all three fits. contamination changes only offset_, the threshold that predict and decision_function apply to the scores: with 0.01 it is placed so that 1.0% of the training rows fall below it, with 0.03 so that 3.0% do. The default "auto" uses the threshold from the original paper and here flags 7.4%, far more than the analysts can review. So contamination does not make the model look for a particular share of anomalies, and it does not promise that share on future data. Set it from your review budget if you use predict, or ignore predict and rank by score.

05. Step 4: A distance-based detector

The alternative scores each row by its mean distance to its k nearest neighbours: a row far from all others is unusual. Distances need comparable scales, so the two skewed columns are logged and every column is standardised first. The script computes the score for k = 10 and k = 100 and adds both to data/scores.csv. LocalOutlierFactor in scikit-learn is a refinement of the same idea that compares each row's neighbour distances with those of its neighbours, which helps when normal data has regions of different density.

Python · knn_scores.py
import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("data/transactions.csv")
Z = df[["amount", "hour", "km_from_home", "tx_last_24h"]].copy()
Z[["amount", "km_from_home"]] = np.log1p(Z[["amount", "km_from_home"]])
Z = StandardScaler().fit_transform(Z)       # distances need comparable scales

scores = pd.read_csv("data/scores.csv")
for k in [10, 100]:
    # ask for k + 1 neighbours: the nearest one is the row itself
    dist, _ = NearestNeighbors(n_neighbors=k + 1).fit(Z).kneighbors(Z)
    scores[f"knn{k}"] = dist[:, 1:].mean(axis=1)   # mean distance to k neighbours
scores.to_csv("data/scores.csv", index=False)
print(scores.drop(columns="tx_id").describe().loc[["50%", "max"]].round(3).to_string())
Terminal
python knn_scores.py
Expected output
     iforest  knn10  knn100
50%    0.393  0.364   0.710
max    0.818  2.525   4.934

The scales differ between detectors, so compare their rankings, not their raw values.

06. Step 5: Evaluate at the review budget

Now evaluate the detectors the way they will be used. Each day, the 120 highest-scoring transactions go to the analysts. So the script finds, for each detector, the score of the 120th highest row among all 4,000, flags the labelled rows above it, and measures precision (the share of flagged rows that are real anomalies, which is what the analysts experience) and recall (the share of real anomalies that get flagged). It adds accuracy, for comparison, and average precision, a threshold-free summary of how well the scores rank anomalies above normal rows. binomtest(...).proportion_ci() gives an exact 95% interval for recall.

Python · evaluate.py
import numpy as np
import pandas as pd
from scipy.stats import binomtest
from sklearn.metrics import accuracy_score, average_precision_score

BUDGET = 120                                   # alerts the analysts can review a day
scores = pd.read_csv("data/scores.csv")
sample = pd.read_csv("data/labelled_sample.csv").merge(scores, on="tx_id")
y = sample["is_anomaly"].to_numpy()
print(f"labelled rows {len(y)}, anomalies {y.sum()}; "
      f"accuracy of flagging nothing: {accuracy_score(y, np.zeros_like(y)):.3f}")

print("detector  flagged  hits  precision  recall  accuracy  avg precision")
for name in ["iforest", "knn10", "knn100"]:
    threshold = np.sort(scores[name])[-BUDGET]        # top 120 of all 4,000 rows
    flag = (sample[name] >= threshold).to_numpy()
    hits = int(np.sum(flag & (y == 1)))
    print(f"{name:9} {flag.sum():7d} {hits:5d} {hits / flag.sum():10.2f} "
          f"{hits / y.sum():7.2f} {accuracy_score(y, flag):9.3f} "
          f"{average_precision_score(y, sample[name]):14.3f}")
    low, high = binomtest(hits, int(y.sum())).proportion_ci()   # exact 95% interval
    missed = sample.loc[~flag & (y == 1), "kind"].value_counts().to_dict()
    print(f"          recall 95% interval {low:.2f}-{high:.2f}, missed: {missed}")
Terminal
python evaluate.py
Expected output
labelled rows 400, anomalies 13; accuracy of flagging nothing: 0.968
detector  flagged  hits  precision  recall  accuracy  avg precision
iforest        16    13       0.81    1.00     0.993          1.000
          recall 95% interval 0.75-1.00, missed: {}
knn10          12     7       0.58    0.54     0.973          0.592
          recall 95% interval 0.25-0.81, missed: {'night_far': 5, 'big_far': 1}
knn100         14    13       0.93    1.00     0.998          1.000
          recall 95% interval 0.75-1.00, missed: {}

First, accuracy is useless here. Flagging nothing scores 0.968, because 96.8% of rows are normal, and the worst detector still reaches 0.973. The metrics that matter are precision and recall at the budget.

The isolation forest flags 16 labelled rows and 13 are real: precision 0.81, recall 1.00. k-NN with k = 10 does much worse, precision 0.58 and recall 0.54, and it misses all five night_far anomalies. Those 40 transactions resemble each other, so each one's ten nearest neighbours are other night-time anomalies, and its distance looks ordinary. Raising k to 100, more than the size of the group, fixes it. Both the forest and k = 100 catch all 13. k = 100 has the higher precision (0.93 against 0.81), but that gap is two rows of the sample. The forest needed no scaling and no choice of k and handles large data cheaply, while the k-NN score is easier to explain ("nothing similar has happened before") but only worked once k was right.

Finally, read the interval. 13 of 13 is not proof that the detector catches everything: the exact 95% interval for recall runs from 0.75 to 1.00, and it covers only the three kinds of anomaly that happen to be in the sample. Report it that way, and grow the labelled sample over time by labelling a random slice of each day's traffic as well as the alerts.

07. Check your understanding

Practice check · 3 questions

Reading the detectors

Answer from the code and the numbers in this worked example.

Q1. In step 5 the k-NN detector with k = 10 misses all five `night_far` anomalies in the sample, while k = 100 catches them. What explains the difference?
Q2. The isolation forest scores an average precision of 1.000 on the labelled sample, yet its precision at the budget is only 0.81. How can both be true?
Q3. You delete the `StandardScaler` line from `knn_scores.py`, and you also try putting a `StandardScaler` in front of the isolation forest. Which scores change?
Practice only: not graded, not saved, not evidence.

08. Apply it

Continue the practice project on the customer table from the segmentation lab, or on a transaction table of your own.

  1. Fit an IsolationForest with random_state=0, rank the rows by score and flag the top 1%; set contamination=0.01 only if you want predict to return the same flags.
  2. Hand-label a random sample of at least 300 rows, then measure precision and recall of the 1% flags on it, with an exact interval for each.
  3. Repeat with a k-NN distance score for two values of k, and write three sentences on which detector you would deploy and why, including what kinds of anomaly each one missed.

09. Review prompt

Without looking back, explain how an isolation forest turns random splits into an anomaly score; what contamination changes and what it leaves alone; why a k-NN distance detector needs scaled features and can miss a group of similar anomalies; why accuracy misleads on rare anomalies; and how to measure a detector at a review budget with a small labelled sample.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check