◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Anomaly Detection

Finding the rare, unusual data points (fraud, faults, intrusions, errors) usually without labelled examples of what "bad" looks like. Learn what normal looks like, then flag what doesn't fit.

Level
●●●●● Easy
Reading
13 min
To learn it well
45 minutes to read, an hour to practise
↗ Plan a path here

Read first

Unsupervised LearningProbability Distributions

This leads to

—
The full path from zero — 6 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. How Machines Learn
  4. Probability Distributions
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Unsupervised Learning
  7. Anomaly Detection

Read them roughly in this order. See it on the concept map →

Why it matters

A bank processes millions of card payments a day. A tiny fraction are fraudulent, and nobody can label them in advance because fraudsters keep changing tactics. A jet engine streams thousands of sensor readings per flight; a developing fault shows up as a pattern never seen before. A website's traffic suddenly triples at 3 a.m. A data pipeline starts writing ages of 999.

All of these are anomaly detection problems: find the data points that are unusual compared with the rest. An unusual point is called an anomaly or outlier. Anomaly detection runs fraud screening, network intrusion detection, predictive maintenance, medical monitoring, and data-quality checks in every serious data pipeline.

It is hard for three reasons:

  • Anomalies are rare. Often well under 1% of the data. A model that says "everything is normal" is 99.9% accurate and useless.
  • Labels are scarce. You may have no confirmed examples of fraud at all, or only a few old ones.
  • Anomalies are diverse. There is one way to be normal and endless ways to be strange. Tomorrow's fault won't look like yesterday's.

So instead of learning "what fraud looks like" with Supervised Learning, most anomaly detection is unsupervised: learn what normal looks like, and flag what doesn't fit.

The intuition

A doorman at a club sees thousands of guests. He has never been given a list of troublemakers, but he knows what ordinary guests look like and behave like. Someone who arrives at the wrong time, dressed wrongly, acting oddly, stands out. He doesn't need to have seen that exact kind of trouble before.

Every method in this chapter is a different way of measuring "stands out":

  • Far from the centre: more than a few standard deviations from the average (z-scores).
  • In an empty region: where the estimated probability density is low.
  • Far from its neighbours: much further from its nearest neighbours than they are from theirs (local outlier factor).
  • Easy to separate: random cuts isolate it quickly (isolation forest).
  • Hard to reproduce: a model trained to compress and rebuild normal data rebuilds it badly (reconstruction error).

Each method gives every point an anomaly score. You then rank points by score and set a threshold, or hand the top few to a human to investigate.

Key idea Anomaly detection models normal behaviour and scores each new point by how badly it fits. Rare and varied anomalies make labels scarce, so the main methods are unsupervised: distance from the centre, low density, isolation by random splits, and reconstruction error.

How it works

Z-scores: the simplest test

For a single numeric feature, measure how many standard deviations each value is from the mean. This is the z-score:

z=x−μσz = \frac{x - \mu}{\sigma}

where μ\mu ("mu") is the mean and σ\sigma ("sigma") the standard deviation. If the data is roughly a normal (Gaussian) distribution, about 99.7% of values have ∣z∣<3|z| < 3, so ∣z∣>3|z| > 3 is a common rule for "suspicious".

A worked example by hand

A customer's last eight card payments, in dollars: 12, 15, 9, 22, 18, 14, 11, 250.

Plain z-score. The mean is 351/8=43.9351/8 = 43.9. The standard deviation is 78.0. So the $250 payment has z=(250−43.9)/78.0=2.64z = (250 - 43.9)/78.0 = 2.64. Below 3: not flagged.

What went wrong? The outlier dragged the mean up and inflated the standard deviation, which made itself look less extreme. This is called masking. Without the $250 payment, the other seven have mean 14.4 and standard deviation 4.1, and $250 would have z=57z = 57.

Robust z-score. Replace the mean with the median and the standard deviation with the median absolute deviation (MAD), both of which barely move when a few points are extreme:

  • Median of the eight payments: 14.5.
  • Absolute deviations from 14.5: 2.5, 0.5, 5.5, 7.5, 3.5, 0.5, 3.5, 235.5. Their median, the MAD, is 3.5.
  • Robust z-score: 0.6745×(x−median)/MAD0.6745 \times (x - \text{median}) / \text{MAD}. The constant 0.6745 makes it comparable to an ordinary z-score for normal data.

For $250: 0.6745×(250−14.5)/3.5=45.40.6745 \times (250 - 14.5)/3.5 = 45.4. Flagged, loudly.

Plain z-score ±3 sd band mean 43.9, sd 78.0: the outlier inflates the spread 250 is only 2.6 sd above the mean → not flagged Robust z-score ±3 robust sd median 14.5, MAD 3.5: the outlier barely moves them 250 is 45 robust units away → flagged $0 $50 $100 $150 $200 $250
Fig. 1 Eight card payments. With a plain z-score, the $250 outlier stretches the mean and standard deviation so much that it sits inside the ±3 standard-deviation band and escapes detection. With the robust version, based on the median and median absolute deviation, the band hugs the normal payments and $250 lies far outside it.

Z-scores work one feature at a time. That misses points that are ordinary on every feature separately but unusual in combination, such as a 1.9 m tall person weighing 45 kg. For that you need methods that look at all features together.

Density-based scores

Fit a probability model p(x)p(\mathbf{x}) to the data: a multivariate Gaussian, a Gaussian mixture (see k-Means Clustering), or a kernel density estimate. Points where p(x)p(\mathbf{x}) is very low are anomalies. With a single multivariate Gaussian, this is the Mahalanobis distance: a z-score that accounts for correlations between features, so the tall, very light person stands out. These methods work well in low dimensions and struggle when there are many features, because density is hard to estimate there.

Local outlier factor

Some regions of normal data are naturally dense and others sparse. A point that would be ordinary in a sparse region can be an anomaly next to a dense cluster. Local outlier factor (LOF) compares each point's local density (based on distances to its kk nearest neighbours, as in k-Nearest Neighbours) with the local densities of those neighbours. A score near 1 means "as dense as my neighbourhood"; well above 1 means "much sparser than my neighbours": an outlier.

Isolation forest

Isolation forest turns the question around. Instead of modelling normal points, it asks how easy each point is to isolate. Build a random tree: pick a random feature and a random threshold between its minimum and maximum, split the data, and keep splitting each side the same way until every point sits alone.

A normal point needs 12 random cuts to isolate An anomaly isolated after 2 random cuts purple lines: random splits on a random feature; anomalies sit alone, so few splits separate them
Fig. 2 Isolating points with random cuts. A point in the dense middle of the data (left) needs many random splits before it is alone. An anomaly far from the rest (right) is cut off after just two. Averaged over many random trees, a short path means an anomaly.

Anomalies are few and far from the rest, so a random cut is likely to separate them early. Normal points sit among many others and need many cuts. Average the path length (number of cuts to isolate a point) over 100 or so random trees, each built on a random subsample of, say, 256 points. Convert it to a score between 0 and 1:

s(x)=2−hˉ(x)/c(n)s(\mathbf{x}) = 2^{-\bar{h}(\mathbf{x}) / c(n)}

Here hˉ(x)\bar{h}(\mathbf{x}) is the average path length and c(n)c(n) is the average path length you would expect for a point in a random tree on nn points, which normalises the score. Scores near 1 mean anomaly; scores around 0.5 or below mean normal. Isolation forest is fast, needs no distance calculations, copes with many features, and is often the first method to try. It borrows the random-tree machinery of Random Forests and Bagging and Decision Trees.

One-class SVM

A one-class SVM learns a boundary that encloses most of the normal training data, using the kernel trick from Support Vector Machines so the boundary can be curved. Points outside are anomalies. The parameter nu sets roughly what fraction of training points may fall outside. It works well on small and medium datasets, but is sensitive to scaling and to gamma, and slow on large data.

Reconstruction error and autoencoders

Train a model to compress data into a few numbers and rebuild it, using only normal data. The model learns the patterns of normal data and nothing else. Give it an anomaly and it rebuilds it badly. The reconstruction error, the difference between input and rebuilt output, is the anomaly score.

  • With PCA and Dimensionality Reduction, keep the top components and measure how much of each point lies outside them.
  • With an autoencoder, a neural network does the compressing and rebuilding. This handles images, audio and complex sensor signals. For example, an autoencoder trained on images of good products on a factory line rebuilds scratched or misshapen products poorly, and the error map even shows where the defect is.

Choosing a threshold

Every method outputs a score; turning scores into alarms needs a threshold. Options:

  • A fixed share. Flag the top 0.1% each day, matching your team's capacity to investigate. In scikit-learn this is the contamination parameter: the expected fraction of anomalies.
  • A statistical rule, such as robust z above 3.5.
  • Tuned on labelled examples, if you have a few confirmed anomalies: choose the threshold that gives acceptable precision and recall (see Evaluation Metrics).

Outliers versus novelties

Two settings are worth distinguishing. Outlier detection: the training data itself contains some anomalies, and you want to find them. Novelty detection: the training data is clean (all normal), and you want to flag new points that differ. scikit-learn's LocalOutlierFactor needs novelty=True for the second case.

In code

Isolation forest from scratch in NumPy, on 500 normal points and a scatter of anomalies around them. Each "tree" is a single random path: we only need to know how many random splits it takes to isolate each point.

import numpy as np

rng = np.random.default_rng(0)
normal = rng.normal(0, 1, size=(500, 2))                  # ordinary behaviour
odd = rng.uniform(-6, 6, size=(40, 2))                    # scattered anomalies
odd = odd[np.linalg.norm(odd, axis=1) > 4]                # keep only ones clearly outside
X = np.vstack([normal, odd])
is_anomaly = np.r_[np.zeros(len(normal)), np.ones(len(odd))]

def path_length(x, X, depth=0, max_depth=10):
    """How many random splits does it take to isolate x within the sample X?"""
    if len(X) <= 1 or depth >= max_depth:
        return depth + (c(len(X)) if len(X) > 1 else 0)
    j = rng.integers(X.shape[1])                          # random feature
    lo, hi = X[:, j].min(), X[:, j].max()
    if lo == hi:
        return depth
    t = rng.uniform(lo, hi)                               # random threshold
    side = X[:, j] < t
    return path_length(x, X[side] if x[j] < t else X[~side], depth + 1, max_depth)

def c(n):                                                 # average path length of an unsuccessful search
    return 2 * (np.log(n - 1) + 0.5772) - 2 * (n - 1) / n if n > 2 else 1.0

n_trees, sample = 100, 256
samples = [X[rng.choice(len(X), sample, replace=False)] for _ in range(n_trees)]
avg_depth = np.array([np.mean([path_length(x, S) for S in samples]) for x in X])
score = 2 ** (-avg_depth / c(sample))                     # near 1 = anomaly, about 0.5 or less = normal

top = np.argsort(score)[::-1][:len(odd)]
print(f"{len(odd)} true anomalies; {int(is_anomaly[top].sum())} of them are in the top {len(odd)} scores")
print("mean score, normal points :", score[is_anomaly == 0].mean().round(3))
print("mean score, anomalies     :", score[is_anomaly == 1].mean().round(3))

# 28 true anomalies; 27 of them are in the top 28 scores
# mean score, normal points : 0.414
# mean score, anomalies     : 0.69

(A real isolation tree is built once and reused for all points; recomputing a fresh random path per point, as here, gives the same expected score with simpler code.)

Now four methods from scikit-learn on a harder, higher-dimensional task. "Normal" is images of the handwritten digit 1, and the anomalies are 20 images of other digits. Each model trains on 100 normal images only (novelty detection). ROC AUC measures how well the scores rank anomalies above normal points: 1.0 is perfect, 0.5 is random guessing.

import numpy as np
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score
from sklearn.neighbors import LocalOutlierFactor
from sklearn.svm import OneClassSVM
from sklearn.datasets import load_digits

# Normal data: images of the digit 1. Anomalies: a few images of other digits.
X, y = load_digits(return_X_y=True)
normal, other = X[y == 1], X[y != 1]
rng = np.random.default_rng(0)
X_test = np.vstack([normal[100:], other[rng.choice(len(other), 20, replace=False)]])
truth = np.r_[np.zeros(len(normal) - 100), np.ones(20)]          # 1 = anomaly
X_train = normal[:100]                                           # train on normal examples only

scores = {
    "isolation forest": -IsolationForest(random_state=0).fit(X_train).score_samples(X_test),
    "local outlier factor": -LocalOutlierFactor(novelty=True).fit(X_train).score_samples(X_test),
    "one-class SVM": -OneClassSVM(gamma="scale", nu=0.05).fit(X_train).score_samples(X_test),
}
pca = PCA(n_components=10).fit(X_train)                          # linear "autoencoder"
recon = pca.inverse_transform(pca.transform(X_test))
scores["PCA reconstruction error"] = ((X_test - recon) ** 2).sum(axis=1)

for name, s in scores.items():
    print(f"{name:25} ROC AUC {roc_auc_score(truth, s):.3f}")

# isolation forest          ROC AUC 0.951
# local outlier factor      ROC AUC 0.988
# one-class SVM             ROC AUC 0.955
# PCA reconstruction error  ROC AUC 0.990

scikit-learn's score_samples returns higher for more normal, so we negate it to get an anomaly score. On this image data, the methods that model the shape of normal data (reconstruction error, LOF) beat the generic isolation forest. On other data the ranking can reverse, so try several.

Common pitfalls

  • Judging by accuracy. With 0.1% anomalies, "never flag anything" scores 99.9%. Use precision and recall on the anomaly class, precision among the top kk alerts, or ROC and PR curves. See Evaluation Metrics.
  • Masking by the anomalies themselves. Means and standard deviations computed on data that contains outliers hide those outliers. Use robust statistics, or fit on data you trust to be clean.
  • Unscaled features. Distance-based methods (LOF, one-class SVM, k-NN) are dominated by large-unit features. Standardise.
  • "Unusual" isn't "bad". Black Friday sales and a new product launch are anomalous and perfectly fine. Expect a human review loop, and feed confirmed results back.
  • Drift. Normal behaviour changes: seasons, new customers, new software versions. A detector trained last year flags this year's normal. Retrain regularly and monitor alert rates (see Monitoring and Data Drift).
  • Thresholds nobody can act on. An alert rate higher than the team can investigate gets ignored. Set the threshold by capacity and cost, not just by statistics.
  • Ignoring time. In Time Series Forecasting data, a value can be normal at noon and anomalous at midnight. Compare against seasonal expectations, not the global average.

Watch out An anomaly detector with no labels can't tell you its own error rate. Before trusting it, gather even a few dozen confirmed anomalies, or inject realistic synthetic ones, and measure precision and recall on them. Otherwise you don't know whether it works.

Where it leads

  • Supervised fraud models. Once you have enough confirmed cases, a supervised classifier such as Gradient Boosting: XGBoost and LightGBM usually beats unsupervised scores, and the anomaly score itself becomes a useful feature for it.
  • Time-series anomalies. Forecast the next value and flag large forecast errors. See Time Series Forecasting.
  • Autoencoders for images, audio and complex signals. See Autoencoders.
  • Monitoring ML systems: detecting when incoming data no longer looks like the training data. See Monitoring and Data Drift.
  • Out-of-distribution detection for neural networks asks whether an input is unlike anything the model was trained on, an important safety question.

A bit of history

Statisticians have argued about outliers since at least the 19th century; Peirce's criterion (1852) and Chauvenet's criterion (1863) were early rules for rejecting suspicious astronomical observations. Grubbs' test (1950) formalised testing for a single outlier in normal data. Local outlier factor was introduced by Breunig, Kriegel, Ng and Sander in 2000. Schölkopf and colleagues published the one-class SVM in 2001. Fei Tony Liu, Kai Ming Ting and Zhi-Hua Zhou introduced the isolation forest in 2008; its insight, isolating anomalies directly instead of profiling normal points, made it one of the most widely used methods. Autoencoder-based detection became standard with the growth of deep learning in the 2010s, especially for images and industrial inspection.

Try it

  1. In the hand example, replace $250 with $40. Compute both the plain and robust z-scores. Is $40 flagged by either?
  2. In the scikit-learn code, change the number of PCA components from 10 to 2 and to 40. How does the reconstruction-error AUC change, and why?
  3. Harder: use the digit 8 as "normal" instead of 1. Which method wins now? Why might some digits be harder than others?

Hint for 1: the median of the new eight values is 14.5 again; find the new MAD from the absolute deviations.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A customer's payments are 12, 15, 9, 22, 18, 14, 11 and 250 dollars. The $250 gets a plain z-score of only 2.64 and isn't flagged. Why?

  2. Why does an isolation forest give anomalies high scores?

  3. Your fraud detector says "normal" for everything and scores 99.9% accuracy. What should you measure instead?

  4. You set contamination=0.001 in scikit-learn's anomaly detectors. What does this control?

  5. A person is 1.9 m tall and weighs 45 kg. Each value alone is within normal range. Which approach is most likely to flag them?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Paper

Isolation Forest

Liu, Ting & Zhou · 2008 · Advanced · Paid

Detects anomalies as the points that random splits isolate fastest.

Book

Probabilistic Machine Learning

Kevin P. Murphy · Advanced · Free

A comprehensive two-volume reference viewing ML through probability. Free drafts online.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/anomaly-detection.md