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
- Builds on
- 6 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 6 concepts before this one
- What Is AI?
- Probability Basics
- How Machines Learn
- Probability Distributions
- Supervised, Unsupervised and Reinforcement Learning
- Unsupervised Learning
- 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:
where ("mu") is the mean and ("sigma") the standard deviation. If the data is roughly a normal (Gaussian) distribution, about 99.7% of values have , so 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 . The standard deviation is 78.0. So the $250 payment has . 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 .
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: . The constant 0.6745 makes it comparable to an ordinary z-score for normal data.
For $250: . Flagged, loudly.
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 to the data: a multivariate Gaussian, a Gaussian mixture (see k-Means Clustering), or a kernel density estimate. Points where 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 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.
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:
Here is the average path length and is the average path length you would expect for a point in a random tree on 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
contaminationparameter: 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 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
- In the hand example, replace $250 with $40. Compute both the plain and robust z-scores. Is $40 flagged by either?
- 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?
- 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.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
scikit-learn: Novelty and Outlier Detection
Isolation forest, local outlier factor, one-class SVM and elliptic envelope compared on the same data.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
Isolation Forest
Detects anomalies as the points that random splits isolate fastest.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Probabilistic Machine Learning
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