S14 · Lesson 21 · Anomaly detection
Flagging the rare event with a model of normal, and why rare events make precision hard
A power transformer's dissolved gases drift before it fails; a network flow looks wrong before an intrusion; a bearing's vibration grows before it seizes. Failures are rare, varied and often never seen before, so there are few labeled examples to train a classifier on. Anomaly detection turns the problem around: model what normal looks like, from plenty of normal data, and flag whatever the model finds improbable. Lesson 20's metrics apply with a twist that dominates every real deployment: when anomalies are rare, even an excellent detector's alarms are mostly false.
- The precision of a detector (the fraction of its alarms that are real) against how rare anomalies are, for a detection rate of 99% and a false-alarm rate set by the slider.
- At a prevalence of 1 in 1000 and 1% false alarms, only about 9% of alarms are real. Lowering the false-alarm rate tenfold helps far more than raising the detection rate.
Predict
A detector catches 99% of anomalies and falsely flags 1% of normal cases. If one case in 1000 is anomalous, what fraction of its alarms are real?
In 100 000 cases: 100 anomalies, of which 99 are flagged; 99 900 normal cases, of which 999 are falsely flagged. Precision is = 9%. The false alarms win on sheer numbers. This is the base-rate effect, and it's why anomaly detectors are tuned for very low false-alarm rates and their alarms are reviewed in a second stage.
Name it
Modeling normal
Fit a density to normal data and flag points where it's low. For a Gaussian model with mean μ and covariance Σ, that's a threshold on the Mahalanobis distance
which for normal data in dimensions follows a χ² distribution with degrees of freedom. A false-alarm rate α corresponds to the χ² quantile: in one dimension, flags 0.27% of normal points; in two dimensions, (9.21 for α = 1%).
Other models of normal: PCA, flagging points far from the principal subspace (the residual or Q statistic, as in lesson 40); mixtures of Gaussians (lesson 36); autoencoders, flagging large reconstruction error; and isolation forests, which flag points that random splits isolate quickly.
Thresholds and base rates
With prevalence π, detection rate (recall) and false-alarm rate ,
For rare anomalies (), precision is roughly : the false-alarm rate must be pushed well below the prevalence before alarms are trustworthy. Precision-recall curves, not ROC curves, show this honestly (lesson 20).
Practical issues
Normal drifts with season, load and aging, so models are refit or adapt; multiple monitored variables multiply false alarms (with independent tests at rate , the chance of at least one false alarm is ); and an anomaly isn't necessarily a fault, so alarms feed people or rules that decide.
Worked example
A sensor reading is normal with mean 50 and standard deviation 2. Flagging readings outside 50 ± 6, what fraction of normal readings raise alarms? And outside 50 ± 8?
Show the solution
- Limits at ±6. That's ±3σ, with a two-sided tail of 0.27%: one false alarm in 370 readings.
- Limits at ±8. That's ±4σ, with a tail of : one in 16 000.
- In time. At one reading a second, 3σ gives an alarm every 6 minutes; 4σ one every 4.4 hours.
Answer 0.27% of normal readings raise alarms with limits at 50 ± 6, and of them with limits at 50 ± 8.
Worked example
Find the precision of a detector with 99% recall and 1% false alarms at a prevalence of 0.1%, and the false-alarm rate needed for 50% precision.
Show the solution
- Precision. With recall r = 0.99, false-alarm rate f = 0.01 and prevalence π = 0.001:
- False-alarm rate for 50%. Precision is 50% when , so The false-alarm rate must equal the prevalence times the recall.
- Fewer misses. Halving the miss rate would barely change precision.
Answer the precision is 9.0%, and 50% precision needs a false-alarm rate of 0.099%.
Worked example
Normal operation of a pump has (pressure, flow) with means (5, 20), standard deviations (0.2, 1.0) and correlation 0.8. Is the reading (5.3, 19.0) anomalous at a 1% false-alarm rate?
Show the solution
- Standardize. In standardized units the deviations are
- Mahalanobis distance. With correlation ρ = 0.8:
- Compare the threshold. That's well above the 9.21 threshold: anomalous.
- Why it takes a joint model. Each variable alone is within 1.5σ, but they moved in opposite directions when they normally move together, which only a joint model catches.
Answer yes: = 15.7, well above the 9.21 threshold, so the reading is anomalous.
Check
A Gaussian variable is flagged when it's more than 3 standard deviations from its mean. What percentage of normal readings are flagged?
Check
A detector with recall 0.9 and false-alarm rate 0.002 watches events where a fraction 0.01 are anomalous. What percentage of its alarms are real?
Check
For two-dimensional Gaussian data, what threshold on the squared Mahalanobis distance gives a 1% false-alarm rate?
Check
Two standardized variables with correlation 0.8 take the values 1.5 and −1.
(a)
What is the squared Mahalanobis distance?
(b)
What percentage of normal points lie at least that far out?
Check
A system monitors 100 independent variables, each with a false-alarm rate of 0.001 per check. What percentage of checks raise at least one false alarm?
Check
Why are anomaly detectors usually trained only on normal data?
Check
Build a Gaussian anomaly detector. Generate 5000 normal training points and 5000 normal test points from a 2D Gaussian with unit variances and correlation rho = 0.5, then 500 anomalies: fresh normal points plus the vector [shift/2, -shift/2], with shift = 2. Use rng = numpy.random.default_rng(seed) and rng.multivariate_normal in that order (train, test, anomalies). Fit the mean and covariance on the training set, flag points with squared Mahalanobis distance above , and set far (false-alarm rate on the normal test set) and tpr (detection rate on the anomalies).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Explain why
A utility deploys an anomaly detector on 10 000 smart meters, flagging each meter's daily reading at a 0.5% false-alarm rate, to find the handful of meters being tampered with. Operators soon ignore the alarms. Explain why, and how to fix the design.
With 10 000 meters checked daily at 0.5%, about 50 normal meters raise false alarms every day, while tampering affects perhaps a few meters a year: by the base-rate effect, nearly every alarm is false, so operators learn to ignore them, and the rare true one is missed too. Recall barely matters here; precision is everything. Fixes: lower the false-alarm rate drastically, for example by requiring an anomaly to persist over several days (combining evidence multiplies the false-alarm probabilities down), by modeling each meter's own normal pattern and its seasonal changes instead of one global threshold, and by combining several independent indicators; then send the few remaining alarms to a second-stage check before a person investigates. Measure success with precision at the operating point, not with accuracy or ROC area.
Practice
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.