Anomaly Detection
Finding fraud, faults and intrusions nobody labelled: robust z-scores, k-NN and LOF, isolation forests, reconstruction error, thresholds and drift.
Intermediate lesson, about 30 minutes, with interactive demos and a quiz.
What you will learn
- Point, contextual and collective anomalies
- Z-scores and median/MAD
- k-NN distance and LOF
- Isolation forests
- Reconstruction error
- Precision-recall under imbalance
- Drift
Finding the odd one out
A stolen card is used for the first time in another country. A bearing in a wind turbine starts to vibrate at a new frequency. A laptop on a company network begins talking to a server nobody has heard of. None of these comes with a label saying “problem”. They are found because they do not look like everything else.
What is it?
Anomaly detection is finding the data points that do not fit the pattern of the rest. Chandola, Banerjee and Kumar’s survey sorts anomalies into three kinds:
- Point anomalies: one value is unusual on its own, such as a £9,000 purchase on a card that never spends more than £200.
- Contextual anomalies: a value is unusual only in its context, such as a heating bill that is normal in January and strange in July.
- Collective anomalies: each value is ordinary, but a group of them together is not, such as a heart trace that goes flat for two seconds, or a slow series of logins that together add up to an attack.
How does it work?
Almost every method in this lesson follows the same two steps. First, give each point an anomaly score: how far it is from the mean, how far from its neighbours, how quickly random cuts isolate it, how badly a model of normal data rebuilds it. Second, choose a threshold, and flag every point whose score is above it. The methods differ in what “unusual” means; the threshold decides how many alerts people have to deal with.
Why does it matter?
Fraud detection, fault detection in machines, intrusion detection on networks, and screening in medicine (unusual heart rhythms, unusual lab results) all use it. The cases that matter are usually rare: in a public dataset of real European card transactions, 492 of 284,807 were fraud, about 0.17% of them. That rarity shapes everything that follows, from which algorithms work to how they should be judged.
Anomaly detection is one of the jobs of unsupervised learning, alongside clustering and dimensionality reduction. The Unsupervised Learning lesson introduces all three.Key takeaways
- An anomaly is a point that does not fit the pattern of the rest: on its own (point), in its context (contextual) or as a group (collective).
- Detectors give every point an anomaly score, then flag the points above a threshold.
- The anomalies that matter, such as fraud and faults, are usually a tiny fraction of the data.
Why it is hard
If anomalies were common, labelled and stable, this would be ordinary classification. They are none of those things.
What is it?
Three problems make anomaly detection its own subject:
- Rare. One case in a thousand, or a million. A classifier trained on such data can score almost perfect accuracy by never predicting the rare class.
- Unlabelled. A label usually means a person has investigated the case, which is slow and expensive, so few past points have one. And new kinds of fraud or fault arise that look nothing like the examples you do have.
- Shifting. Normal behaviour changes with the seasons, with growth and with new products, and attackers change tactics once they are caught.
How does it work?
The amount of labelling available decides which kind of problem you are solving:
SupervisedLabelled examples of both normal and anomalous cases. Train a classifier, but treat it as an imbalanced problem. Only finds anomalies like the ones it has seen.Semi-supervised (novelty detection)A clean set of normal data only. Model what normal looks like, then flag new points that do not fit. Common for machines, where healthy running data is plentiful.Unsupervised (outlier detection)No labels; the data is mostly normal with a few unknown anomalies mixed in. Score every point by how isolated or unusual it is. The setting for most of this lesson.Libraries draw the same line: scikit-learn calls the clean-training case novelty detection and the contaminated case outlier detection.
Why does it matter?
Each problem has a cost. Rarity means accuracy is useless as a yardstick. Missing labels mean you often cannot measure recall at all, and must rely on small audited samples or planted test cases. Drift means a detector that worked at launch slowly fills analysts’ queues with false alarms. The later sections tackle each one.
Key takeaways
- Anomalies are rare, mostly unlabelled, and the meaning of normal drifts over time.
- With labels it is imbalanced classification; with clean normal data, novelty detection; with neither, outlier detection.
- Detectors usually produce a ranked queue for people, not automatic decisions.
Statistical baselines: z-scores and the median
The simplest detector is a ruler: how many standard deviations is this reading from the average? It works, until the anomalies start moving the ruler.
What is it?
The z-score of a value is its distance from the mean in units of standard deviation. A common rule flags any value with |z| ≥ 3. The robust score replaces the mean with the median and the standard deviation with the median absolute deviation (MAD): the median of the distances from the median. Multiplied by 1.4826, the MAD estimates the standard deviation when the data are normal, so the two scores are on the same scale.
z = (x − mean) / sdrobust = (x − median) / (1.4826 × MAD)
MAD = median( |xᵢ − median(x)| )
Iglewicz and Hoaglin’s modified z-score is the same robust score written as 0.6745 (x − median) / MAD; they suggest flagging values whose score is above 3.5 in absolute value.
How does it work?
Both rules measure distance from a centre with a yardstick. The difference is what happens when the data already contain anomalies. One huge value drags the mean towards itself and inflates the standard deviation, so it looks less extreme than it is; a group of them can hide each other completely. This is called masking. There is even a hard limit: in a sample of n values, no z-score can be larger than (n − 1)/√n, so with 10 readings the |z| ≥ 3 rule can never fire at all. The median and the MAD ignore how extreme the extreme values are, and cannot be dragged arbitrarily far until half the data is contaminated (a breakdown point of 50%), which is why Leys and colleagues recommend them over the mean and standard deviation for outlier screening.
With one fault, both rules catch it: z = 3.46 and a robust score of 4.14. Add the burst and the z-score row flags nothing, because the mean has moved to 61.9 and the band has widened to ± 12 °C. The robust row still flags three of the four faults: the median moved by 0.7 °C and the MAD by 0.15. The fourth, at 69 °C, now scores 3.44, just under the 3.5 cut-off. Drag the hottest reading out to 80 °C and watch the z-score band stretch to follow it.
More than one feature
For several features at once, the Mahalanobis distance is the multivariate z-score: distance from the mean, measured in units that account for each feature’s spread and for how the features move together. It suffers from masking for the same reason, and robust versions estimate the centre and spread from the most central part of the data instead, such as scikit-learn’s elliptic envelope.
Why does it matter?
These baselines are fast, explainable (“this reading is 5 robust standard deviations above normal”) and often enough, especially for a single sensor with a clean history. They assume one roughly symmetric cluster of normal values, which fails as soon as normal has several modes, such as weekday and weekend traffic. The next methods drop that assumption.
Key takeaways
- A z-score measures distance from the mean in standard deviations; anomalies inflate the very mean and sd they are judged by.
- Median and MAD are robust: a few extreme values barely move them, so it is much harder for faults to hide each other.
- Both assume a single cluster of normal values; multi-modal data needs distance or density methods.
Distance and density: k-NN and LOF
Instead of one centre for all the data, ask each point a local question: how far away are your nearest neighbours?
What is it?
The k-NN distance score is the distance from a point to its k-th nearest neighbour; the points with the largest scores are the outliers. The local outlier factor (LOF) refines it: it compares a point’s local density with the density around its neighbours. An LOF near 1 means “as crowded as my neighbours”; well above 1 means “much emptier around me than around them” (Breunig et al., 2000).
How does it work?
- k-NN distance. For each point, find its k nearest neighbours and take the distance to the farthest of them. Points inside any cluster, of any shape, have short distances; isolated points have long ones.
- LOF. Estimate each point’s local density as one over the average (reachability) distance to its k neighbours. Divide the neighbours’ average density by the point’s own. A point just outside a very tight cluster has neighbours with high density and a low density of its own, so its ratio is large, even if its raw distances are smaller than those inside a loose cluster.
k matters in both. Too small, and a few anomalies close together vouch for each other: each one’s nearest neighbour is another anomaly. Too large, and the score blurs small clusters into their surroundings.
At k = 1 the pair drops out of the top five; from k = 2 it ranks second and third. Now look at the local outlier above the tight cluster. With k-NN distance at k = 3 or more it never makes the top five, because points on the edge of the loose cluster are farther from their neighbours. Switch to LOF with k = 6 or more and all five planted points take the top five places: the local outlier is judged against how crowded its own neighbourhood is.
Why does it matter?
Distance methods make no assumption about the shape of normal data, which suits multi-modal data such as different customer types. The cost is speed: a naive implementation compares every point with every other, which is slow for millions of rows, and in very high dimensions distances tend to bunch together, so the nearest and farthest neighbours can be almost equally far away. Scaling matters too: features in different units must be standardised first, or the largest one dominates the distance.
The k-Nearest Neighbours lesson covers distances, scaling and the curse of dimensionality in more depth.Key takeaways
- The k-NN distance score flags points far from their k-th nearest neighbour, whatever the shape of the clusters.
- LOF compares a point’s density with its neighbours’ density, so it catches outliers next to dense clusters.
- k trades off: too small and clustered anomalies vouch for each other; too large and small clusters blur away.
Isolation forests: cut until alone
Most detectors model what normal looks like. Isolation forests skip that and ask a simpler question: how easy is this point to separate from the rest?
What is it?
An isolation forest is a collection of random trees. Each tree cuts the data at random, and the number of cuts needed to isolate a point (its path length) is short for anomalies and long for points in a crowd. Averaged over many trees, short paths become a high anomaly score (Liu, Ting and Zhou, 2008).
s(x) = 2^( −E[h(x)] / c(ψ) )c(ψ) = 2·H(ψ − 1) − 2(ψ − 1)/ψ
E[h(x)] is the average path length of x over the trees; c(ψ) is the average path length expected in a tree grown on ψ points, so scores are comparable across sample sizes. H is the harmonic number, about ln i + 0.5772.
How does it work?
- Draw a small random subsample of the data, typically ψ = 256 points.
- Grow a tree: pick a feature at random and a cut value at random between that feature’s minimum and maximum; split; repeat in each half until every point is alone or a height limit of about log₂ ψ is reached.
- Repeat for many trees (100 is the usual default).
- Send each point down every tree, average its path length, and convert to a score. The paper reads it like this: very close to 1, an anomaly; much smaller than 0.5, quite safe to call normal; about 0.5 for every point, no distinct anomaly in the sample.
Over 200 random trees, the far loner in the lower left needs 3.0 cuts on average and a point from the tight cluster 9.4. A single tree is noisy: across those trees the loner took anywhere from 1 to 8 cuts and the crowd point from 3 to 17. That is why the method averages many trees.
With 100 trees, the loner’s average path is 3.05 cuts, a score of 0.79; the crowd point’s is 10.27, a score of 0.45. One tree gives a blocky, noisy map; by a few dozen trees it has settled. The rectangular streaks come from the cuts themselves: every cut is horizontal or vertical, so the score spreads along the axes. Look at which points are ringed: like k-NN distance, the forest ranks a point on the edge of the loose cluster above the local outlier sitting just outside the tight one. Isolation is a global measure; for local outliers, LOF is still the better tool.
Why does it matter?
Isolation forests compute no distances and no densities. Growing t trees on subsamples of ψ points takes on the order of t·ψ·log ψ steps, however large the full dataset is, and scoring a point takes at most about log₂ ψ comparisons per tree, so the cost grows linearly with the number of points scored. Small subsamples are a feature, not a compromise: the paper found that they reduce swamping (normal points wrongly flagged) and masking, that 256 points generally give enough detail across a wide range of data, and that path lengths usually settle well before 100 trees. Implementations are available in libraries such as scikit-learn.
Isolation trees are a random cousin of decision trees. The Decision Trees lesson shows how trees cut feature space into boxes.Key takeaways
- Random axis-aligned cuts isolate anomalies in few steps and crowd points in many.
- The score 2^(−E[h]/c(ψ)) turns the average path length into a number near 1 for anomalies.
- Small subsamples and no distance computations make isolation forests fast, and small subsamples also reduce swamping and masking.
Reconstruction error: PCA and autoencoders
Some anomalies hide in plain sight: every value is normal, but the combination is impossible. To catch them, learn how the features move together.
What is it?
Reconstruction-based detection compresses each data point with a model fitted to normal data, rebuilds it, and scores it by the reconstruction error: how far the rebuilt point is from the original. Normal points fit the pattern and are rebuilt well; anomalies are not.
How does it work?
With PCA, compressing means projecting onto the main directions of variation and rebuilding means mapping back: the error is the squared distance from the point to that subspace. An autoencoder does the same with a neural network, so the pattern can be curved. In both, the model is fitted on data that is mostly or entirely normal, and the threshold is set from the errors it makes on normal data.
The “off the line” reading, 1,200 rpm at 9.6 A, has z-scores of −1.23 and 1.45: both sensors look ordinary on their own. But at that speed a healthy motor draws about 6.8 A, and the reconstruction error is 3.59, twenty times the largest error on the 80 normal readings (0.18). The “fast, consistent” reading at 2,100 rpm and 10.4 A is the opposite: both z-scores are above 2, but it sits on the line, and its reconstruction error is just 0.02. Reconstruction error flags broken relationships, not large values, so catching a reading that is extreme but consistent needs a second check on the compressed code itself: how far along the line the reading sits.
Why does it matter?
Machines, networks and bodies are full of features that move together: speed and current, requests and bandwidth, heart rate and breathing. A fault can show up as a broken relationship before any single value is extreme, which is why reconstruction error, from PCA on a few sensors to autoencoders on images and audio, is used to monitor machines and industrial processes.
The Autoencoders lesson trains a real network on glyphs and uses its reconstruction error to spot ones it has never seen.Key takeaways
- Reconstruction methods learn the pattern of normal data and score points by how badly they are rebuilt.
- They catch anomalies in the combination of features, which per-feature checks miss.
- Fit on normal data and keep the model constrained, or it learns to rebuild the anomalies too.
Choosing a threshold: the accuracy trap
Every detector ends with a dial: flag everything above this score. Where you set it decides how many frauds you catch and how many innocent customers you call.
What is it?
With labels for at least a test set, a threshold can be judged by two numbers. Recall is the share of real anomalies that were flagged. Precision is the share of flags that were real anomalies. Lowering the threshold can only raise recall, and usually lowers precision. The precision-recall (PR) curve plots that trade-off at every threshold, and the average precision (AP), a step-by-step estimate of the area under it, summarises it in one number.
How does it work?
Accuracy, the share of all points classified correctly, is dominated by the normal class when anomalies are rare. The ROC curve, which plots recall against the false alarm rate, has a subtler version of the same problem: a false alarm rate of 1% sounds small, but 1% of a million normal transactions is 10,000 alerts. Saito and Rehmsmeier showed that under heavy imbalance ROC plots can be deceptive and PR plots are more informative, and the page for the real card-fraud dataset recommends measuring the area under the PR curve for that reason.
At a threshold of 4.5, six frauds are caught with no false alarms: precision 100%, recall 60%. The other four frauds look like ordinary spending, with scores between 1.8 and 2.9. Lower the threshold to 2.5 and eight of the ten are caught, but 425 false alarms come with them: precision falls under 2%. The ROC curve barely notices (its area is 0.97); the PR curve, with an average precision of 0.61, shows the cliff. Flag nothing and accuracy is 99.90%.
Setting the threshold in practice
Without labels, one practical way to set the threshold is by budget: how many alerts can analysts review each day? Flagging the top 50 scores is a threshold too. Where some labels exist, choose the point on the PR curve that matches the costs: a missed fraud might cost hundreds of pounds, a false alarm a phone call. And whenever possible, test with planted anomalies, as in these demos, because you know exactly which ones should have been found.
Why does it matter?
The threshold turns scores into work and losses. Set it too low and analysts face a queue of false alarms they soon stop trusting; set it too high and fraud and faults go through unseen. And a detector judged by accuracy alone can look excellent while catching nothing, as the “Flag nothing” button shows.
The Evaluating Models lesson covers precision, recall, ROC and PR curves and imbalanced data in general.Key takeaways
- When anomalies are rare, accuracy rewards flagging nothing; use precision and recall.
- PR curves and average precision expose false alarms that ROC curves hide under heavy imbalance.
- Thresholds are set by costs and review capacity; test them on known or planted anomalies.
When normal moves: drift
A detector learns what normal looked like when it was fitted. Normal does not stay still.
What is it?
Drift is a change over time in the data a model sees, or in what counts as normal. It can be gradual (a sensor slowly wearing, a business growing), seasonal (December shopping) or sudden (a new product, a software update, an attacker changing tactics). Gama and colleagues survey the strategies for adapting.
How does it work?
The simplest defence is to fit the baseline on a rolling window of recent data, so it moves with normal. The window length is a trade-off: short windows follow drift quickly but are noisy and can adapt to a slow fault until it looks normal; long windows are stable but fall behind. Contextual baselines, such as comparing a Monday with previous Mondays, handle seasonality.
Against the fixed baseline, all four faults are caught but so are 70 ordinary days from day 40 onwards, because the drift has carried normal out of the band. A 30-day rolling window catches all four with one false alarm. A 5-day window catches them too, but its baseline is so noisy that it raises 9 false alarms.
Why does it matter?
When drift goes unnoticed, a detector does not crash. It raises a slowly rising tide of alerts that people learn to ignore, as the fixed baseline did above. Watch the alert rate itself, refit on recent data, keep analysts’ verdicts as labels for tuning, and remember that a rolling baseline can learn to accept a fault that develops slowly, so check long-term trends separately.
Key takeaways
- Drift moves normal away from the data a detector was fitted on, so false alarms climb.
- Rolling windows and contextual baselines keep up; the window length trades responsiveness against noise.
- Monitor the alert rate and keep reviewers’ verdicts as labels for retuning.
Which method when
No method wins everywhere. The shape of the data, how many features there are and what an anomaly looks like decide.
What is it?
Each family in this lesson has its own idea of “unusual”: far from one centre (z-scores and the median), far from its neighbours or emptier than them (k-NN distance and LOF), quick to cut off from the rest (isolation forests), or badly rebuilt by a model of normal data (reconstruction error). Choosing a detector means choosing the idea that matches the anomalies you care about.
How does it work?
Match the method to the data you have:
Robust z-score (median/MAD)One feature, one cluster of normal values. Instant, explainable, a good first alarm on any single sensor.k-NN distance and LOFA few standardised features, clusters of different shapes and densities. Slower on big data; choose k with care.Isolation forestMany rows, many numeric features, no labels. Fast, with two main settings: the original paper’s defaults are 100 trees and 256 points.Reconstruction (PCA, autoencoder)Many correlated features: sensors, images, audio. Catches broken relationships; needs normal data to fit on.Whatever the method, the same habits matter: standardise features, fit on data that is as clean as you can get, test on planted or labelled anomalies, judge with precision and recall rather than accuracy, and watch for drift once the detector is running.
Why does it matter?
A detector can only find the kind of unusual it measures. In the demos above, the per-sensor z-scores passed the motor reading with an impossible combination, and the k-NN distance score and the isolation forest both ranked a point on the edge of the loose cluster above the local outlier that LOF picked out.
Key takeaways
- Start with a robust baseline; add an isolation forest or LOF when the data has many features or several clusters.
- Reconstruction methods suit correlated features and broken relationships.
- Whatever the method, test on planted or labelled anomalies, judge by precision and recall, and watch for drift.
Check your understanding
Six situations where anomaly detection is used. Each asks you to apply an idea, not just recall it.
Question 1 of 6A payments team reports that its new fraud model is 99.8% accurate on last month’s transactions, of which 0.2% were fraud. What should you ask before celebrating?
Next, see how the same tools fit into the wider picture in Unsupervised Learning, or practise choosing thresholds in the Confusion Matrix lab.
References
The papers, books and documentation behind the methods and claims in this lesson.
References
- [1]
Anomaly Detection: A Survey(opens in a new tab)
Varun Chandola, Arindam Banerjee & Vipin Kumar, 2009
ACM Computing Surveys 41(3), article 15, 58 pages. A broad overview: point, contextual and collective anomalies; supervised, semi-supervised and unsupervised settings; and the main families of methods.
- [2]
Credit Card Fraud Detection dataset(opens in a new tab)
Machine Learning Group, Université Libre de Bruxelles (ULB) & Worldline, 2016
Two days of transactions by European cardholders in September 2013: 492 frauds among 284,807 transactions (about 0.17%). Given the imbalance, the dataset page recommends measuring the area under the precision-recall curve, since confusion-matrix accuracy is not meaningful.
- [3]
Novelty and Outlier Detection (scikit-learn user guide, section 2.7)(opens in a new tab)
scikit-learn developers, 2026
Documentation of scikit-learn’s one-class SVM, robust covariance (elliptic envelope), isolation forest and local outlier factor, and of the difference between outlier detection (training data contains outliers) and novelty detection (it does not).
- [4]
Alternatives to the Median Absolute Deviation(opens in a new tab)
Peter J. Rousseeuw & Christophe Croux, 1993
Journal of the American Statistical Association 88(424), 1273–1283. The MAD, its 1.4826 consistency factor for normal data, its 50% breakdown point, and more efficient robust alternatives.
- [5]
NIST/SEMATECH, 2012
Describes masking and swamping, the bound (n − 1)/√n on the largest possible z-score in a sample of n values, and Iglewicz and Hoaglin’s modified z-score 0.6745 (x − median) / MAD with a cut-off of 3.5. The handbook was created in 2003 and significantly revised in 2012.
- [6]
Maximum Z Scores and Outliers(opens in a new tab)
Ronald E. Shiffler, 1988
The American Statistician 42(1), 79–80. Shows that in a sample of n values no z-score can exceed (n − 1)/√n.
- [7]
Christophe Leys, Christophe Ley, Olivier Klein, Philippe Bernard & Laurent Licata, 2013
Journal of Experimental Social Psychology 49(4), 764–766. Argues against flagging outliers with the mean ± 3 standard deviations, because the mean and standard deviation are themselves sensitive to outliers, and recommends the median absolute deviation instead.
- [8]
Efficient Algorithms for Mining Outliers from Large Data Sets(opens in a new tab)
Sridhar Ramaswamy, Rajeev Rastogi & Kyuseok Shim, 2000
Proceedings of the 2000 ACM SIGMOD International Conference on Management of Data, 427–438. Ranks every point by the distance to its k-th nearest neighbour and declares the top n points outliers.
- [9]
LOF: Identifying Density-Based Local Outliers(opens in a new tab)
Markus M. Breunig, Hans-Peter Kriegel, Raymond T. Ng & Jörg Sander, 2000
Proceedings of ACM SIGMOD 2000 (SIGMOD Record 29(2)), 93–104. The local outlier factor: compares a point’s local reachability density with that of its neighbours, and shows that the LOF of points deep inside a cluster is close to 1.
- [10]
Isolation Forest(opens in a new tab)
Fei Tony Liu, Kai Ming Ting & Zhi-Hua Zhou, 2008
Eighth IEEE International Conference on Data Mining (ICDM 2008), 413–422. Isolates points with random cuts; anomalies have short average path lengths. Defines the score 2^(−E[h(x)]/c(ψ)), uses subsamples of 256 points and 100 trees as its defaults, and reports that small subsamples reduce swamping and masking.
- [11]
Takaya Saito & Marc Rehmsmeier, 2015
PLOS ONE 10(3), e0118432. Shows that ROC plots can be deceptive on imbalanced data, while precision-recall plots, which measure the share of true positives among the positive predictions, give an accurate picture of performance.
- [12]
A Survey on Concept Drift Adaptation(opens in a new tab)
João Gama, Indrė Žliobaitė, Albert Bifet, Mykola Pechenizkiy & Abdelhamid Bouchachia, 2014
ACM Computing Surveys 46(4), article 44. Concept drift, where the relation between a model’s inputs and its target changes over time: the strategies for handling it, representative techniques, and how to evaluate adaptive learners.
Related
- Builds on: Unsupervised Learning
- Builds on: Evaluating Models
- Practise in the lab: Clustering Visualizer
- Practise in the lab: Confusion Matrix Explorer