Anomaly detection

Find rare, unusual rows without labels: isolation forests, local outlier factor and how to set the expected share of anomalies.

Lesson 50 of 6610 minIntermediate

You will learn to

  • Explain how isolation forest and local outlier factor score unusual rows
  • Set a contamination rate
  • Evaluate anomalies without labels

Before this lesson

Intuition

A bank clerk who has seen thousands of transactions notices the odd one at once: an unusual amount, in an unusual place, at an unusual hour. Nobody labelled it as fraud; it simply did not look like the rest.

Anomaly detection (also called outlier detection) automates this. The algorithm learns what ordinary rows look like and gives every row an anomaly score: the higher the score, the stranger the row. It is unsupervised: you do not need examples of anomalies, which is useful because they are rare and often new. Typical uses are fraud, faulty sensors, data entry errors and unusual behaviour in logs.

Two simple ideas drive most detectors:

  • Isolation. Unusual rows are easy to separate from the others. Cut the data with random lines and an odd row ends up alone after only a few cuts, while a row in a crowd needs many.
  • Local density. A row is unusual if it lives in a much sparser area than its neighbours do. This is the idea of the local outlier factor (LOF): it compares a row's density with the density around its nearest neighbours, so it can find a row that is ordinary globally but odd for its neighbourhood.

Picture it

12Random cutUnusual row: isolated after 2 cutsTypical row
Random cuts (dashed lines) isolate the unusual row (dark outline) after two cuts. A row inside the dense group would need many more cuts.

An isolation forest repeats this with many random trees and averages how many cuts each row needed. Short average path means high anomaly score.

The math

Isolation forest. Let h(x)h(x) be the number of cuts needed to isolate row xx in one random tree, and E[h(x)]E[h(x)] its average over the trees. With a sample of nn rows per tree, the normalising length is c(n)=2H(n−1)−2(n−1)/nc(n) = 2H(n-1) - 2(n-1)/n, where HH is the harmonic number (approximately a logarithm). The score is:

s(x,n)=2−E[h(x)]/c(n)s(x, n) = 2^{-E[h(x)]/c(n)}

A score near 1 means very short paths (anomaly). A score near 0.5 means an average path. Below 0.5, the row is deep inside the data.

Local outlier factor. Let lrd⁡(x)\operatorname{lrd}(x) be the local reachability density of xx, roughly the inverse of the average distance to its nearest neighbours. Then:

LOF⁡(x)=mean of lrd⁡(neighbours of x)lrd⁡(x)\operatorname{LOF}(x) = \frac{\text{mean of } \operatorname{lrd}(\text{neighbours of } x)}{\operatorname{lrd}(x)}

A value near 1 means the row is as dense as its neighbours. A value well above 1 means it is much sparser.

Contamination is the expected proportion of anomalies. Detectors turn scores into yes/no labels by choosing the threshold so that this share of rows is flagged.

Worked example

Isolation score. For n=256n = 256 rows per tree, c(256)≈10.25c(256) \approx 10.25. Then:

Average cuts E[h]Score
32 to the power of (-3 / 10.25) = 0.82
80.58
10.250.50
120.44

A row isolated in 3 cuts scores 0.82, clearly anomalous. A row that needs 12 cuts scores 0.44, ordinary.

LOF. A row's nearest neighbours are on average 4 units away, so its density is about 1/4 = 0.25. Its neighbours each have neighbours about 1 unit away, so their density is about 1. LOF = 1 / 0.25 = 4: the row is four times sparser than its surroundings.

Contamination. With 1,000 rows and contamination 0.02, the threshold flags the 20 highest-scoring rows. If you set 0.10 you get 100 flagged rows, including many ordinary ones. The setting does not change the scores, only where the line is drawn.

How mlflow does it

  • Create a pipeline with the task Anomaly detection. The catalog includes isolation forest (iforest), local outlier factor (lof), k-nearest neighbours detector (knn), one-class SVM (svm), PCA-based (pca), minimum covariance determinant (mcd), angle-based (abod), connectivity-based (cof), histogram-based (histogram), subspace (sod), stochastic outlier selection (sos) and clustering-based (cluster) detectors.
  • Many detectors expose a contamination setting, described in the app as the proportion of outliers in the data set.
  • Plots for an anomaly model: Anomaly score distribution and Anomaly map. The score distribution helps you pick a threshold: a clear gap between a long low tail and a few high scores means an obvious cut.
  • There is no target in this task, so no accuracy-style metric. See the Anomaly detection task page.

Common mistakes

  • Treating contamination as known. It is a guess. Start with a number your team can review, and look at the score distribution before fixing it.
  • Deleting flagged rows automatically. An anomaly is unusual, not necessarily wrong. It might be your most valuable customer. Review before removing.
  • Not scaling. Distance-based detectors (LOF, kNN) are dominated by large-scale columns. Scale first.
  • Expecting one detector to find every kind of oddity. Isolation forest finds global outliers; LOF finds local ones. Compare two or more.
  • Evaluating with accuracy on a few known cases. With rare anomalies, accuracy is meaningless. Use precision of the top-ranked rows reviewed by an expert.
  • Training on data that is full of anomalies. If the "normal" data is contaminated, the detector learns the anomalies as normal.

Try it in mlflow

Create an anomaly detection pipeline

  1. Open Pipelines and click New pipeline.
  2. Choose the task Anomaly detection and pick a dataset without a target column.
  3. Add Isolation Forest (iforest) and Local Outlier Factor (lof) in the Models part and run the pipeline.
  4. Open the best model candidate and look at the Anomaly score distribution and the Anomaly map.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. In an isolation forest, why do unusual rows get a high anomaly score?
  2. 2. You set contamination to 0.02 on 1,000 rows. How many rows will be flagged as anomalies?
  3. 3. You have no labels. Which is the most sensible way to check anomaly detections?