Unit 8, lesson 61

Anomaly and Novelty Detection

How anomaly and novelty detection score observations against a reference population, how a distance score and an isolation forest work, why training contamination matters, and how to set and evaluate an alert threshold.

  • Video 61
  • Detecting Unusual Observations

A plant records a temperature reading from every machine each minute, and a technician can inspect only a few machines per shift. Which readings deserve a look? A detector can only say that a reading is unusual relative to some reference, and unusual is not the same as faulty or harmful. This lesson fixes the reference population, builds a distance score and an isolation forest score, turns scores into alerts with a threshold, and asks what evidence shows that the alerts are useful.

Key terms

Anomaly detection

Definition Anomaly detection is the task of finding observations that depart markedly from a stated reference population. A detector has three parts, an anomaly score fitted on data from the reference population, an alert threshold that turns scores into flags, and an action that a flag triggers, such as a manual review or a recheck of the sensor. Anomalous here means unusual relative to the reference. Whether a flagged observation is a fault, a harmful event or a rare but legitimate condition is a separate question, answered by review or by later outcomes. A detector is useful only to the extent that its flags agree with those answers on data it was neither fitted nor tuned on.

In plain words Rare and harmful are different properties. A legitimate operating mode that occurs once a month is rare but harmless, and a fault that happens every day can be common enough to look normal. A detector finds the unusual, and review or later outcomes decide what the unusual cases mean.

Example A constructed reference sample of the readings 9, 10, 10 and 11, in temperature deviation units on a fixed calibrated scale, describes normal operation of one machine type. Four later readings, 8, 9.5, 10.5 and 14, are scored against it. An independent review labels 14 as harmful and 8 as an unusual but legitimate operating condition. Both readings lie outside the reference range, and only one of them called for action.

Reference population

Definition The reference population is the population of observations that the detector should treat as normal. It is defined by the context in which the scores will be used, such as the machine type, the operating mode, the sensor and its calibration, and the time period. The reference sample is a set of observations from that population, available at fitting time, from which the parameters of the score are estimated. Every statement that an observation is unusual is relative to the reference sample, and it carries over to the reference population only as far as the sample represents it.

In plain words Unusual compared with what? The same reading can be ordinary for one kind of machine and alarming for another. Choosing the reference is a modeling decision, and so is the choice between fitting one reference per context and including the context as a feature.

Example Machine type A has the reference readings 9, 10, 10, 11 and machine type B has 13, 14, 14, 15. Both samples have the standard deviation 0.5≈0.707\sqrt{0.5} \approx 0.707, with divisor nn, and their means are 10 and 14. A reading of 14 lies 4/0.5≈5.664/\sqrt{0.5} \approx 5.66 standard deviations from the mean of A and exactly at the mean of B, while a reading of 10 is the other way around. Scoring a type B machine against the type A reference would flag its ordinary readings.

Anomaly score

Definition An anomaly score is a function s(x)s(\mathbf{x}) fitted on a reference sample, with a stated direction, here larger meaning more unusual. Its operational definition names the method, the features and their scaling, the reference sample and the direction. It ranks observations by their departure from the reference, and it is not a probability of failure or of harm unless it has been calibrated against labeled outcomes. A simple score for a single feature is the standardized distance from the reference mean,

s(x)=∣x−m∣d,s(x) = \frac{\lvert x - m \rvert}{d} ,

where mm is the mean and dd the standard deviation of the reference sample, with divisor nn and d>0d > 0, both computed once and then frozen. This score assumes that normal behavior forms one central range. A reference with several separate modes needs a different score, such as a mixture density, and correlated features call for a distance that accounts for the correlation, such as the Mahalanobis distance.

In plain words The distance score counts how many reference standard deviations a reading lies from the reference mean. It has no units and is easy to explain. Its weakness is its picture of normal as one bump, so a reading in an empty gap between two normal modes can get a low score.

Example For the reference 9, 10, 10, 11, the mean is 10 and the average squared deviation is (1+0+0+1)/4=0.5(1 + 0 + 0 + 1)/4 = 0.5, so d=0.5≈0.7071d = \sqrt{0.5} \approx 0.7071. The four later readings score

s(8)=22≈2.828,s(9.5)=s(10.5)≈0.707,s(14)=42≈5.657.\begin{gathered} s(8) = 2\sqrt{2} \approx 2.828, \\[0.4em] s(9.5) = s(10.5) \approx 0.707, \\[0.4em] s(14) = 4\sqrt{2} \approx 5.657. \end{gathered}

Pooling the readings of machine types A and B into one reference gives the mean 12 and the standard deviation 4.5≈2.12\sqrt{4.5} \approx 2.12. A reading of 12, unlike every reading of either machine, then gets the lowest possible score, 0.

Novelty detection

Definition Novelty detection fits the score on a reference sample that is intended to contain only normal observations, then scores new observations made later for departure from it. Outlier detection, by contrast, fits on data that may already contain anomalies and tries to find them within the same data. Training contamination is the presence, in the data used to fit the score, of observations from outside the reference population, such as faults or recording errors, and the contamination rate is their fraction. Contamination pulls the fitted center toward the anomalies and inflates the fitted spread, so anomalies resembling the contaminating ones receive lower scores, an effect called masking, and the detector learns that some failure behavior is normal. Authors use these terms differently, so a description of a detector should state whether the fitting data are meant to be clean, how contamination is handled, and whether scores are used on the fitting data or on future observations.

In plain words Novelty detection asks whether a new case looks like a clean history. Outlier detection asks which cases in a pile look unlike the rest. Both suffer when failures hide in the data treated as normal. Refitting on every new batch without review can slowly absorb anomalies into the definition of normal, so score rates and the reference itself should be monitored over time.

Example Suppose the harmful reading 14 had slipped into the reference sample, which becomes 9, 10, 10, 11, 14. The mean moves to 10.8, the average squared deviation grows to 2.96 and the standard deviation to about 1.720. A new reading of 14 now scores (14−10.8)/1.720≈1.86(14 - 10.8)/1.720 \approx 1.86 instead of 5.66, and a new reading of 8 scores about 1.63 instead of 2.83. At an alert threshold of 2, the contaminated detector flags neither of them.

Isolation forest

Definition An isolation forest scores observations by how quickly random splits separate them from a reference sample. Each of its tt trees is grown on a subsample of ψ≥2\psi \ge 2 reference observations drawn without replacement, and ψ=256\psi = 256 is a common default when enough data exist. At each node a feature is chosen at random, in common implementations among the features that still vary in the node, and a split value is drawn uniformly between the smallest and largest values of that feature in the node. Observations below the split go left and the rest go right. A node becomes a leaf when it holds one observation, when all its observations are identical, or when its depth reaches the height limit ⌈log⁡2ψ⌉\lceil \log_2 \psi \rceil. To score x\mathbf{x} in one tree, follow its splits to a leaf at depth ee that holds mm reference observations, and set its path length to h(x)=e+c(m)h(\mathbf{x}) = e + c(m), where c(1)=0c(1) = 0 and

c(m)=2Hm−1−2(m−1)mc(m) = 2H_{m-1} - \frac{2(m - 1)}{m}

for m≥2m \ge 2, with the harmonic numbers Hr=1+12+⋯+1rH_r = 1 + \tfrac12 + \dots + \tfrac1r. The correction c(m)c(m) is the average path length of an unsuccessful search in a binary search tree with mm keys, and it stands in for the splits the leaf did not make. With hˉ(x)\bar{h}(\mathbf{x}) the average path length over the trees, the score is

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

a number between 0 and 1 that is larger for shorter paths. Implementations often approximate HrH_r by ln⁡r+0.5772\ln r + 0.5772, and some report the negative of this score or subtract an offset, so check which direction means more unusual before setting a threshold. A score of 0.6 is not a 60 percent probability of anything.

In plain words An unusual observation sits apart, so random cuts tend to separate it after only a few splits, while an observation inside a dense group needs many. The trees never estimate a density or a center. One consequence is saturation. Split values come only from the range of the reference sample, so every value beyond that range follows the same branch as the most extreme reference value, however far out it lies.

Example Use the whole reference sample 9, 10, 10, 11 in every tree, so ψ=4\psi = 4, the height limit is ⌈log⁡24⌉=2\lceil \log_2 4 \rceil = 2, and

c(4)=2(1+12+13)−64=113−32=136.\begin{aligned} c(4) &= 2\bigl(1 + \tfrac12 + \tfrac13\bigr) - \tfrac{6}{4} \\[0.4em] &= \tfrac{11}{3} - \tfrac{3}{2} = \tfrac{13}{6} . \end{aligned}

For the reading 8, the first split falls below 10 with probability 1/21/2, which leaves 8 at depth 1 in a leaf holding only the reference reading 9, so its path length is 1. Otherwise 8 reaches such a leaf at depth 2. Averaged over the random split values, the expected path lengths of the readings 8, 9.5, 10.5 and 14 are 1.5, 2.25, 2.25 and 1.5. With many trees the average paths approach these values, so the scores approach

2−1.5⋅6/13=2−9/13≈0.619,2−2.25⋅6/13=2−27/26≈0.487.\begin{gathered} 2^{-1.5 \cdot 6/13} = 2^{-9/13} \approx 0.619 , \\[0.4em] 2^{-2.25 \cdot 6/13} = 2^{-27/26} \approx 0.487 . \end{gathered}

A finite forest gives averages near these values that vary with the random seed. An alert threshold of 0.6 flags 8 and 14, while the distance score with threshold 3 flags only 14. The two methods rank the readings differently because they measure different things, and neither ranking is right in general.

Alert threshold

Definition An alert threshold τ\tau turns a score in which larger means more unusual into a decision, flag x\mathbf{x} when s(x)≥τs(\mathbf{x}) \ge \tau. It is chosen on development data from the review capacity and the costs of missed events and of false alarms, and it is frozen before the final evaluation. On a protected evaluation set with reliable labels, the flags give the counts TP\mathrm{TP}, FP\mathrm{FP}, FN\mathrm{FN} and TN\mathrm{TN}, and

precision=TPTP+FP,recall=TPTP+FN.\begin{gathered} \text{precision} = \frac{\mathrm{TP}}{\mathrm{TP} + \mathrm{FP}} , \\[0.4em] \text{recall} = \frac{\mathrm{TP}}{\mathrm{TP} + \mathrm{FN}} . \end{gathered}

The false-alarm rate is FP/(FP+TN)\mathrm{FP}/(\mathrm{FP} + \mathrm{TN}). Precision needs at least one flag, recall at least one harmful case and the false-alarm rate at least one harmless case. The review workload is the number of flags per operating period. A budget rule that flags the rr highest scores in each period is an alternative to a fixed threshold. A threshold derived from an assumed contamination rate builds in that assumption and does not measure how often harmful events occur.

In plain words A lower threshold catches more harmful events and sends more harmless ones to review. Where to stop depends on how many reviews are possible and on what a missed event costs, which the scores alone cannot say. Evaluation also needs labels for cases that were not flagged, because a review of flagged cases alone says nothing about the harmful events that were missed.

Example The four later readings have distance scores 2.83, 0.71, 0.71 and 5.66, and only 14 is labeled harmful. A threshold of 3 flags only 14, so TP=1\mathrm{TP} = 1 and FP=0\mathrm{FP} = 0, which gives precision 1, recall 1 and false-alarm rate 0. A threshold of 2 flags 8 and 14, one true positive and one false positive, so precision falls to 1/21/2, recall stays 1 and the false-alarm rate rises to 1/31/3. With four constructed cases these numbers show the arithmetic only. They are not reliable estimates of rates in operation.

Check yourself

  1. A fresh reviewed set has the scores 0.2, 0.4, 0.7, 0.8 and 0.9 with the harm labels 0, 0, 1, 0 and 1, and larger scores mean more unusual. Compare the thresholds 0.7 and 0.9, with flags for scores at or above the threshold, by review count, precision and recall.
Show the answer

At threshold 0.7 the scores 0.7, 0.8 and 0.9 are flagged, three reviews. Two of them are harmful and one is harmless, and no harmful case is missed, so TP=2\mathrm{TP} = 2, FP=1\mathrm{FP} = 1 and FN=0\mathrm{FN} = 0. Precision is 2/3≈0.6672/3 \approx 0.667 and recall is 2/2=12/2 = 1.

At threshold 0.9 only the score 0.9 is flagged, one review, and it is harmful. So TP=1\mathrm{TP} = 1, FP=0\mathrm{FP} = 0 and FN=1\mathrm{FN} = 1, precision is 1 and recall is 1/21/2.

The stricter threshold cuts the workload from three reviews to one and misses one of the two harmful cases. Which threshold is better depends on the review capacity and on the cost of a missed harmful event compared with an unnecessary review. The table supplies evidence for that choice but cannot make it, and five cases cannot show that the same rates will hold later.

  1. For the isolation forest of the example, with the reference 9, 10, 10, 11 in every tree and height limit 2, find the expected path lengths and limiting scores of the readings 30 and 10, and compare them with their distance scores. What happens to the reference readings 9 and 11 themselves?
Show the answer

Every split value lies between 9 and 11, so the reading 30 always goes the same way as 14. Its expected path length is 1.5 and its limiting score is 2−9/13≈0.6192^{-9/13} \approx 0.619, exactly that of 14. Its distance score is 20/0.5=202≈28.2820/\sqrt{0.5} = 20\sqrt{2} \approx 28.28, five times that of 14.

The reading 10 always ends in the leaf that holds both reference readings 10. If the first split lies below 10, it goes right into 10, 10, 11 and the second split sends it left. Otherwise it goes left into 9, 10, 10 and the second split sends it right. Either way the leaf sits at depth 2 with m=2m = 2, so the path length is 2+c(2)=32 + c(2) = 3 and the score is

2−3⋅6/13=2−18/13≈0.383.2^{-3 \cdot 6/13} = 2^{-18/13} \approx 0.383 .

Its distance score is 0. The reference readings 9 and 11 follow the same paths as 8 and 14 and also score about 0.619. With such a small reference the forest cannot separate the harmful 14 from the largest normal reading, while the distance score keeps growing with distance.

  1. In one month a detector screens 10,000 readings and flags 40, and review finds that 10 of the flagged readings were harmful. A report states precision 0.25 and recall 1, because no unflagged reading was found to be harmful. Then a uniformly random sample of 200 of the 9,960 unflagged readings is reviewed, and 2 of them are harmful. What was wrong with the reported recall, and what is a better estimate?
Show the answer

The precision 10/40=0.2510/40 = 0.25 is supported, since every flagged reading was reviewed. The recall is not. Nobody had looked at the unflagged readings, so finding no harmful one among them says nothing, and the random sample already shows harmful readings that were not flagged, which rules out recall 1.

The sample suggests that about 2/200=12/200 = 1 percent of the unflagged readings are harmful, about 9,960×0.01=99.69{,}960 \times 0.01 = 99.6 readings. The estimated recall is

1010+99.6≈0.091,\frac{10}{10 + 99.6} \approx 0.091 ,

so the detector may have caught only about one harmful reading in eleven. With just 2 harmful readings in the sample this estimate is very uncertain, and a larger random review of unflagged readings would narrow it. Reviewing only the highest scores can never estimate what the detector missed.

How this lesson connects