Repository navigation
Expand file tree
/
Copy pathdensity.qmd
More file actions
850 lines (724 loc) · 39.3 KB
/
Copy pathdensity.qmd
File metadata and controls
850 lines (724 loc) · 39.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
# Density-based methods {#sec-density-methods}
```{r}
#| label: setup7
#| include: false
#| cache: false
source("before-each-chapter.R")
```
Anomalies are observations that are unlikely to have come from the same distribution as the rest of the data.
One method to identify anomalies is to first estimate the probability distribution of the data, and then find observations that are improbable under that distribution.
This is the approach taken by density-based methods, where anomalies are defined as observations with low probability.
Any density-based method of anomaly detection first requires a density estimate at each observation, denoted by $f(\bm{y}_i)$.
This may be an assumed density, or estimated from the data; it may be a parametric function, or a nonparametric estimate; it may be a conditional density or a marginal density.
Wherever it comes from, $f$ is treated as an appropriate probability density function for the data set.
When $\bm{y}_i$ takes values on a discrete space (such as the integers), then $f$ is a probability mass function, but it is still called a "density" for convenience when discussing methods that can apply to both discrete and continuous data.
In many cases, $f(\bm{y}_i)$ is the estimated likelihood of the observation from a given model.
Note that some of the methods discussed in @sec-distance-methods are often called "density-based" methods, including LOF (@sec-lof) and GLOSH (@sec-glosh).
These methods use an *implicit* measure of density, based on the crowdedness of the neighbourhood of each observation.
This chapter discusses only methods that *explicitly* involve a density function.
## Surprisals {#sec-surprisals}
"Surprisal" is a term coined by American engineer Myron @Tribus1961 in the context of information theory.
In the statistical literature it is better known as a **log score**.
But since we are considering anomaly detection, "surprisal" seems a more appropriate word to use here.
The **surprisal** of an observation $\bm{y}_i$ is defined as
$$
s_i = -\log f(\bm{y}_i),
$$ {#eq-surprisal}
measuring the surprise in seeing the observation.
So it is a measure of how surprising (or anomalous) that observation is, given the density $f$.
A large value of $s_i$ indicates that $\bm{y}_i$ is not a likely value, and so is a potential anomaly.
On the other hand, typical values will have low surprisals.
In information theory, the average surprisal is known as the **entropy** of a random variable\ [@Cover2006;@Stone2022], and provides a measure of uncertainty.
Throughout this book, $\log$ denotes the natural logarithm, so surprisals are measured in **nats**; surprisals computed with base-2 logarithms are measured in bits, and one nat is $1/\log 2 \approx 1.44$ bits.
Although the term "surprisal" may not be in common use amongst statisticians and other data scientists, the underlying idea is widely used.
For example, if $f$ is obtained from a model with parameters that need to be estimated from the data, then the sum of the surprisals is equal to minus the log likelihood of the data.
Therefore, finding parameters that minimise the sum of the surprisals is equivalent to maximum likelihood estimation.
Surprisals are also commonly used in forecasting and prediction problems (where they are called log scores) to assess whether an estimated distribution $f$ provides a good description of the future data values $y$\ [@Gneiting2014].
In that context, the data are thought to be a reliable reflection of the underlying processes, and once the data are observed, the surprisal is used to assess how well the estimated distribution $f$ matches what actually happened.
This book uses surprisals in reverse: $f$ is assumed to be a good description of the underlying processes, and the surprisals are then used to identify observations that are unlikely to have come from that distribution.
### Normal distribution
Suppose our observations come from a N(0,1) distribution, and that $f$ denotes the corresponding density function.
Then
$$
s_i = -\log\left( \frac{1}{\sqrt{2\pi}} e^{-y_i^2/2} \right)
= \frac12 y_i^2 + \frac12\log(2\pi).
$$
So the surprisals are simply equal to half the squared observations plus a constant.
This is easily extended to any Normal distribution, showing that surprisals are equal to half the squared *standardised* observations plus a constant.
### $\chi^2$ distribution
For a $\chi^2_k$ distribution, a surprisal is given by
$$
s_i = -\log\left( \frac{y_i^{k/2-1}e^{-y_i/2}}{2^{k/2}\Gamma(k/2)} \right)
= \frac{1}{2} y_i - (k/2 - 1)\log(y_i) + c_k
$$
where $c_k$ is a constant.
### Poisson distribution
Surprisals can also be computed for discrete distributions.
For a Poisson($\lambda$) distribution, a surprisal is given by
$$
s_i = -\log\left( \frac{\lambda^{y_i} e^{-\lambda}}{y_i!} \right)
= \log(y_i!) - y_i\log(\lambda) + \lambda
$$
### Multivariate Normal distribution
The definition of a surprisal also works for multivariate distributions.
For an $m$-dimensional N$(\bm{0}, \bm{\Sigma})$ distribution, a surprisal is given by
$$
s_i
= -\log\left( (2\pi)^{-m/2}|\bm{\Sigma}|^{-1/2} \exp\Big\{-\frac{1}{2}\bm{y}_i^\intercal\bm{\Sigma}^{-1}\bm{y}_i\Big\} \right)
= \frac{1}{2} \bm{y}_i^\intercal\bm{\Sigma}^{-1}\bm{y}_i
+ \frac{m}{2}\log(2\pi) + \frac{1}{2} \log|\bm{\Sigma}|
$$
When $\bm{\Sigma} = \bm{I}$, this is simply the sum of surprisals computed on each of the marginal distributions.
## Surprisal probabilities {#sec-surprisal-probabilities}
The **surprisal probability** of an observation is the probability of observing a value that is at least as surprising as the observation, under the distribution $f$.
This is easier to interpret than the surprisal itself, because it is on the familiar probability scale between 0 and 1.
It also allows us to set a threshold for identifying anomalies in terms of a false positive rate.
Specifically, for an observation $\bm{y}_i$ under the distribution $f$, its surprisal probability is given by
$$
p_i = \int f(\bm{u}) 𝟙(-\log f(\bm{u}) \ge s_i) d\bm{u}
= \int f(\bm{u}) 𝟙(f(\bm{u}) \le f(\bm{y}_i)) d\bm{u},
$$ {#eq-pi-density}
where $𝟙(z)$ is an indicator function taking value 1 when $z$ is true and 0 otherwise.
@fig-density-scores shows the calculation for a $\chi^2_5$ distribution.
```{r}
#| label: fig-density-scores
#| fig-cap: >-
#| A $\chi^2_5$ density function with one observation shown at $y_i$.
#| The shaded area shows where $f(y) < f(y_i)$, corresponding to $p_i$.
#| In this example, $p_i = 0.05$, so the region between the orange shaded areas is a 95% HDR.
#| echo: false
den <- dist_chisq(5)
hdr <- hdr(den, size = 95) |> unlist() %>% `[`(c("lower", "upper"))
falpha <- density(den, at = hdr["lower"])
df <- tibble(
y = seq(0, 15, l = 501),
fy = density(den, at = y)[[1]],
s = -log(fy),
p = surprisals_prob(y, distribution = den)
)
palpha <- 0.1
df |>
ggplot(aes(x = y, y = fy)) +
geom_line() +
labs(x = TeX("$y$"), y = TeX("Probability Density Function: $f(y)$")) +
geom_hline(aes(yintercept = falpha), col = "#D55E00", linetype = "dashed") +
geom_polygon(
fill = "#D55E00",
data = df |>
filter(y >= hdr[2]) |>
bind_rows(
tibble(y = c(hdr[2], hdr[2], max(df$y)), fy = c(0, falpha, 0))
) |>
arrange(fy, y)
) +
geom_polygon(
fill = "#D55E00",
data = df |>
filter(y <= hdr["lower"]) |>
bind_rows(
tibble(y = c(hdr[1], hdr[1], 0), fy = c(0, falpha, 0))
) |>
arrange(fy, desc(y))
) +
scale_x_continuous(
breaks = c(seq(0, 15, by = 5), hdr[2]),
labels = TeX(c(seq(0, 15, by = 5), "$y_i$")),
minor_breaks = NULL
) +
scale_y_continuous(
breaks = c(seq(0, 0.15, by = 0.05), falpha),
labels = TeX(c(seq(0, 0.15, by = 0.05), "$f(y_i)$")),
minor_breaks = NULL
)
```
The `surprisals()` function takes values of the data $\bm{y}_i$ and returns values of $s_i$ (@eq-surprisal), where the assumed density $f$ can be provided as a distribution object from the **`distributional`** package.
The values of $p_i$ in @eq-pi-density can be obtained using `surprisals_prob()`.
```{r}
#| label: surprisals_eg
#| code-fold: false
tibble(
y = -5:5,
s = surprisals(y, distribution = dist_normal()),
p = surprisals_prob(y, distribution = dist_normal())
)
```
The value of $p_i$ is the probability of an observation being at least as anomalous (or surprising) as $\bm{y}_i$ if the observations come from the distribution $f$.
So if we label points as anomalous when $p_i < \alpha$, we will have a false positive rate of $\alpha$.
This approach allows for anomalies to occur anywhere in the distribution, not just in the tails.
For example, anomalies may lie between modes in a multimodal distribution, or in otherwise low-density regions of the distribution.
The surprisal approach converts the problem of working with a potentially complicated distribution into a problem of working with a simple univariate distribution on the surprisal scale, where large values correspond to anomalies.
If $\bm{Y}$ has density $f$, its surprisal $S = -\log f(\bm{Y})$ is a univariate random variable, and @eq-pi-density says that $p_i = \Pr(S \ge s_i)$.
So an anomaly is an observation whose surprisal lies far in the upper tail of the distribution of $S$, which is why extreme value theory is useful for estimating surprisal probabilities (@sec-approximate-surprisal-prob).
### Connection to highest density regions
Surprisal probabilities are related to highest density regions (discussed in @sec-hdr and @sec-mhdr).
If we identify anomalies as observations with $p_i < \alpha$, then the non-anomalous observations will lie in the $100(1 - \alpha)\%$ highest density region, and all the anomalies will lie outside this region.
This is a useful way to visualise the anomalies, by plotting the data with the highest density region superimposed.
Some examples are shown later in this chapter (@fig-ofpot and @fig-ofpot2).
### Connection to $z$-scores
If $f$ is the Normal distribution $\text{N}(\mu, \sigma^2)$, then the points of lowest density are those furthest from $\mu$.
In fact, $p_i = 2[1 - \Phi(|y_i - \mu|/\sigma)]$, where $\Phi$ is the standard Normal distribution function.
Therefore, identifying anomalies as observations with $p_i < \alpha$ is equivalent to a $z$-score test (@sec-zscores) with the threshold set to the $(1 - \alpha/2)$ quantile of the standard Normal distribution.
This link can be extended to any symmetric unimodal distribution.
If $f$ is a symmetric unimodal distribution centred at $c$, then the most anomalous observations will be those with the largest absolute distance from $c$.
If $F$ is the distribution function corresponding to $f$, then $p_i = 2[1 - F(c + |y_i - c|)]$.
## Approximate surprisal probabilities {#sec-approximate-surprisal-prob}
If we do not know what the distribution of the data should be, or if we think our assumed distribution is incorrect for some reason, there are some ways to find approximate surprisal probabilities that can still be accurate even when the assumed distribution is wrong.
### Approximate GPD surprisal probabilities
Let $f^*$ denote the assumed (and possibly incorrect) density function.
For example, it might be a poor estimate of the true density.
Using this assumed density, we can compute the surprisals, $s_i = -\log f^*(\bm{y}_i)$.
Then we can fit a Generalised Pareto Distribution (GPD) to the largest surprisals using the POT approach discussed in @sec-evt.
This can work even when $f^*$ is incorrect or poorly estimated.
The POT result in @sec-evt explains why: for almost any continuous distribution, the values above a high threshold approximately follow a GPD.
Here the GPD is fitted to the surprisals, not to the data, so the result needs to hold only for the surprisals.
Using the wrong density $f^*$ changes the surprisal values, but in most cases the largest surprisals still follow a GPD.
What $f^*$ and the data affect is the shape parameter $\xi$ in @eq-POT, which describes how quickly the upper tail of the surprisals dies away.
For example, suppose $f^*$ is the N(0,1) density, so that $s_i = \frac12 y_i^2 + \frac12\log(2\pi)$ (@sec-surprisals).
Then the tail of the surprisals depends on how large $y_i^2$ can get:
- $\xi < 0$ if the data are Uniform on $[-1, 1]$, because the surprisals can be no larger than $\frac12 + \frac12\log(2\pi)$.
- $\xi = 0$ if the data are N(0,1), because $y_i^2$ has a $\chi^2_1$ distribution, whose tail decays exponentially.
- $\xi > 0$ if the data are $\text{t}_4$, because occasional very large observations give very large surprisals.
The GPD includes all three cases, and $\xi$ is estimated from the largest surprisals, so we don't need to know in advance which case applies.
In effect, the estimated probabilities depend on where each surprisal lies among the others, so $f^*$ only needs to put the most extreme observations in roughly the right order.
@surprisals give the precise conditions under which this works, and show that it leads to good estimates of the surprisal probabilities for the largest surprisals, which are the ones that matter for anomaly detection.
Let $\beta$ denote the tail probability used in the GPD threshold, and let $u$ denote the $(1 - \beta)$ sample quantile of the surprisal values.
For example, with the common choice $\beta = 0.1$, $u$ is the $90^{\text{th}}$ percentile of the $s_i$ values.
We fit a GPD to the surprisals above $u$, and then compute the approximate surprisal probability of each observation with $s_i > u$ by
$$
\hat{p}_i = \beta\int_{s_i}^\infty \hat g(s) ds,
$$ {#eq-pi-gpd}
where $\hat g$ denotes the estimated GPD density of the surprisals above $u$ (that is, the GPD fitted to the exceedances $s_i - u$, shifted to start at $u$).
This approximation only gives us surprisal probabilities for the surprisals above the threshold $u$.
For any $s_i \le u$, all we can say is that $p_i$ is at least about $\beta$, and `surprisals_prob()` returns $\hat{p}_i = \beta$ for these observations.
@fig-gpd-approx illustrates the calculation, using surprisals computed from 1000 N(0,1) observations with an incorrect $\text{t}_4$ density.
The top panel shows all the surprisals, with the largest 10% (those above $u$) highlighted.
The bottom panel shows only these largest surprisals, along with the fitted GPD density multiplied by $\beta$.
The multiplication is needed because these surprisals are only 10% of the total, so the bars in the bottom panel have total area $\beta = 0.1$ rather than 1.
The shaded area to the right of $s_i$ is the estimated surprisal probability $\hat{p}_i$.
```{r}
#| label: fig-gpd-approx
#| echo: false
#| fig-asp: 0.9
#| fig-cap: >-
#| Approximate GPD surprisal probabilities, with $\beta = 0.1$.
#| Top: histogram of the surprisals of 1000 N(0,1) observations, computed using a $\text{t}_4$ density.
#| The largest 10% of surprisals, above the threshold $u$, are shown in orange.
#| Bottom: the surprisals above $u$, along with the fitted GPD density multiplied by $\beta$.
#| The shaded area to the right of the surprisal $s_i$ is the estimated surprisal probability $\hat{p}_i$.
gpd_s <- surprisals(n01$v1, distribution = dist_student_t(4))
gpd_beta <- 0.1
# Threshold and GPD fit computed in the same way as surprisals_prob()
gpd_u <- unname(quantile(gpd_s, prob = 1 - gpd_beta, type = 8))
# (fitted to the excesses divided by their median, then rescaled)
gpd_excess <- gpd_s[gpd_s > gpd_u] - gpd_u
gpd_c <- median(gpd_excess)
gpd_fit <- evd::fpot(gpd_excess / gpd_c, threshold = 0, std.err = FALSE)$estimate
gpd_fit["scale"] <- gpd_fit["scale"] * gpd_c
# Observation with the 10th largest surprisal
gpd_si <- sort(gpd_s, decreasing = TRUE)[10]
gpd_pi <- gpd_beta *
evd::pgpd(
gpd_si,
loc = gpd_u,
scale = gpd_fit["scale"],
shape = gpd_fit["shape"],
lower.tail = FALSE
)
# beta times the GPD density (which is zero at u itself, so start just above it)
gpd_den <- tibble(
s = sort(c(seq(gpd_u + 1e-6, max(gpd_s) + 0.2, length.out = 301), gpd_si)),
density = gpd_beta *
evd::dgpd(
s,
loc = gpd_u,
scale = gpd_fit["scale"],
shape = gpd_fit["shape"]
)
)
binwidth <- 0.1
gpd_hist <- function(data) {
geom_histogram(
data = data,
aes(
x = s,
y = after_stat(count) / (length(gpd_s) * binwidth),
fill = s > gpd_u
),
binwidth = binwidth,
boundary = gpd_u
)
}
# Orange for the largest surprisals, in both panels
gpd_fill <- scale_fill_manual(
values = c(`FALSE` = "grey70", `TRUE` = "#D55E00"),
guide = "none"
)
# Label u and s_i on the x-axis, along with some round numbers
x_axis <- function(breaks, labels) {
scale_x_continuous(
breaks = breaks,
labels = TeX(labels),
minor_breaks = NULL
)
}
p_all <- ggplot() +
gpd_hist(tibble(s = gpd_s)) +
geom_vline(xintercept = gpd_u, linetype = "dashed") +
x_axis(c(1:5, gpd_u), c(1:5, "$u$")) +
gpd_fill +
labs(x = "Surprisal", y = "Density", title = "All surprisals")
p_tail <- ggplot() +
gpd_hist(tibble(s = gpd_s[gpd_s > gpd_u])) +
geom_area(
data = gpd_den |> filter(s >= gpd_si),
aes(x = s, y = density),
fill = "#0072B2",
alpha = 0.5
) +
geom_line(data = gpd_den, aes(x = s, y = density), colour = "#0072B2") +
geom_vline(xintercept = gpd_u, linetype = "dashed") +
annotate(
"segment",
x = gpd_si,
xend = gpd_si,
y = 0,
yend = max(gpd_den$density[gpd_den$s == gpd_si]),
colour = "#0072B2"
) +
x_axis(c(3:5, gpd_u, gpd_si), c(3:5, "$u$", "$s_i$")) +
annotate(
"text",
x = gpd_si + 0.25,
y = 2.5 * gpd_pi,
label = TeX("$\\hat{p}_i$", output = "character"),
parse = TRUE,
hjust = 0,
colour = "#0072B2"
) +
annotate(
"text",
x = gpd_u + 0.15,
y = max(gpd_den$density),
label = TeX("$\\beta \\hat{g}(s)$", output = "character"),
parse = TRUE,
hjust = 0,
colour = "#0072B2"
) +
gpd_fill +
labs(x = "Surprisal", y = "Density", title = "Surprisals above the threshold")
patchwork::wrap_plots(p_all, p_tail, ncol = 1)
```
```{r}
#| label: check_gpd_approx
#| include: false
#| dependson: fig-gpd-approx
# The figure's GPD calculation must match surprisals_prob()
stopifnot(isTRUE(all.equal(
unname(gpd_pi),
surprisals_prob(
n01$v1,
distribution = dist_student_t(4),
approximation = "gpd"
)[gpd_s == gpd_si]
)))
```
The approach does require a relatively large number of surprisals to be available, in order to adequately estimate the GPD from the largest $100\beta$% of them.
So we would typically need at least a few hundred observations to start with.
The `surprisals_prob()` function uses this GPD approximation (@eq-pi-gpd) when `approximation = "gpd"`.
The argument `threshold_probability` is used to specify $\beta$, with the default value of 0.1.
### Approximate rank-based surprisal probabilities
An alternative approach that does not require a GPD is to estimate $p_i$ as the proportion of observations with surprisal values at least as large as $s_i$.
That is, $\hat{p}_i = (n - \text{rank}(s_i) + 1)/n$, where $\text{rank}(s_i)$ is the rank of $s_i$ among the $s_1,\dots,s_n$ values, with the smallest value having rank 1, and tied values all given the smallest of their ranks.
For large $n$, this provides a quick and convenient estimate of $p_i$.
@surprisals show that this approach works well when the ordering of the largest surprisal values under $f$ and $f^*$ is similar, which should be the case when $f^*$ is a reasonable approximation to $f$.
The `approximation` argument of `surprisals_prob()` can be set to `"rank"` to use these rank-based surprisal probabilities.
### Example: Standard Normal values
For example, consider the 1000 values contained in the first column of `n01`.
These were generated from a standard Normal distribution.
We can use `surprisals_prob()` to identify anomalies with surprisal probability less than 1%.
This is equivalent to $z$-scores greater than `r sprintf("%.3f", qnorm(1-0.01/2))` in absolute value.
We will use all three methods described above, first using the correct density in computing the surprisals, and then repeating the calculation using an incorrect density.
For the incorrect density, we will use a $\text{t}_4$ distribution, which has much longer tails than the true N(0,1) distribution.
```{r}
#| label: surprisal_prob
#| code-fold: false
# Compute surprisal probabilities of v1 assuming a standard Normal distribution
# and a t4 distribution
norm_prob <- tibble(
y = n01$v1,
p = surprisals_prob(y, distribution = dist_normal()),
p_gpd = surprisals_prob(
y,
distribution = dist_normal(),
approximation = "gpd"
),
p_emp = surprisals_prob(
y,
distribution = dist_normal(),
approximation = "rank"
),
pt = surprisals_prob(y, distribution = dist_student_t(4)),
pt_gpd = surprisals_prob(
y,
distribution = dist_student_t(4),
approximation = "gpd"
),
pt_emp = surprisals_prob(
y,
distribution = dist_student_t(4),
approximation = "rank"
)
)
norm_prob |> arrange(p)
```
The true values are in column `p`, as this uses the correct distribution applied to the correct surprisals.
Notice that `p_gpd` and `p_emp` are both relatively accurate: the GPD and rank approximations work.
The last three columns show the probabilities based on surprisals using the incorrect distribution.
Here, `pt` is very inaccurate, with probabilities much larger than they should be, especially in the extreme tails.
This is because the $\text{t}_4$ distribution has much heavier tails than the true N(0,1) distribution, so the probability of observations more extreme than those observed is much larger than it should be.
But `pt_gpd` and `pt_emp` are both reasonable estimates, despite being based on an incorrect distribution for computing the surprisals.
In fact, `p_emp` and `pt_emp` are identical, because the ordering of the surprisals is unchanged despite the incorrect distribution being used.
The various estimates are displayed in @fig-surprisal_prob for values of $y$ greater than 2.5, showing that the estimates (other than `pt`) are close to the true values in the tail, where we need them for anomaly detection.
The rank estimates can never be smaller than $1/n$, so they overstate the probability of the most extreme observation, whereas the GPD estimates are not bounded below in this way.
```{r}
#| label: fig-surprisal_prob
#| dependson: surprisal_prob
#| fig-cap: Surprisal probabilities for observations with $y > 2.5$, estimated using the correct N(0,1) distribution and using an incorrect $\text{t}_4$ distribution.
#| The GPD and rank estimates of surprisal probabilities are still accurate, even when the wrong distribution is used to compute the surprisal values.
norm_prob |>
filter(y > 2.5) |>
tidyr::pivot_longer(
p:pt_emp,
names_to = "Estimate",
values_to = "Probability"
) |>
ggplot(aes(x = y, y = Probability, col = Estimate)) +
geom_line()
```
### Example: $\text{t}_4$ values
In the previous example, the incorrect density had heavier tails than the data, so the errors made observations look less anomalous than they really were.
The opposite mistake is more serious: if the assumed density has lighter tails than the data, then ordinary observations will look anomalous.
To see this, consider 1000 values generated from a $\text{t}_4$ distribution, and compute their surprisals using an N(0,1) density.
```{r}
#| label: surprisal_prob_t4
#| code-fold: false
set.seed(1)
t4_prob <- tibble(
y = rt(1000, df = 4),
p = surprisals_prob(y, distribution = dist_student_t(4)),
pn = surprisals_prob(y, distribution = dist_normal()),
pn_gpd = surprisals_prob(
y,
distribution = dist_normal(),
approximation = "gpd"
),
pn_emp = surprisals_prob(
y,
distribution = dist_normal(),
approximation = "rank"
)
)
t4_prob |> arrange(p)
```
```{r}
#| label: check_t4_prob
#| include: false
#| dependson: surprisal_prob_t4
# The prose says pn flags many more observations than the true p,
# while the GPD and rank estimates flag about as many
n_flag <- colSums(select(t4_prob, -y) < 0.01)
stopifnot(
n_flag["pn"] > 3 * n_flag["p"],
abs(n_flag["pn_gpd"] - n_flag["p"]) <= 6,
abs(n_flag["pn_emp"] - n_flag["p"]) <= 6
)
```
Now the true values are in column `p`, computed using the $\text{t}_4$ density.
The probabilities in `pn`, computed using the N(0,1) density, are far too small.
Using a threshold of 0.01, `pn` would flag `r n_flag["pn"]` observations as anomalies, compared to `r n_flag["p"]` using the true probabilities.
The GPD and rank estimates are much closer to the true values, flagging `r n_flag["pn_gpd"]` and `r n_flag["pn_emp"]` observations respectively.
@fig-surprisal_prob_t4 shows the estimates for values of $y$ greater than 2.5.
```{r}
#| label: fig-surprisal_prob_t4
#| dependson: surprisal_prob_t4
#| fig-cap: Surprisal probabilities for $\text{t}_4$ observations with $y > 2.5$, estimated using the correct $\text{t}_4$ distribution and using an incorrect N(0,1) distribution.
#| The probabilities computed directly from the N(0,1) distribution are far too small, but the GPD and rank estimates are much closer to the true values.
t4_prob |>
filter(y > 2.5) |>
tidyr::pivot_longer(
p:pn_emp,
names_to = "Estimate",
values_to = "Probability"
) |>
ggplot(aes(x = y, y = Probability, col = Estimate)) +
geom_line()
```
Even when we don't know the distribution of the data, we can use some incorrect assumed distribution to compute the surprisals, and then apply either a GPD or the rank approximation to obtain good estimates of the surprisal probabilities.
## KDE surprisals {#sec-kdesurprisals}
Suppose we estimate $f$ using a kernel density estimate.
In fact, when the `surprisals()` or `surprisals_prob()` functions are applied to data without specifying a probability distribution, a kernel density estimate of the data is used by default.
The kernel density estimate at each observation is (@eq-mkde)
$$
f_i = \hat{f}(\bm{y}_i) = \frac{1}{n} \sum_{j=1}^n K_{\bm{H}}(\bm{y}_i - \bm{y}_j),
$$ {#eq-kdescores}
and so the **KDE surprisal** at each observation is defined as
$$
s_i = -\log(f_i).
$$
The largest possible surprisal occurs when an observation has no other observations nearby.
Then $f_i \approx K_{\bm{H}}(\bm{0})/n$ because $K_{\bm{H}}(\bm{y}_i - \bm{y}_j) \approx 0$ when $\|\bm{y}_i - \bm{y}_j\|$ is large.
So the largest possible KDE surprisal, when using a Gaussian kernel, is
$$
-\log(K_{\bm{H}}(\bm{0})/n) = \log(n) + \frac{m}{2}\log(2\pi)
+ \frac{1}{2}\log|\bm{H}|,
$$
where $\bm{H}$ is the bandwidth matrix.
For univariate data, when $m = 1$ and $\bm{H} = h^2$, this simplifies to
$$
-\log(K_h(0)/n) = \log(nh\sqrt{2\pi}).
$$
Identifying anomalies using KDE surprisals is related to the local outlier factor method (@sec-lof).
However, the local outlier factor method is based on the ratio of the average density at the neighbours of a point to the density at the point itself, while the KDE surprisal method is based on the density at a point alone.
This means that the KDE surprisal method is more likely to identify points in low-density regions as anomalies, even when their neighbours are equally sparse.
## LOO surprisals {#sec-loo-surprisals}
If the density $f$ has been estimated from the data (whether from a parametric model or a nonparametric method such as KDE), then there is a problem of circular reasoning.
Any genuine anomalies may affect the estimated density, and then they may not appear to be anomalies.
Therefore, it is sometimes useful to consider the leave-one-out (LOO) estimate given by $f_{-i}$.
That is, $f_{-i}$ is the density estimate using all observations other than the $i$th observation.
Then an unusual observation can't influence the density estimate, giving us a better measure of how anomalous it really is.
In this case, the associated surprisal is called a **LOO surprisal**, given by $s_{-i} = -\log f_{-i}(\bm{y}_i)$.
### LOO KDE surprisals
For KDE surprisals, the contribution of the $i$th point to the kernel density estimate at that point is $K_{\bm{H}}(\bm{0})/n$.
Therefore, the leave-one-out kernel density estimate is given by
$$
f_{-i} = \left[ nf_i - K_{\bm{H}}(\bm{0}) \right]/(n - 1),
$$ {#eq-loo-kde}
where $f_i$ is the kernel density estimate from @eq-kdescores using all data, so that the leave-one-out KDE surprisal is $s_{-i} = -\log (f_{-i})$.
Thus, we can compute the leave-one-out KDE surprisals without needing to re-estimate the density many times.
The largest possible LOO KDE surprisal is infinite, occurring when there are no observations nearby, so that $nf_i = K_{\bm{H}}(\bm{0})$ (to numerical precision) and hence $f_{-i} = 0$ in @eq-loo-kde.
### The lookout algorithm
The **lookout** algorithm (standing for Leave-One-Out Kernel density estimates for OUTlier detection) was proposed by @lookout, and later modified by @lookout2.
It computes surprisal probabilities using a GPD approximation applied to the LOO KDE surprisals, where the bandwidth matrix is the lookout bandwidth (@eq-lookoutH).
These probabilities can be calculated using the `surprisals_prob()` function with `loo = TRUE`, `approximation = "gpd"`, and `method = "lookout"`.
## Example: Old Faithful eruption durations {#sec-oldfaithful-density}
Let's apply the KDE surprisals method to the Old Faithful eruptions contained in the `oldfaithful` data set.
We will use the LOO KDE surprisal probabilities to identify anomalies in the eruption durations (but using the default robust normal reference bandwidth, rather than the lookout bandwidth).
```{r}
#| label: ofscores-kde
#| code-fold: false
of_surprisals <- oldfaithful |>
mutate(
loo_kde_surprisal = surprisals(duration, loo = TRUE),
prob = surprisals_prob(duration, loo = TRUE, approximation = "gpd"),
)
of_surprisals |> arrange(desc(loo_kde_surprisal))
```
The three largest LOO surprisals correspond to the three erroneous short durations.
The `prob` column contains the associated surprisal probabilities.
If we omit the three extreme values, we obtain different results.
```{r}
#| label: ofscores2
#| code-fold: false
of_surprisals <- oldfaithful |>
filter(duration > 60) |>
mutate(
loo_kde_surprisal = surprisals(duration, loo = TRUE),
prob = surprisals_prob(duration, loo = TRUE, approximation = "gpd"),
)
of_surprisals |> arrange(desc(loo_kde_surprisal))
```
```{r}
#| label: ofscores2b
#| include: false
#| dependson: ofscores2
no <- of_surprisals |> filter(prob < 0.005) |> NROW()
no_above_300 <- of_surprisals |> filter(duration > 300, prob < 0.005) |> NROW()
no_below_90 <- of_surprisals |> filter(duration < 90, prob < 0.005) |> NROW()
no_between_155_and_165 <- of_surprisals |>
filter(duration >= 155, duration <= 165, prob < 0.005) |>
NROW()
stopifnot(no == no_above_300 + no_below_90 + no_between_155_and_165)
```
Now there are `r english::words(no)` points with probabilities less than 0.005: `r english::words(no_above_300)` with durations above 300 seconds, `r english::words(no_below_90)` below 90 seconds, and the rest between 155 and 165 seconds.
@fig-ofpot shows an HDR boxplot of the data, with those points with surprisal probabilities less than 0.005 highlighted in black.
```{r}
#| label: fig-ofpot
#| fig-cap: "HDR boxplot of the Old Faithful eruption durations, with the surprisal anomalies highlighted in black."
#| fig-asp: 0.2
#| code-fold: false
oldfaithful |>
filter(duration > 60) |>
gg_hdrboxplot(duration)
```
The same algorithm is easily applied in two dimensions.
For example, we can consider the bivariate distribution of eruption duration and waiting time.
```{r}
#| label: ofscores-bivariate
#| code-fold: false
of <- oldfaithful |>
select(duration, waiting)
of |>
mutate(
loo_scores = surprisals(of, loo = TRUE),
prob = surprisals_prob(of, loo = TRUE, approximation = "gpd")
) |>
filter(prob < 0.005) |>
arrange(prob, duration)
```
Now, `r english::words(sum(surprisals_prob(of, loo = TRUE, approximation = "gpd") < 0.005))` anomalies are identified, with `r english::words(sum(surprisals(of, loo = TRUE) == Inf))` of them having infinite LOO surprisals.
We can visualise them in an HDR scatterplot, shown in @fig-ofpot2.
```{r}
#| label: fig-ofpot2
#| code-fold: false
#| fig-cap: "HDR scatterplot of the Old Faithful eruption durations and waiting times, with the surprisal anomalies highlighted in black."
oldfaithful |>
gg_hdrboxplot(duration, waiting, show_points = TRUE)
```
## Gaussian mixture model surprisal probabilities {#sec-gmm-surprisal}
A Gaussian mixture model (GMM) is a flexible parametric model for the joint distribution of the data, which can capture multimodality and other complex features.
It comprises a weighted sum of multivariate Normal distributions, each with its own mean vector and covariance matrix.
That is,
$$
f(\bm{y}) = \sum_{k=1}^K \pi_k \phi(\bm{y}; \bm{\mu}_k, \bm{\Sigma}_k),
$$
where $K$ is the number of components, the weights $\pi_k \ge 0$ sum to 1, and $\phi(\bm{y}; \bm{\mu}_k, \bm{\Sigma}_k)$ is the multivariate Normal density with mean $\bm{\mu}_k$ and covariance matrix $\bm{\Sigma}_k$.
In fact, a KDE with a Gaussian kernel can be considered a Gaussian mixture model with a large number of equally-weighted components, each centred at an observation and with a common covariance matrix given by the bandwidth matrix.
However, we can also fit a GMM with a smaller number of components, which may provide a more parsimonious model for the data.
The **`mclust`** package provides a convenient way to fit GMMs to data.
```{r}
#| label: gmm1
#| message: false
#| code-fold: false
library(mclust)
set.seed(2)
gmm <- oldfaithful |>
select(duration, waiting) |>
Mclust() |>
dist_mclust()
gmm
```
```{r}
#| label: gmm2
#| echo: false
#| dependson: gmm1
gmm_par <- parameters(gmm)
gmm_wt <- gmm_par$w[[1]]
gmm_nc <- length(gmm_wt)
gmm_par <- lapply(gmm_par[[1]][[1]], parameters)
mu <- lapply(gmm_par, \(x) x$mu[[1]])
sigma <- lapply(gmm_par, \(x) x$sigma[[1]])
gmm_dist <- lapply(seq_len(gmm_nc), function(i) {
distributional::dist_multivariate_normal(list(mu[[i]]), list(sigma[[i]]))
})
gmm_dist <- do.call(c, gmm_dist)
# Reorder by weight
j <- order(gmm_wt, decreasing = TRUE)
mu <- mu[j]
sigma <- sigma[j]
gmm_dist <- gmm_dist[j]
gmm_wt <- gmm_wt[j]
stopifnot(length(j) == 3L)
```
The algorithm initialises by clustering a random subset of the data (because there are more than 2000 observations), so different results may be obtained on different runs.
The `set.seed()` function is used here to ensure reproducibility.
We have estimated a `r gmm_nc`-component GMM for the Old Faithful data, with means
$$
\bm{\mu}_1 = \begin{bmatrix} `r sprintf("%.1f", mu[[1]][1])` \\ `r sprintf("%.1f", mu[[1]][2])` \end{bmatrix}, \quad
\bm{\mu}_2 = \begin{bmatrix} `r sprintf("%.1f", mu[[2]][1])` \\ `r sprintf("%.1f", mu[[2]][2])` \end{bmatrix}, \quad\text{and}\quad
\bm{\mu}_3 = \begin{bmatrix} `r sprintf("%.1f", mu[[3]][1])` \\ `r sprintf("%.1f", mu[[3]][2])` \end{bmatrix},
$$
covariances
$$
\bm{\Sigma}_1 =
\begin{bmatrix}
`r sprintf("%.1f", sigma[[1]][1,1])` & `r sprintf("%.1f", sigma[[1]][1,2])` \\
`r sprintf("%.1f", sigma[[1]][2,1])` & `r sprintf("%.1f", sigma[[1]][2,2])`
\end{bmatrix}
, \quad \bm{\Sigma}_2 =
\begin{bmatrix}
`r sprintf("%.1f", sigma[[2]][1,1])` & `r sprintf("%.1f", sigma[[2]][1,2])` \\
`r sprintf("%.1f", sigma[[2]][2,1])` & `r sprintf("%.1f", sigma[[2]][2,2])`
\end{bmatrix}
, \quad\text{and}\quad \bm{\Sigma}_3 =
\begin{bmatrix}
`r sprintf("%.1f", sigma[[3]][1,1])` & `r sprintf("%.1f", sigma[[3]][1,2])` \\
`r sprintf("%.1f", sigma[[3]][2,1])` & `r sprintf("%.1f", sigma[[3]][2,2])`
\end{bmatrix}
,
$$
and weights $`r sprintf("%.3f", gmm_wt[1])`$, $`r sprintf("%.3f", gmm_wt[2])`$, and $`r sprintf("%.3f", gmm_wt[3])`$, respectively.
The component multivariate Normal densities are shown in @fig-gmm-components.
```{r}
#| label: fig-gmm-components
#| fig-cap: "The estimated Gaussian mixture model for the Old Faithful data, showing the different components."
#| echo: false
#| dependson: gmm2
cols <- discrete_colours[1:3]
w <- sprintf("%.2f", gmm_wt)
p <- ggplot() +
geom_point(data = oldfaithful, aes(x = duration, y = waiting), alpha = 0.1)
for (i in seq_along(gmm_dist)) {
p <- p +
geom_contour(
data = density_df(gmm_dist[i]) |> mutate(weight = w[i]),
aes(x = x, y = y, z = density, colour = weight),
breaks = hdr_table(gmm_dist[i], prob = seq(9) / 10)$density
)
}
p +
labs(x = "Duration", y = "Waiting time") +
scale_colour_manual(name = "Weight", values = cols, breaks = w)
```
When the components are added together, we get the density shown in @fig-gmm-density.
```{r}
#| label: fig-gmm-density
#| dependson: gmm1
#| fig-cap: "The estimated density for the Old Faithful data based on a Gaussian mixture model with the three components shown in @fig-gmm-components."
#| code-fold: false
gmm |>
gg_density() +
geom_point(data = oldfaithful, aes(x = duration, y = waiting), alpha = 0.1) +
labs(x = "Duration", y = "Waiting time")
```
We can compute the density at each observation under this fitted model, and then compute surprisal probabilities based on that density.
```{r}
#| label: gmm-surprisals
#| dependson: gmm1
#| code-fold: false
of <- oldfaithful |>
mutate(
gmm_prob = surprisals_prob(
pick(duration, waiting),
distribution = gmm,
approximation = "gpd"
)
) |>
arrange(gmm_prob)
of
```
```{r}
#| label: fig-gmm-surprisals
#| dependson: gmm-surprisals
#| fig-cap: "Observations with surprisal probability less than 0.005 under the Gaussian mixture model."
of |>
ggplot(aes(x = duration, y = waiting, colour = gmm_prob < 0.005)) +
geom_point() +
labs(
x = "Duration",
y = "Waiting time",
colour = "Surprisal probability < 0.005"
) +
scale_colour_manual(values = c("FALSE" = "grey70", "TRUE" = "#D55E00"))
```
As shown in @fig-gmm-surprisals, the model has highlighted the `r english::words(sum(of$gmm_prob < 0.005))` points that do not appear to belong to the two main clusters of observations.
## Summary {#sec-density-summary}
Density-based methods define an anomaly as an observation that is improbable under the distribution of the data.
The surprisal, $s_i = -\log f(\bm{y}_i)$, measures how improbable each observation is, and the surprisal probability puts this on a probability scale, as the chance of seeing an observation at least as surprising.
Flagging observations with surprisal probability below $\alpha$ then gives a false positive rate of $\alpha$, and the non-anomalous observations are those lying in the $100(1 - \alpha)$% highest density region.
Unlike $z$-scores, this allows anomalies to lie anywhere in the distribution, including between the modes of a multimodal distribution, although for Normal data the two approaches are equivalent.
The main practical difficulty is that we rarely know $f$.
Two ideas make the approach work in practice.
First, the surprisal probabilities of the most extreme observations can be estimated accurately even when the density used to compute the surprisals is wrong, by fitting a Generalised Pareto Distribution to the largest surprisals, or by using their ranks.
Second, when the density is estimated from the data, using leave-one-out estimates stops each anomaly from inflating its own density estimate; for kernel density estimates, the leave-one-out values can be computed without re-estimating the density.
The density estimate can be nonparametric, such as a kernel density estimate, which makes few assumptions but requires a bandwidth, or parametric, such as a Gaussian mixture model, which is more parsimonious and can still capture multimodality.
The surprisal approach is used throughout the rest of the book, with the density replaced by a conditional distribution when we want to find observations that are unusual given other information, such as predictor values in @sec-regression-methods or the past history of a time series in @sec-timeseries.