Anomaly detection
Last updated
A card payment unlike any the owner has made, a sensor reading that jumps, a penguin weighed at 37 kilos: some rows are unusual, and finding them matters. Usually nobody has labelled what unusual looks like, and there are far too few examples to learn it anyway. So anomaly detection learns what normal looks like, and flags what doesn't fit. This lesson does it with z-scores and with an isolation forest, and shows how the anomalies themselves can hide.
By the end of this lesson you can
- Flag unusual values with z-scores, and explain masking
- Explain why an isolation forest isolates anomalies in few cuts
- Fit IsolationForest on normal data, and score new rows
What's unusual?
An anomaly (or outlier) is an example that doesn't fit the pattern of the rest. Some are mistakes to fix, such as a typo or a broken sensor; some are exactly what you're looking for, such as fraud, a failing machine or a new disease.
Why not just train a classifier, normal against anomaly? Usually you can't. Anomalies are rare, perhaps one in ten thousand, so there are too few to learn from; they're varied, since each fraud is new; and nobody has labelled them. So anomaly detection turns the question round: learn what normal looks like, with no labels, and score each new example by how badly it fits. It's unsupervised (lesson 2.2), or, when you have a clean set of normal examples to learn from, one-class.
z-scores
For one number, the simplest test is lesson 1.10's z-score: how many standard deviations a value is from the mean,
and flag anything with . If the values are bell-shaped, fewer than 3 in 1,000 normal values are that far out. Two typing mistakes in the penguins' masses: penguin 10 weighed as 37,500 g (an extra 0) and penguin 200 as 450 g (a missing one):
Penguin 10 is found, 16.8 standard deviations out. Penguin 200, at 450 g, has a z-score of only −1.9, and isn't flagged. A 450 g adult penguin is impossible, so why?
Wrong way: fitting on data that contains the anomalies
The mean and standard deviation were computed from the data with the mistakes in it. The 37,500 g penguin drags the mean up and, much worse, inflates the standard deviation, so every other value looks closer to normal. One anomaly hides another: it's called masking. Fit the mean and standard deviation on data known to be clean instead:
Now both are caught: +41.6 and −4.7. The lesson holds for every method here. Fit the model of "normal" on data you trust to be normal, or with a method that resists outliers, such as the median and the interquartile range (lesson 4.1's RobustScaler), and only then score the data you're checking.
A z-score also looks at one number at a time. A penguin with a short flipper and a heavy body can be ordinary in each and unusual together. For that, you need a method that looks at all the features at once.
Isolation: few cuts for the odd one out
An isolation forest (Liu, Ting and Zhou, 2008) starts from a simple observation: unusual points are easy to separate. Cut the data at random, a random feature at a random value between its smallest and largest, and keep only the side your point is on. Repeat until it's alone. An outlier, out on its own, is usually cut off within a few cuts. A point in the crowd needs many:
This time it took 4 random cuts to leave the outlier on its own. Averaged over 200 random trees: 3.3 cuts for the outlier, 9.7 for the point in the crowd. Few cuts means unusual.
So the number of cuts needed is a score: few means unusual. One random tree is noisy, so average over many. The same count, by hand, over 200 random trees:
2.3 cuts on average to isolate the outlier, 14.5 for an ordinary point. It never measures a distance or fits a curve, and it works on many features at once.
IsolationForest
scikit-learn's version, fitted on 300 normal points, then asked to score them and 3 planted outliers, at (4, 4), (−4, 3.5) and (0, −5):
score_samples gives each point a score, lower for more unusual. The five lowest: rows 301 and 300, two of the planted outliers; then rows 151 and 239, ordinary points that happen to sit at the edge of the cloud; then 302, the third outlier. Any method that ranks points has this problem: the edge of normal shades into the unusual. You choose how many to flag, from how many you can afford to check.
predict turns scores into decisions, 1 for normal and −1 for an anomaly, using a cut-off you can set with contamination, the share you expect to be unusual:
The centre, (0, 0), and (1.5, 1), at the edge, are normal; (4, 4) is an anomaly.
One-class thinking
Two situations, with different rules:
- Novelty detection: you have a clean set of normal examples, such as a month of readings from a machine known to be healthy. Fit on those, then score new data as it arrives. This is the safer case, and the one step 3 recommends.
- Outlier detection: you only have the data with the anomalies already in it. Use a method that tolerates some, such as an isolation forest with
contaminationset, and expect masking at the edges.
Either way, evaluate as you would a classifier, if you can get even a few labelled anomalies: precision and recall (lesson 2.8) among the top-scored rows, which is what someone will actually check. Other methods in scikit-learn: LocalOutlierFactor compares each point's density with its neighbours'; OneClassSVM draws a boundary around the normal data (lesson 4.7); a Gaussian mixture's low-likelihood points are unusual (lesson 4.9); and DBSCAN's noise points too.
When to use it
Good at
- Unusual rows in tables, with many features at once
- No labels
- Speed, on big data
Bad at
- Telling you why a row is unusual
- Anomalies that are only odd in context (a normal value at the wrong time of day), unless you build that feature
- Telling you how many anomalies there are: you choose the cut-off
Needs from you
- Clean normal data to fit on, when you can get it
- A contamination rate, or a number of rows you can afford to check
- A few labelled anomalies, to measure precision and recall
In scikit-learn
- Classification: none:
IsolationForest,LocalOutlierFactor,OneClassSVM - Regression: none
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Liu, Ting and Zhou, Isolation forest, IEEE International Conference on Data Mining, 2008: isolating anomalies with random trees
- Chandola, Banerjee and Kumar, Anomaly detection: a survey, ACM Computing Surveys 41(3), 2009: kinds of anomaly and of method
- scikit-learn: Novelty and outlier detection: IsolationForest, LocalOutlierFactor, OneClassSVM, and novelty against outlier detection