---
title: Anomaly detection
heading: Flagging the rare event with a model of normal, and why rare events make precision hard
eyebrow: S14 · Lesson 21 · Anomaly detection
xp: 50
---

::: hook
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.
:::

::: play
- 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.
:::

```sim plot
view: graph
x: p = 0.00001..0.5 log
y: P = 0..1
slider: f = 0.0001..0.1 = 0.01 log
plot: 0.99*p/(0.99*p + f*(1 - p)) | label: precision
readout: precision at 1 in 1000 = 0.99*0.001/(0.99*0.001 + f*0.999)
```

::: 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?

- [ ] 99%
- [ ] 50%
- [x] About 9%
- [ ] About 1%

::: reveal
In 100 000 cases: 100 anomalies, of which 99 are flagged; 99 900 normal cases, of which 999 are falsely flagged. Precision is $99/(99 + 999)$ = 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.
:::
:::

::: nameit
## Modeling normal

Fit a density $p(\mathbf x)$ 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**

$$d^2 = (\mathbf x - \boldsymbol\mu)^T\Sigma^{-1}(\mathbf x - \boldsymbol\mu)$$

which for normal data in $k$ dimensions follows a χ² distribution with $k$ degrees of freedom. A false-alarm rate α corresponds to the χ² quantile: in one dimension, $|z| > 3$ flags 0.27% of normal points; in two dimensions, $d^2 > -2\ln\alpha$ (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) $r$ and false-alarm rate $f$,

$$\text{precision} = \frac{r\pi}{r\pi + f(1 - \pi)}$$

For rare anomalies ($\pi \ll f$), precision is roughly $r\pi/f$: 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 $m$ independent tests at rate $f$, the chance of at least one false alarm is $1 - (1 - f)^m$); and an anomaly isn't necessarily a fault, so alarms feed people or rules that decide.
:::

::: 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?

::: solution
1. **Limits at ±6.** That's ±3σ, with a two-sided tail of 0.27%: one false alarm in 370 readings.
2. **Limits at ±8.** That's ±4σ, with a tail of $6.3 \times 10^{-5}$: one in 16 000.
3. **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 $6.3 \times 10^{-5}$ of them with limits at 50 ± 8.
:::
:::

::: 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.

::: solution
1. **Precision.** With recall r = 0.99, false-alarm rate f = 0.01 and prevalence π = 0.001:
   $$\begin{aligned} P &= \frac{r\pi}{r\pi + f(1 - \pi)} \\ &= \frac{0.00099}{0.00099 + 0.00999} \\ &= 9.0\% \end{aligned}$$
2. **False-alarm rate for 50%.** Precision is 50% when $f(1 - \pi) = r\pi$, so
   $$\begin{aligned} f &= 0.99 \times 0.001/0.999 \\ &= 0.099\% \end{aligned}$$
   The false-alarm rate must equal the prevalence times the recall.
3. **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%.
:::
:::

::: 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?

::: solution
1. **Standardize.** In standardized units the deviations are
   $$(z_1, z_2) = (1.5, -1.0)$$
2. **Mahalanobis distance.** With correlation ρ = 0.8:
   $$\begin{aligned} d^2 &= \frac{z_1^2 - 2\rho z_1z_2 + z_2^2}{1 - \rho^2} \\ &= \frac{2.25 + 2.4 + 1}{0.36} \\ &= 15.7 \end{aligned}$$
3. **Compare the threshold.** That's well above the 9.21 threshold: anomalous.
4. **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: $d^2$ = 15.7, well above the 9.21 threshold, so the reading is anomalous.
:::
:::

::: check
given: k = 2 | 3 | 4 | 5
answer: 2*(1 - 0.5*(1 + erf(k/sqrt(2))))*100
tolerance: 1%

## A Gaussian variable is flagged when it's more than {k} standard deviations from its mean. What percentage of normal readings are flagged?

::: right
Right. The two-sided tail beyond ±{k}σ: {answer}%.
:::

::: misses
- [(1 - 0.5*(1 + erf(k/sqrt(2))))*100] Count both tails.
- [any] Not yet. $2Q(k)$.
:::
:::

::: check
given: r = 0.9 | 0.99; f = 0.002 | 0.01 | 0.05; p = 0.0001 | 0.001 | 0.01
answer: r*p/(r*p + f*(1 - p))*100
tolerance: 0.5%

## A detector with recall {r} and false-alarm rate {f} watches events where a fraction {p} are anomalous. What percentage of its alarms are real?

::: right
Right. $r\pi/(r\pi + f(1 - \pi))$ = {answer}%.
:::

::: misses
- [r*100] That's the recall, the fraction of anomalies caught, not the fraction of alarms that are real.
- [(1 - f)*100] That's the specificity.
- [any] Not yet. Real alarms over all alarms.
:::
:::

::: check
given: a = 0.1 | 1 | 5
answer: -2*ln(a/100)
tolerance: 0.5%

## For two-dimensional Gaussian data, what threshold on the squared Mahalanobis distance gives a {a}% false-alarm rate?

::: right
Right. With two degrees of freedom, $P(d^2 > t) = e^{-t/2}$, so $t = -2\ln\alpha$ = {answer}.
:::

::: misses
- [-2*log(a/100)] Use the natural logarithm.
- [-ln(a/100)] The χ² tail with 2 degrees of freedom is $e^{-t/2}$.
- [any] Not yet. Solve $e^{-t/2} = \alpha$.
:::
:::

::: check
kind: parts
given: z1 = 1 | 1.5 | 2; z2 = -1 | 0.7 | 1.5; r = 0.5 | 0.8

## Two standardized variables with correlation {r} take the values {z1} and {z2}.

::: part
answer: (z1^2 - 2*r*z1*z2 + z2^2)/(1 - r^2)
tolerance: 0.5%

### What is the squared Mahalanobis distance?

::: misses
- [z1^2 + z2^2] That ignores the correlation.
- [any] Not yet. $(z_1^2 - 2\rho z_1z_2 + z_2^2)/(1 - \rho^2)$.
:::
:::

::: part
answer: exp(-(z1^2 - 2*r*z1*z2 + z2^2)/(1 - r^2)/2)*100
tolerance: 1%

### What percentage of normal points lie at least that far out?

::: misses
- [exp(-(z1^2 + z2^2)/2)*100] Use the Mahalanobis distance, which includes the correlation.
- [any] Not yet. $e^{-d^2/2}$ for two dimensions.
:::
:::

::: right
Right. Opposite moves in correlated variables are rarer than either value alone suggests.
:::
:::

::: check
given: f = 0.001 | 0.01; m = 100 | 1000 | 5000
answer: (1 - (1 - f)^m)*100
tolerance: 0.5%

## A system monitors {m} independent variables, each with a false-alarm rate of {f} per check. What percentage of checks raise at least one false alarm?

::: right
Right. $1 - (1 - f)^m$ = {answer}%.
:::

::: misses
- [m*f*100] That approximation fails once $mf$ isn't small.
- [any] Not yet. One minus the chance that none alarms.
:::
:::

::: check
kind: choice

## Why are anomaly detectors usually trained only on normal data?

- [x] Anomalies are rare, varied and often unseen before, so there are too few labeled examples to learn them; modeling normal flags anything that doesn't fit
- [ ] Training on anomalies would make the model anomalous
- [ ] Normal data is always Gaussian
- [ ] Supervised methods can't handle imbalanced data at all

::: right
Right. The next failure may look like nothing in the training set, so the model learns the one thing there's plenty of: normal behavior.
:::

::: misses
- [2] Labeled anomalies help when available; the problem is having them.
- [3] Normal data often isn't Gaussian; richer models of normal are used.
- [4] Supervised methods handle imbalance with care; the deeper issue is unseen anomaly types.
:::
:::

::: check
kind: python
given: rho = 0.5 | 0.8; shift = 2 | 3; seed = 1 | 2

## 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` = {rho}, then 500 anomalies: fresh normal points plus the vector `[shift/2, -shift/2]`, with `shift` = {shift}. 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 $-2\ln 0.01$, and set `far` (false-alarm rate on the normal test set) and `tpr` (detection rate on the anomalies).

```python starter
import numpy as np
far, tpr = 0.0, 1.0
```

```python solution
import numpy as np
rng = np.random.default_rng(seed)
C = np.array([[1, rho], [rho, 1]])
train = rng.multivariate_normal([0, 0], C, 5000)
test = rng.multivariate_normal([0, 0], C, 5000)
anom = rng.multivariate_normal([0, 0], C, 500) + np.array([shift / 2, -shift / 2])
mu = train.mean(axis=0)
Si = np.linalg.inv(np.cov(train.T))
d2 = lambda X: np.einsum('ij,jk,ik->i', X - mu, Si, X - mu)
t = -2 * np.log(0.01)
far = float(np.mean(d2(test) > t))
tpr = float(np.mean(d2(anom) > t))
```

```python tests
import numpy as np
rng = np.random.default_rng(seed)
C = np.array([[1, rho], [rho, 1]])
tr = rng.multivariate_normal([0, 0], C, 5000); te = rng.multivariate_normal([0, 0], C, 5000)
an = rng.multivariate_normal([0, 0], C, 500) + np.array([shift / 2, -shift / 2])
mu = tr.mean(axis=0); Si = np.linalg.inv(np.cov(tr.T))
d = lambda X: np.einsum('ij,jk,ik->i', X - mu, Si, X - mu)
t = -2 * np.log(0.01)
assert abs(far - np.mean(d(te) > t)) < 1e-12 and abs(tpr - np.mean(d(an) > t)) < 1e-12, "Compute both rates with the fitted model."
assert abs(far - 0.01) < 0.005, "The false-alarm rate should be near the 1% design value."
```

::: right
Right. The false-alarm rate lands near 1% as designed, and anomalies that push correlated variables apart are caught at high rates, more so the stronger the correlation.
:::
:::

::: explain
## 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.

::: model
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

::: check
given: r = 0.95 | 0.8; f = 0.002 | 0.02; p = 0.0005 | 0.05
answer: r*p/(r*p + f*(1 - p))*100
tolerance: 0.5%

## What precision does a detector with recall {r} and false-alarm rate {f} reach at prevalence {p}?

::: misses
- [r*100] That's the recall.
- [any] $r\pi/(r\pi + f(1 - \pi))$.
:::
:::

::: check
given: a = 0.1 | 0.5 | 1 | 2 | 5 | 10
answer: -2*ln(a/100)
tolerance: 0.5%

## What $d^2$ threshold gives a {a}% false-alarm rate in two dimensions?

::: misses
- [-ln(a/100)] It's $-2\ln\alpha$.
- [any] $-2\ln\alpha$.
:::
:::
:::
