Repository navigation
Expand file tree
/
Copy pathmultivariate.qmd
More file actions
1220 lines (1020 loc) · 63.5 KB
/
Copy pathmultivariate.qmd
File metadata and controls
1220 lines (1020 loc) · 63.5 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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Multivariate probability distributions {#sec-multivariate}
```{r}
#| label: setup3
#| include: false
#| cache: false
source("before-each-chapter.R")
# Set up for using rgl
options(rgl.useNULL = TRUE)
rgl::setupKnitr()
source("delta_neighbourhood.R")
```
While this book covers anomaly detection in univariate data, most of the methods it discusses are for multivariate data.
We will therefore need to understand some basic concepts of multivariate probability distributions.
## Hiding in high-dimensional space {#sec-hiding}
When first thinking about multivariate probability distributions, it can take some time to develop an intuition for how they behave.
One way to start developing this intuition is to plot data with increasing numbers of dimensions, starting with the univariate case.
Consider the `n01` data set, which contains 10 variables, each from independent standard Normal distributions.
Only the first three variables are used here and, to make the example more interesting, they are replaced by their cumulative sums.
A couple of anomalies are also added.
We will then see if we can find them using some data visualisations.
```{r}
#| label: demo_data
#| code-fold: false
# Construct example data set
df <- n01 |>
transmute(
V1 = v1,
V2 = v1 + v2,
V3 = v1 + v2 + v3
)
# Add anomalies
df[999, ] <- tibble(V1 = -2, V2 = 3.4, V3 = 1.3)
df[1000, ] <- tibble(V1 = 1.2, V2 = -1.8, V3 = 1.1)
df$anomaly <- c(rep(FALSE, 998), TRUE, TRUE)
```
First, we can do a strip plot of each variable to visualise the data from a univariate perspective (@fig-demo_strip).
```{r}
#| label: fig-demo_strip
#| dependson: demo_data
#| fig-asp: 0.3
#| fig-cap: Strip plots of each of the three variables, with anomalies shown in orange.
df |>
tidyr::pivot_longer(V1:V3) |>
ggplot(aes(x = value, y = 0, col = anomaly)) +
geom_jitter(width = 0) +
facet_grid(name ~ .) +
scale_y_discrete() +
labs(x = "", y = "") +
scale_colour_manual(values = c("#999999", "#D55E00"))
```
The only obvious feature of these graphs is that the variance increases in successive panels.
This is because the variance of the sum of independent random variables is the sum of their variances.
The two anomalies are plotted in each panel, but they are not obviously different from the other observations.
Now we will plot pairwise scatterplots of the three variables, giving the bivariate perspective (@fig-demo-pairs).
```{r}
#| label: fig-demo-pairs
#| dependson: demo_data
#| fig-cap: Pairwise scatterplots of the three variables, with anomalies shown in orange.
#| warning: false
#| message: false
GGally::ggpairs(
df[, 1:3],
lower = list(
continuous = GGally::wrap("points"),
mapping = aes(colour = df$anomaly)
)
) +
scale_colour_manual(values = c("#999999", "#D55E00")) +
theme(panel.spacing = unit(1, "lines"))
```
This shows that there are positive relationships between the variables, with the strongest between `V2` and `V3`.
One of the anomalies is now clearly separate from the other observations in the plot of `V2` vs `V1` (the top left scatterplot).
For this anomaly, the value of `V1` is -2, which is not particularly unusual compared to the other observations.
Similarly, the value of `V2` is 3.4, which is also not particularly unusual.
But because of their positive correlation, the combination of these two values is unusual, so it shows up in the 2-dimensional scatterplot.
The other anomaly does not look particularly unusual in any of the plots.
To visualise trivariate relationships, we need to use a 3D scatterplot, as in @fig-rgl.
It is easiest to see this if it can spin.
Try dragging the plot around with your mouse to view it from different angles.
See if you can find a viewpoint where the second anomaly is clearly separated from the other observations.
::: {#fig-rgl}
::::: {.figure-content}
```{r}
#| label: demo-rgl
#| webgl: true
#| cache: false
rgl::plot3d(
df[, 1:3],
size = 5,
col = c(rep("#999999", 998), rep("#D55E00", 2))
)
```
:::::
Three-dimensional scatterplot of the three variables, with anomalies shown in orange.
:::
This second anomaly is not particularly unusual in any combination of two variables, but it is unusual in the combination of all three variables.
When looking for anomalies, it is important to consider all the variables together, rather than looking at each variable in isolation, or even looking at all the pairwise relationships.
It is possible for an observation to be unusual in $m$ dimensions, but not unusual in any of the lower-dimensional subsets of variables.
In other words, there are more places for anomalies to hide in higher dimensions.
## The curse of dimensionality {#sec-curse}
The **curse of dimensionality** refers to the increasing sparseness of space as the number of dimensions increases.
### Points in the corners
Suppose we observed a high-dimensional data set of independent U$(-1,1)$ variables, and consider the proportion of points that lie outside the unit sphere (in the corners of the space) as the number of dimensions increases.
First, let's visualise what this means in 1, 2 and 3 dimensions.
In 1 dimension, the unit sphere is just the interval $[-1,1]$, so no points lie outside this interval.
In 2 dimensions, the unit sphere is the circle with radius 1, sitting snugly within a square of side length 2, as shown in @fig-curse2d.
```{r}
#| label: fig-curse2d
#| fig-cap: Two thousand simulated observations from two independent U(-1,1) distributions, with points within the unit circle shown in grey, and points outside the unit circle shown in orange.
#| fig-height: 5
#| fig-width: 5
#| out-width: 70%
tibble(
x = runif(2000, -1, 1),
y = runif(2000, -1, 1),
within_sphere = (x^2 + y^2) < 1
) |>
ggplot(aes(x = x, y = y, colour = within_sphere)) +
geom_point() +
coord_fixed() +
scale_colour_manual(values = c("#D55E00", "#777777")) +
guides(col = "none")
```
The proportion of points lying outside the circle in the corners of the space (shown in orange) is $`r sprintf("%.1f", 100*(1-pi/4))`$%.
The equivalent plot in 3 dimensions is shown in @fig-curse3d.
The unit sphere is now a ball of radius 1 sitting within a box, and $`r sprintf("%.1f", 100*(1-pi/6))`$% of points lie outside the ball.
::: {#fig-curse3d}
::::: {.figure-content}
```{r}
#| label: curse3d-plot
#| webgl: true
#| cache: false
df <- tibble(
x = runif(2000, -1, 1),
y = runif(2000, -1, 1),
z = runif(2000, -1, 1),
within_sphere = (x^2 + y^2 + z^2) < 1,
colour = if_else(within_sphere, "#777777", "#D55E00")
)
rgl::plot3d(df[, 1:3], size = 5, col = df$colour)
```
:::::
Two thousand simulated observations from three independent U(-1,1) distributions, with points within the unit sphere shown in grey, and points outside the unit sphere shown in orange.
:::
As the number of dimensions grows, it becomes increasingly likely that points will lie in the corners of the space.
In fact, the proportion of points lying outside the unit sphere in $m$ dimensions is 1 minus the ratio of the volume of the unit sphere to the volume of the whole space.
This is given by
$$
1 - \frac{\pi^{m/2}}{2^m\Gamma(m/2 + 1)}
$$
where $\Gamma$ is the gamma function, and is plotted in @fig-curse.
```{r}
#| label: fig-curse
#| fig-cap: For observations from an $m$-dimensional U(-1,1) distribution, the percentage of points lying outside the unit sphere in the corners of the space.
tibble(m = seq(10)) |>
mutate(outside = 100 * (1 - (pi^(m / 2) / (2^m * gamma(m / 2 + 1))))) |>
ggplot(aes(x = m, y = outside)) +
geom_line() +
labs(
x = TeX("Dimensions ($m$)"),
y = "Percentage of points outside unit sphere"
) +
scale_x_continuous(breaks = seq(10), minor_breaks = NULL)
```
By 10 dimensions, almost all points lie outside the unit sphere, and live in the corners of the space; almost no points are in the centre of the space.
This occurs because an observation is only near the centre if all of its coordinates are near zero, and with enough variables, at least one of them is likely to be far from zero.
For example, the probability that all $m$ coordinates lie between $-0.5$ and $0.5$ is $0.5^m$, which is less than 0.001 when $m = 10$.
### The size of neighbourhoods
Another way to think about this is to consider central hypercubes that contain 50% of the observations.
These must have sides of length $2^{1-1/m}$, in order for the volume of the hypercube to be $2^{m-1}$, exactly half of the entire space.
For $m = 1$, the hypercube is an interval of length 1; for $m = 2$, it is a square of side length $\sqrt{2} \approx 1.41$ as shown in @fig-hypercube; for $m = 3$, the central cube must have side length $2^{2/3} \approx 1.59$; and so on.
```{r}
#| label: fig-hypercube
#| fig-cap: Two thousand simulated observations from two independent U(-1,1) distributions, with the central square containing 50% of the observations.
#| fig-height: 5
#| fig-width: 5
#| out-width: 70%
tibble(
x = runif(2000, -1, 1),
y = runif(2000, -1, 1),
within_cube = (abs(x) < 2^(-1 / 2)) & (abs(y) < 2^(-1 / 2))
) |>
ggplot(aes(x = x, y = y, colour = within_cube)) +
geom_point() +
coord_fixed() +
scale_colour_manual(values = c("#D55E00", "#777777")) +
guides(col = "none")
```
As the dimension $m$ increases, the size of the hypercube containing 50% of the observations must also increase.
@fig-hypercubes shows the side length of these hypercubes plotted against the dimension $m$.
```{r}
#| label: fig-hypercubes
#| fig-cap: For observations from an $m$-dimensional U(-1,1) distribution, the side length of a hypercube which contains 50% of points.
tibble(m = seq(20)) |>
mutate(length = 2^(1 - 1 / m)) |>
ggplot(aes(x = m, y = length)) +
geom_line() +
geom_point() +
labs(
x = TeX("Dimensions ($m$)"),
y = "Side length of hypercube containing 50% of points"
) +
scale_x_continuous(breaks = seq(2, 20, by = 2), minor_breaks = NULL) +
ylim(1, 2)
```
The side lengths of these hypercubes approach the maximum of 2 as the number of dimensions increases.
So the size of the neighbourhood containing 50% of the observations becomes almost as large as the whole space.
Therefore, methods that rely on local neighbourhoods become unreliable in high dimensions, as these neighbourhoods must become so large as to no longer be "local".
## Joint probability distributions {#sec-joint}
Now we have a sense of what it means to have data in many dimensions, let's consider how we can describe the joint probability distribution of multiple variables.
### Statistical definitions
Suppose $\bm{Y} = [Y_1,\dots,Y_m]^\intercal$ is a random vector taking values in $\mathbb{R}^m$, the set of $m$-dimensional real vectors.
Then the joint distribution of $\bm{Y}$ is defined by the joint cdf
$$
F(\bm{y}) = \Pr(\bm{Y} \le \bm{y}),
$$
while the joint density function is given by
$$
f(\bm{y}) = \frac{\partial^m F(\bm{y})}{\partial y_1 \dots \partial y_m}.
$$
The marginal cdfs are defined by $F_i(y) = \Pr(Y_i \le y)$, with corresponding marginal pdfs given by $f_i(y) = F_i'(y)$, $i = 1,\dots,m$.
If the variables are independent, then the joint pdf is the product of the marginal pdfs, $f(\bm{y}) = \prod_{i=1}^m f_i(y_i)$.
The expected value of $\bm{Y}$ is the vector of expectations of its components, and is given by
$$
\text{E}(\bm{Y}) = \int_{\mathbb{R}^m} \bm{y} f(\bm{y})d\bm{y}.
$$
The covariance matrix of $\bm{Y}$ is given by
$$
\text{Var}(\bm{Y})
= \text{E}[(\bm{Y} - \text{E}(\bm{Y}))(\bm{Y} - \text{E}(\bm{Y}))^\intercal].
$$
The covariance matrix is an $m \times m$ matrix, with $(i,j)$th element given by $\text{Cov}(Y_i,Y_j) = \text{E}[(Y_i - \text{E}(Y_i))(Y_j - \text{E}(Y_j))]$.
The diagonal elements are the variances of the individual variables, while the off-diagonal elements are the covariances between the variables.
The covariance matrix is always symmetric and positive semi-definite.
Two useful results we will need are for the expectation and covariance of a linear transformation of a random vector.
If $\bm{Y}$ is an $m$-dimensional random vector, and $\bm{A}$ is a $k \times m$ matrix, then
\begin{align*}
\text{E}(\bm{A}\bm{Y}) & = \bm{A}\text{E}(\bm{Y}), \\
\text{Var}(\bm{A}\bm{Y}) & = \bm{A}\text{Var}(\bm{Y})\bm{A}^\intercal.
\end{align*}
### Multivariate Normal distribution
If random vector $\bm{Y}$ has a multivariate Normal distribution, we write $\bm{Y} \sim \text{N}(\bm{\mu}, \bm{\Sigma})$, where $\bm{\mu}$ is the mean and $\bm{\Sigma}$ is the covariance matrix.
The multivariate Normal distribution has pdf given by
$$
f(\bm{y}; \bm{\mu}, \bm{\Sigma})
= (2\pi)^{-m/2}|\bm{\Sigma}|^{-1/2} \exp\left\{ -\frac{1}{2}(\bm{y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{y} - \bm{\mu}) \right\}.
$$
The notation $|\bm{\Sigma}|$ denotes the determinant of the matrix $\bm{\Sigma}$.
The marginal distributions of a multivariate Normal distribution are also Normal.
More generally, suppose we split $\bm{Y}$ into two parts, $\bm{Y}_1$ and $\bm{Y}_2$, with the mean and covariance matrix split in the same way:
$$
\bm{Y} = \begin{bmatrix}
\bm{Y}_1 \\
\bm{Y}_2
\end{bmatrix},
\qquad \bm{\mu} = \begin{bmatrix}
\bm{\mu}_1 \\
\bm{\mu}_2
\end{bmatrix},
\qquad \bm{\Sigma} = \begin{bmatrix}
\bm{\Sigma}_{11} & \bm{\Sigma}_{12} \\
\bm{\Sigma}_{21} & \bm{\Sigma}_{22}
\end{bmatrix}.
$$
Then the marginal distribution of $\bm{Y}_1$ is $\text{N}(\bm{\mu}_1, \bm{\Sigma}_{11})$.
Another useful result concerns the quadratic form $(\bm{Y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{Y} - \bm{\mu})$ that appears in the pdf.
If $\bm{\Sigma}^{-1} = \bm{U}^\intercal\bm{U}$, then $\bm{Z} = \bm{U}(\bm{Y} - \bm{\mu})$ has a $\text{N}(\bm{0}, \bm{I})$ distribution (using the results for linear transformations above), so its elements are independent standard Normal random variables.
Therefore
$$
(\bm{Y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{Y} - \bm{\mu})
= \bm{Z}^\intercal\bm{Z} = \sum_{i=1}^m Z_i^2 \sim \chi^2_m.
$$ {#eq-mvn-chisq}
### Further reading
A good reference on multivariate probability distributions is @JKmulticontinuous1.
## Highest density regions {#sec-mhdr}
As with univariate distributions (@sec-hdr), a **highest density region** for a multivariate distribution is defined as the region of the sample space where the density is higher than a given threshold.
Suppose we have a multivariate random variable $\bm{Y}$ with a smooth, continuous density function $f$.
Then the $100(1 - \alpha)$% HDR is the set
$$
R_\alpha = \{\bm{y}: f(\bm{y}) \ge f_\alpha\}
$$
where $f_\alpha$ is the largest constant such that $\Pr(\bm{Y} \in R_\alpha) = 1 - \alpha$.
HDRs are equivalent to level sets of the density function, and so can be plotted as contours for bivariate density functions.
For example, the bivariate Normal distribution with mean $(0,0)$ and covariance matrix $\bm{\Sigma} = \begin{bmatrix} 1 & 0.5 \\ 0.5 & 1 \end{bmatrix}$ is shown in @fig-bivariate as a series of HDR contours, each containing an additional 10% of the probability mass.
```{r}
#| label: fig-bivariate
#| message: false
#| fig-cap: Bivariate Normal distribution with mean $(0,0)$ and covariance matrix $\bm{\Sigma} = \begin{bmatrix} 1 & 0.5 \\ 0.5 & 1 \end{bmatrix}$.
#| The HDR contours cover 10%, 20%, $\dots$, 90% of the probability mass.
mu <- c(0, 0)
Sigma <- matrix(c(1, 0.5, 0.5, 1), 2, 2)
distributional::dist_multivariate_normal(list(mu), list(Sigma)) |>
gg_density(hdr = "fill") +
labs(
x = TeX("$y_1$"),
y = TeX("$y_2$"),
title = TeX("Contours of $f(y_1,y_2)$")
)
```
Similarly, we can obtain HDRs for a mixture distribution.
Suppose we had two bivariate Normal distributions with means $(0,0)$ and $(3,1)$, and covariance matrices equal to $\bm{\Sigma} = \begin{bmatrix} 1 & 0.5 \\ 0.5 & 1 \end{bmatrix}$ and the identity matrix $\bm{I}_2$ respectively.
Then the HDRs for an equal mixture of these two distributions are shown in @fig-bivariate-mixture.
```{r}
#| label: fig-bivariate-mixture
#| message: false
#| fig-cap: Bivariate mixture distribution of two equally weighted Normal components with means $(0,0)$ and $(3,1)$, and covariance matrices $\bm{\Sigma} = \begin{bmatrix} 1 & 0.5 \\ 0.5 & 1 \end{bmatrix}$ and $\bm{I}_2$ respectively.
#| The HDR contours cover 10%, 20%, $\dots$, 90% of the probability mass.
mu1 <- c(0, 0)
mu2 <- c(3, 1)
Sigma1 <- rbind(c(1, 0.5), c(0.5, 1))
Sigma2 <- diag(2)
mixture_density <- dist_mixture(
dist_multivariate_normal(mu = list(mu1), sigma = list(Sigma1)),
dist_multivariate_normal(mu = list(mu2), sigma = list(Sigma2)),
weights = c(0.5, 0.5)
)
mixture_plot <- mixture_density |>
gg_density(hdr = "fill") +
labs(
x = TeX("$y_1$"),
y = TeX("$y_2$"),
title = TeX("Contours of $f(y_1,y_2)$")
)
mixture_plot
```
Here, the 10%, 20%, 30% and 40% HDRs contain disconnected regions, but for the larger HDRs, there is just one region for each.
## Multivariate quantiles {#sec-mv-quantiles}
Unlike the univariate case, there is no unique definition of a multivariate quantile, because there is no natural way to order points in $\mathbb{R}^m$.
Instead, multivariate quantiles are usually defined in a "centre-outward" way, so that a quantile describes a region containing a given probability, and the boundary of that region plays the role of a quantile.
There are many different definitions, each with its own advantages and disadvantages [@Serfling2002].
Two of them will be particularly useful in this book.
The first uses the HDRs of the previous section.
Because $\Pr(\bm{Y} \in R_\alpha) = \Pr(f(\bm{Y}) \ge f_\alpha) = 1 - \alpha$, the threshold $f_\alpha$ is the $\alpha$ quantile of the univariate random variable $f(\bm{Y})$, the density evaluated at a random observation.
So the boundary of $R_\alpha$ can be thought of as a multivariate quantile, and an observation lying outside $R_\alpha$ for some small value of $\alpha$ is in a region of low density.
This idea is the basis of the density-based approach to anomaly detection that is developed in @sec-density-methods.
For a multivariate Normal distribution, the density is a decreasing function of $(\bm{y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{y} - \bm{\mu})$, so it follows from @eq-mvn-chisq that
$$
R_\alpha
= \left\{ \bm{y}: (\bm{y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{y} - \bm{\mu}) \le \chi^2_{m,1-\alpha} \right\},
$$
where $\chi^2_{m,1-\alpha}$ is the $(1 - \alpha)$ quantile of the $\chi^2_m$ distribution.
That is, the HDRs of a multivariate Normal distribution are ellipsoids centred on $\bm{\mu}$, such as the ellipses in @fig-bivariate.
HDRs require the density to be known, or estimated.
The second approach, based on data depth, works directly with a sample of observations, and does not require a density.
This approach is discussed in @sec-depth.
## Robust covariance estimation {#sec-robust-cov}
The sample covariance matrix is a useful measure of the spread of a multivariate distribution, given by
$$
\bm{S}
= \frac{1}{n - 1} \sum_{i=1}^n (\bm{y}_i - \bar{\bm{y}})(\bm{y}_i - \bar{\bm{y}})^\intercal.
$$ {#eq-cov}
However, it is sensitive to anomalies, and so is not suitable for our purposes.
Many robust estimators of covariance have been proposed in the literature, but only one is discussed here: the **Minimum Covariance Determinant** (MCD) estimator [@Rousseeuw2003-ip;@fastmcd], which is implemented in the `covMcd()` function in the **`robustbase`** package [@robustbase].
This estimator finds the subset of $h$ observations (where $n/2 < h \le n$) whose covariance matrix has the smallest determinant.
The idea is that the subset of observations with the smallest covariance determinant is likely to be a subset of "good" observations, and so a covariance matrix computed from them will be robust to anomalies.
If $H$ denotes this subset, the raw MCD estimate of the covariance matrix is
$$
\bm{S}_H
= \frac{c_H}{h} \sum_{i \in H} (\bm{y}_i - \bar{\bm{y}}_H)(\bm{y}_i - \bar{\bm{y}}_H)^\intercal,
$$
where $\bar{\bm{y}}_H$ is the mean of the observations in $H$.
Because $H$ deliberately leaves out the most outlying observations, the covariance of the observations in $H$ underestimates the spread of the distribution, and $c_H > 1$ is a correction factor chosen so that $\bm{S}_H$ is a consistent estimate of $\bm{\Sigma}$ when the data come from a multivariate Normal distribution (with an additional adjustment for small samples).
The raw estimate uses only $h$ observations, which makes it rather inefficient.
So a reweighting step follows, in which every observation is compared to the raw estimate.
Using @eq-mvn-chisq, an observation is retained if $(\bm{y}_i - \bar{\bm{y}}_H)^\intercal\bm{S}_H^{-1}(\bm{y}_i - \bar{\bm{y}}_H) \le \chi^2_{m,0.975}$, and dropped otherwise.
If $W$ is the set of $n_W$ retained observations, with mean $\bar{\bm{y}}_W$, the final MCD estimate is
$$
\bm{S}_{\text{MCD}}
= \frac{c_W}{n_W - 1} \sum_{i \in W} (\bm{y}_i - \bar{\bm{y}}_W)(\bm{y}_i - \bar{\bm{y}}_W)^\intercal,
$$ {#eq-mcd}
where $c_W$ is another correction factor.
The `covMcd()` function returns $\bm{S}_{\text{MCD}}$ (as `cov`) along with the raw estimate $\bm{S}_H$ (as `raw.cov`).
The subset size $h$ is set via the argument `alpha`, with $h \approx$ `alpha` $\times\, n$; the default `alpha = 0.5` gives the most robust estimate, allowing almost half the observations to be anomalies.
The `mvscale()` and `kde_bandwidth()` functions in the **`weird`** package use `alpha = 0.9`, allowing up to 10% of the observations to be anomalies, which gives a more efficient estimate, and the same value is used here.
To illustrate, consider a data set whose true distribution is known.
It uses the first two variables of the `n01` data set, $v_1$ and $v_2$, with $y_1 = v_1$ and $y_2 = v_1 + v_2$.
Then $(y_1,y_2)$ has a bivariate Normal distribution with mean $(0,0)$ and covariance matrix $\bm{\Sigma} = \begin{bmatrix} 1 & 1 \\ 1 & 2 \end{bmatrix}$ (using the results for linear transformations in @sec-joint), so the correlation between $y_1$ and $y_2$ is $1/\sqrt{2} \approx 0.71$.
The last 50 of the 1000 observations are then replaced with a small cluster of anomalies centred at $(2,-2)$, constructed from two other variables in `n01`.
```{r}
#| label: mcd-data
#| code-fold: false
mcd_df <- n01 |>
transmute(y1 = v1, y2 = v1 + v2, anomaly = FALSE)
# Replace the last 50 observations with a cluster of anomalies
idx <- 951:1000
mcd_df$y1[idx] <- 2 + 0.3 * n01$v3[idx]
mcd_df$y2[idx] <- -2 + 0.3 * n01$v4[idx]
mcd_df$anomaly[idx] <- TRUE
# Sample and MCD estimates
mcd_y <- mcd_df |> select(y1, y2)
mcd_est <- robustbase::covMcd(mcd_y, alpha = 0.9)
cor(mcd_y)
cov2cor(mcd_est$cov)
```
The sample correlation has been pulled down to `r sprintf("%.2f", cor(mcd_y)[1, 2])` by the anomalies, while the MCD estimate gives `r sprintf("%.2f", cov2cor(mcd_est$cov)[1, 2])`, close to the true value of 0.71.
In the reweighting step, `r sum(mcd_est$raw.weights[idx] == 0)` of the 50 anomalies are dropped.
Because the bulk of these data really do come from a bivariate Normal distribution, we can use @eq-mvn-chisq to draw the 95% HDR of the true distribution, and the corresponding ellipses obtained by plugging in the sample estimates and the MCD estimates of the mean and covariance matrix.
These are shown in @fig-robust-cov.
```{r}
#| label: fig-robust-cov
#| dependson: mcd-data
#| fig-cap: >-
#| Simulated bivariate Normal data (grey) with a cluster of 50 anomalies (black).
#| The ellipses show the 95% HDR of the true distribution, and the corresponding regions obtained using the sample mean and covariance matrix, and the MCD estimates.
# Compute an ellipse containing 95% of a bivariate Normal distribution
ellipse <- function(centre, S, level = 0.95) {
theta <- seq(0, 2 * pi, length = 200)
r <- sqrt(qchisq(level, df = 2))
pts <- centre + r * t(chol(S)) %*% rbind(cos(theta), sin(theta))
tibble(y1 = pts[1, ], y2 = pts[2, ])
}
ellipses <- bind_rows(
ellipse(c(0, 0), matrix(c(1, 1, 1, 2), 2, 2)) |>
mutate(method = "True distribution"),
ellipse(colMeans(mcd_y), cov(mcd_y)) |> mutate(method = "Sample covariance"),
ellipse(mcd_est$center, mcd_est$cov) |> mutate(method = "MCD")
)
mcd_df |>
ggplot(aes(x = y1, y = y2)) +
geom_point(data = ~ filter(.x, !anomaly), colour = "#999999", alpha = 0.4) +
geom_point(data = ~ filter(.x, anomaly), colour = "black", alpha = 0.6) +
geom_path(data = ellipses, aes(colour = method), linewidth = 0.8) +
labs(
x = TeX("$y_1$"),
y = TeX("$y_2$"),
colour = ""
)
```
```{r}
#| label: check-robust-cov
#| include: false
#| dependson: mcd-data
stopifnot(
abs(cor(mcd_y)[1, 2] - 0.51) < 0.01,
abs(cov2cor(mcd_est$cov)[1, 2] - 0.69) < 0.01,
sum(mcd_est$raw.weights[idx] == 0) == 49,
# All anomalies outside the MCD ellipse, some inside the sample ellipse
all(mahalanobis(mcd_y[idx, ], mcd_est$center, mcd_est$cov) > qchisq(0.95, 2)),
any(mahalanobis(mcd_y[idx, ], colMeans(mcd_y), cov(mcd_y)) <= qchisq(0.95, 2))
)
```
The MCD ellipse is almost identical to the true HDR, and all 50 anomalies lie outside it.
In contrast, the ellipse based on the sample covariance matrix has been stretched towards the anomalies, and is less elongated because of the reduced correlation, so that some of the anomalies lie inside it.
## Multivariate scaling {#sec-scaling}
Some anomaly detection methods will require the data to have been scaled first, to prevent the variables with the largest ranges from dominating.
### Z-scores
One common approach is to apply univariate scaling on each variable, by subtracting its mean and dividing by its standard deviation.
This gives $z$-scores.
If our data are given by $y_1,\dots,y_n$, then their $z$-scores are given by
$$
z_i = (y_i - \bar{y})/s_y
$$
where $\bar{y}$ is the mean and $s_y$ is the standard deviation of the observations.
These are easily computed using the `scale()` function.
However, the mean and standard deviation may be affected by anomalies, and it would be better to use an approach that was robust to anomalies.
### Robust $z$-scores
The simplest way to make the scaling robust to anomalies is to use the median instead of the mean, and to use a robust estimate of the standard deviation such as $Q_n$ (@sec-robust-univariate).
Robust $z$-scores computed in this way can be obtained using the `mvscale()` function with the argument `cov = NULL`.
### Multivariate $z$-scores
It is sometimes useful to scale a set of multivariate data, so that the scaled variables are uncorrelated with each other, and have mean zero and unit variance.
Suppose each observation is a vector $\bm{y}_i$, coming from a distribution with mean $\bm{\mu}$ and covariance matrix $\bm{\Sigma}$.
Let $\bm{\Sigma}^{-1} = \bm{U}^\intercal \bm{U}$ be the Cholesky decomposition (see @sec-cholesky) of $\bm{\Sigma}^{-1}$.
Then the data can be scaled by $\bm{U}$, giving $\bm{z}_i = \bm{U} (\bm{y}_i - \bm{\mu})$, so that the covariance matrix of the scaled data is the identity matrix.
This can be thought of as both scaling and rotating the data, so that the variables are uncorrelated with mean zero and unit variance.
It is the multivariate equivalent of calculating $z$-scores.
Multivariate $z$-scores can be computed using the `mvscale()` function with the arguments `center = mean` and `cov = stats::cov`.
### Robust multivariate $z$-scores
When there may be anomalies in the data set, we can replace the mean by the pointwise median (i.e., the vector of medians for each variable), and estimate $\bm{\Sigma}$ using the robust covariance matrix $\bm{S}_{\text{MCD}}$ (@eq-mcd).
The `mvscale()` function in the **`weird`** package will do this for us, by default.
Let's consider the `oldfaithful` data again, where waiting times are much longer than durations.
@fig-scaling shows the data before and after scaling.
The scaling has rotated the data a little, and the variables are now less correlated, and centred on zero.
The right plot still appears to show some positive relationship between the variables, because the covariance matrix used for scaling was computed robustly, and so was based only on the upper cluster of points.
```{r}
#| label: fig-scaling
#| warning: false
#| fig-cap: "Old Faithful duration and waiting time data, before and after scaling."
p1 <- oldfaithful |>
ggplot(aes(x = duration, y = waiting)) +
geom_point(alpha = 0.2) +
labs(
title = "Original data",
x = "Duration of eruption (seconds)",
y = "Waiting time to next eruption (seconds)"
)
p2 <- mvscale(oldfaithful, warning = FALSE) |>
ggplot(aes(x = z1, y = z2)) +
geom_point(alpha = 0.2) +
labs(
title = "Scaled data",
x = TeX("$z_1$"),
y = TeX("$z_2$")
)
patchwork::wrap_plots(p1, p2, nrow = 1)
```
## Clustering {#sec-clustering}
Clustering methods group observations into distinct non-overlapping "clusters" based on their similarity.
They are sometimes used for anomaly detection, as anomalies may form their own small clusters, or may appear as observations that do not belong to any cluster.
Even if clustering is not used directly, some anomaly detection methods use tools based on clustering, and so we will need to understand some of the basic concepts.
This section describes four of the most popular clustering methods: K-means clustering, the leader algorithm, DBSCAN, and hierarchical clustering.
The methods differ in what information must be supplied in advance.
K-means requires the number of clusters, $K$.
The leader algorithm and DBSCAN instead use a distance threshold, $\delta$, which defines a local neighbourhood around each observation.
DBSCAN also uses a density parameter, $M$.
Hierarchical clustering can be used to examine what happens across many possible values of a distance threshold.
### K-means clustering
K-means clustering [@Hartigan1975] partitions the data into $K$ clusters, where $K$ is a user-specified parameter.
The algorithm begins by selecting $K$ observations as initial "centroids".
Then, each observation is assigned to the cluster whose centroid is closest to it, based on some distance measure (usually Euclidean distance, but see @sec-distances for other possibilities).
After all observations have been assigned to clusters, the centroids are updated to be the mean of the observations in each cluster.
This process is repeated until convergence, which occurs when the cluster assignments no longer change.
Although the K-means algorithm is relatively fast, it can be sensitive to the choice of initial centroids, so it is common to run the algorithm several times using different random starts.
It also assumes that the clusters are roughly spherical and of similar size, which may not always be the case.
A further drawback, especially in the context of anomaly detection, is that anomalies can strongly affect the cluster centroids.
The number of clusters, $K$, must also be specified in advance, which can be difficult to determine, and often requires some experimentation.
### Leader algorithm
Rather than specify the number of clusters in advance, we can specify a maximum radius for each cluster, and then find clusters that satisfy this constraint.
This is known as the **leader algorithm** [@Hartigan1975], and is a fast, incremental clustering method that can be used for large data sets.
The main input is $\delta$, the maximum distance from an observation to the leader of its cluster.
The algorithm can be summarised as follows:
1. Select the first observation as the first **leader**.
2. For each subsequent observation:
a. If the observation is within $\delta$ of one or more existing leaders, assign it to the cluster of the nearest such leader.
b. If the observation is not within $\delta$ of any existing leader, make it the leader of a new cluster.
Thus, each cluster is defined by a leader and the observations assigned to that leader.
The leaders remain fixed throughout the algorithm: they are observations from the original data, not cluster centroids.
Every assigned observation is within $\delta$ of its leader, so two observations in the same leader cluster can be up to $2\delta$ apart.
The result depends on the order of the observations, since an observation that appears early in the data can become a leader and affect the assignment of all the observations that follow.
The leader algorithm is very fast because it makes only one pass through the data, although its speed also depends on how many leaders are created.
It can be useful for anomaly detection because an isolated observation is not forced into a distant cluster: instead, it becomes the leader of a singleton or small cluster.
However, this should not be interpreted as full robustness.
An early anomaly can become a leader, and both the leaders and the resulting clusters depend on the ordering of the observations.
The `leader()` function from the **`probout`** package implements this algorithm.
The function uses a strict comparison, requiring the distance to be less than `radius`, rather than less than or equal to it; this distinction is unimportant for continuous data unless a distance is exactly equal to the threshold.
By default, `leader()` scales each variable to the unit interval, but we use `scale = FALSE` below because the data have already been converted to robust multivariate $z$-scores.
To compare K-means and the leader algorithm, we apply them to the Old Faithful data set in @fig-clustering-off.
First, the data are converted to robust multivariate $z$-scores (@sec-scaling) to prevent the waiting-time variable from dominating the clustering.
K-means clustering is then applied with $K = 2$, while the leader algorithm is applied with $\delta = 3.3$, chosen after some experimentation.
The `leader()` function returns each cluster as a vector of observation indices, so these partitions are converted to a vector of cluster labels for plotting.
```{r}
#| label: fig-clustering-off
#| fig-cap: >-
#| Clustering of the Old Faithful data set using K-means and the leader algorithm.
#| The K-means clusters are shown in the left plot, while the leader clusters are shown in the right plot.
#| K-means forces every observation into one of two clusters, while the leader algorithm can isolate outlying observations into small clusters.
set.seed(12345)
of_scaled <- oldfaithful |>
select(duration, waiting) |>
mvscale()
km_clusters <- kmeans(of_scaled, centers = 2, nstart = 20)
leader_result <- probout::leader(
as.matrix(of_scaled),
radius = 3.3,
scale = FALSE
)[[1]]
leader_cluster <- integer(nrow(of_scaled))
for (k in seq_along(leader_result$partitions)) {
leader_cluster[leader_result$partitions[[k]]] <- k
}
oldfaithful |>
mutate(
km_cluster = factor(km_clusters$cluster),
leader_cluster = factor(leader_cluster)
) |>
tidyr::pivot_longer(
cols = c(km_cluster, leader_cluster),
names_to = "method",
values_to = "cluster"
) |>
mutate(
method = recode(
method,
km_cluster = "K-means clustering",
leader_cluster = "Leader clustering"
)
) |>
ggplot(aes(x = duration, y = waiting, colour = cluster)) +
geom_point() +
facet_wrap(~method) +
labs(x = "Duration (seconds)", y = "Waiting time (seconds)")
```
K-means forces every observation into one of the specified $K = 2$ clusters, so outlying observations can pull the cluster centroids towards themselves.
The leader algorithm does not fix the number of clusters.
An observation farther than $\delta$ from every existing leader starts a new cluster, allowing isolated observations to form singleton or small clusters rather than being absorbed into one of the main clusters.
Conversely, increasing $K$ in K-means to match the number of leader clusters need not produce the same result: K-means may split the main clouds rather than separate the outlying observations.
### DBSCAN clustering
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is a clustering method proposed by @dbscan that identifies clusters as dense regions of nearby observations.
Like the leader algorithm, it uses a neighbourhood radius $\delta$, but adds a density condition controlled by a second parameter $M$.
It does not require the number of clusters to be specified in advance, and unlike K-means and the leader algorithm, it allows some observations to be left unclustered.
These unclustered observations are called **noise** by the algorithm, and are often interpreted as potential anomalies.
Note that this use of the word "noise" is different from the usual use of the word in statistics, where it refers to random variation in the data.
The algorithm has two main parameters: $\delta$, the radius of the neighbourhood around each observation, and $M$, the minimum number of observations required for a neighbourhood to be considered dense.
For each observation $\bm{y}_i$, let $N_{\delta}(\bm{y}_i)$ denote the number of observations within distance $\delta$ of $\bm{y}_i$, including $\bm{y}_i$ itself.
An observation $\bm{y}_i$ is classified as follows:
- it is a **core** observation if $N_{\delta}(\bm{y}_i) \ge M$;
- it is a **border** observation if it is not a core observation, but it is within distance $\delta$ of at least one core observation;
- otherwise it is **noise**.
Clusters are formed by connecting nearby core observations that are within $\delta$ of each other.
Each connected group of core observations forms one cluster.
Border observations are then attached to any cluster containing a core observation within distance $\delta$.
If a border observation is within distance $\delta$ of core observations from more than one cluster, its assignment may be arbitrary or implementation-dependent.
Noise observations are not assigned to any cluster.
The DBSCAN algorithm is implemented in the `dbscan()` function in the **`dbscan`** package.
@fig-clustering-dbscan shows the result for the Old Faithful data set, using $\delta = 0.61$ and $M = 20$ (again, chosen after some experimentation).
```{r}
#| label: fig-clustering-dbscan
#| dependson: fig-clustering-off
#| fig-cap: "DBSCAN clustering of the Old Faithful data set using robust multivariate $z$-scores, with noise observations shown in dark grey."
dbscan_clusters <- dbscan::dbscan(of_scaled, eps = 0.61, minPts = 20)
oldfaithful |>
mutate(dbscan_cluster = factor(dbscan_clusters$cluster)) |>
ggplot(aes(x = duration, y = waiting, colour = dbscan_cluster)) +
geom_point() +
labs(x = "Duration (seconds)", y = "Waiting time (seconds)") +
scale_colour_manual(
values = c(
`0` = "#444444",
`1` = "#D55E0088",
`2` = "#0072B288"
),
labels = c(
`0` = "Noise",
`1` = "Cluster 1",
`2` = "Cluster 2"
)
) +
guides(colour = guide_legend(title = "DBSCAN cluster"))
```
### The $\delta$-neighbourhood graph
Both the leader algorithm and DBSCAN can be understood using a graph (i.e., a network, not a plot).
Each observation is a vertex, and we draw an edge between two vertices if the distance between the corresponding observations is at most $\delta$.
This graph is sometimes called the **$\delta$-neighbourhood graph**.
Points that can be reached from each other by following edges are said to be **connected**.
A **connected component** is a group of vertices that are all connected to each other, but with no connections to vertices outside the group.
For example, consider the eight points labelled A to H shown in @fig-graph, and suppose we choose $\delta = 1.5$.
The blue disks centred on each point have radius $\delta/2$; so overlapping disks indicate that their central points are within $\delta$ of each other.
Points B and H form an edge, but are disconnected from all other points because they are further than $\delta$ from the other points.
The pair A and F also form an edge, and D is connected to them via F.
They do not form a triangle because A and D are too far apart.
The points C, E and G form a connected triangle.
```{r}
#| label: fig-graph
#| fig-cap: >-
#| An example of a $\delta$-neighbourhood graph based on eight observations, where two observations are joined by an edge if the distance between them is at most $\delta=1.5$.
#| The blue disks have radius $\delta/2$, so overlapping disks indicate that their central points are within $\delta$ of each other.
#| If DBSCAN is applied with $M=3$, the graph contains two clusters and two noise observations.
#| message: false
#| warning: false
#| echo: false
X <- data.frame(
x = c(0.926, 1.82, -1.61, -0.285, -0.342, 0.366, -1.33, 2.41),
y = c(0.0638, 1.55, -1.88, 1.211, -1.31, 0.0421, -0.785, 1.21)
)
rownames(X) <- LETTERS[1:8]
delta_neighbourhood(X, 1.5) +
coord_fixed() +
geom_text(
aes(x = x, y = y, label = LETTERS[1:8]),
nudge_x = -0.1,
nudge_y = 0.1
)
```
The leader algorithm uses this graph in an order-dependent way.
As observations (vertices) are processed, some become leaders.
A new observation joins an existing leader if it is connected by an edge to at least one leader; otherwise, it becomes a new leader.
This means leaders cannot be within $\delta$ of each other.
The output is a set of leader-centred, star-like clusters.
These are not necessarily the same as the connected components of the full $\delta$-neighbourhood graph: observations in different leader clusters may still be connected by an edge, and a connected component may contain several leader clusters.
For these eight points, if we process in alphabetical order, A becomes the first leader.
B, C and D also become leaders, since none are within $\delta$ of an existing leader.
The later observations E, F, G and H are assigned to existing leaders, giving clusters A--F, B--H, C--E--G, and D.
DBSCAN uses the same $\delta$-neighbourhood graph differently.
It first identifies which vertices are core observations, using the density condition described above.
Since the $\delta$-neighbourhood includes $\bm{y}_i$ itself, a vertex is core when it has at least $M - 1$ neighbours in the graph.
DBSCAN then forms clusters from connected groups of core vertices, and attaches any border vertices that are connected to those core groups.
Sparse vertices that are not connected to any core vertex are labelled as noise.
Thus, where the leader algorithm uses $\delta$ to build clusters around selected representative vertices, DBSCAN uses $\delta$ to build dense connected regions.
If we considered only the connected components of the $\delta$-neighbourhood graph, there would be three groups: A--F--D, C--E--G, and B--H.
DBSCAN adds the density condition.
With $M = 3$, F is a core observation because its $\delta$-neighbourhood contains A, F and D.
The points C, E and G are also core observations because each of them has the other two points in its $\delta$-neighbourhood.
By contrast, B and H are not core observations, because their $\delta$-neighbourhoods contain only B and H.
They are not border observations either, because they are not connected to any core observation.
Therefore, DBSCAN labels B and H as noise.
So, for this example, DBSCAN gives two clusters and two noise observations:
- A--F--D is one cluster, with F as a core observation and A and D as border observations;
- C--E--G is another cluster, with all three points as core observations;
- B and H are noise observations.
This example illustrates the difference between a sparse group and a dense cluster.
The pair B--H is a connected component of the $\delta$-neighbourhood graph, and may be a leader cluster, but it is not dense enough to be a DBSCAN cluster.
### Hierarchical clustering
A related approach is to examine what happens as the distance threshold changes.
If we ignore the DBSCAN density condition and simply take the connected components of the $\delta$-neighbourhood graph, then increasing the threshold gives a sequence of cluster mergers.
This is the idea behind **single-linkage hierarchical clustering**.
Imagine slowly increasing a distance threshold $\delta$ from 0 upwards.
At $\delta = 0$, and assuming there are no duplicate observations, there are no edges, so every observation is its own cluster.
As $\delta$ increases, more edges appear, and clusters merge together.
When an edge connects two clusters that were previously separate, those two clusters merge into one larger cluster.
Eventually, all clusters merge into a single cluster.
For the small example of @fig-graph, @fig-clusters shows what happens as $\delta$ increases from 0.5 to 2.0.
With a small value of $\delta$, all points are disconnected, and the graph consists of eight vertices with no edges.
As $\delta$ increases, more points are connected to each other, and eventually, the graph consists of a single connected component.
```{r}
#| label: fig-clusters
#| fig-cap: >-
#| Connected components resulting from different $\delta$ values.
#| This sequence of connected components corresponds to single-linkage hierarchical clustering, not DBSCAN, because there is no density condition and no observations are labelled as noise.
#| echo: false
#| warning: false
#| fig-width: 8
#| fig-asp: 1
#| out-width: "100%"
#| dependson: fig-graph
prox <- 0.5 + seq(0, 1.5, by = 0.5)
p <- list()
for (i in seq_along(prox)) {
p[[i]] <- delta_neighbourhood(X, delta = prox[i]) +
geom_text(
aes(x = x, y = y, label = LETTERS[1:8]),
nudge_x = -0.1,
nudge_y = 0.1
) +
labs(subtitle = TeX(sprintf("$\\delta$ = %.1f", prox[i]))) +
coord_cartesian(xlim = c(-2.5, 2.5), ylim = c(-2.5, 2.5), ratio = 1)
}
patchwork::wrap_plots(p, nrow = 2)
```
In single-linkage hierarchical clustering, we start with each observation as its own cluster, and then repeatedly merge the two closest clusters together until we have one final cluster.
The distance between two clusters when they merge is called the **merge distance**.
For single-linkage clustering, the distance between two clusters is the minimum distance between any point in one cluster and any point in the other cluster.
This is different from DBSCAN in two important ways.
First, single-linkage hierarchical clustering does not distinguish between core, border and noise observations --- every observation belongs to some cluster at every stage, just as in K-means and the leader algorithm.
Second, rather than fixing $\delta$ in advance and returning a single partition of the data, hierarchical clustering records the complete sequence of partitions for all possible values of $\delta$, indexed by the merge distance.
We can obtain a particular partition by cutting the hierarchy at a chosen merge distance, but the hierarchy itself shows how the clusters merge as $\delta$ increases.
Other forms of hierarchical clustering use different measures of the distances between clusters.
For example, complete-linkage is based on the maximum distance between any two points in the two clusters, while average-linkage is based on the average distance between all pairs of points across the two clusters.
The graph interpretation above applies specifically to single-linkage hierarchical clustering.
Hierarchical clustering is usually displayed as a **dendrogram**, with the following properties:
- Each observation starts as a leaf.
- Branches join when two clusters merge.
- The axis showing the height of each join gives the merge distance.
The single-linkage dendrogram for the point cloud in @fig-graph is shown in @fig-dendrogram.
```{r}
#| label: fig-dendrogram
#| echo: false
#| dependson: fig-graph
#| fig-asp: 0.5
#| fig-cap: >-
#| Dendrogram of the point cloud in @fig-graph.
#| The heights of the joins correspond to the merge distances.
library(ggdendro)
hc <- dist(X) |>
hclust(method = "single")
hcdata <- dendro_data(hc, type = "rectangle")
ggplot() +
geom_segment(
data = segment(hcdata),
aes(x = x, y = y, xend = xend, yend = yend)
) +
scale_x_continuous(breaks = seq_len(NROW(X)), labels = label(hcdata)$label) +
coord_flip() +
labs(x = "Observation", y = "Merge distance")
```
@fig-mergedistances shows a bar plot of the cluster merge distances for the point cloud shown in @fig-graph.
These correspond to the merge heights in the dendrogram in @fig-dendrogram.
The shortest distance corresponds to the merge of A and F, the first pair of vertices to be joined by an edge.
The largest distance corresponds to when all points became connected, when the B--H component merged with the rest of the data.
With $n$ observations, there are $n$ initial clusters, but only $n - 1$ merges are needed to end up with one final cluster.
So we get $n - 1$ merge distances.
```{r}
#| label: fig-mergedistances
#| echo: false
#| fig-cap: >-
#| Merge distances of the point cloud in @fig-graph.
#| Each bar corresponds to one merge, with length equal to the merge distance.
#| fig-width: 8
#| fig-height: 1.6
#| fig-asp: 0.2
#| out-width: "100%"
#| warning: false
#| dependson: [fig-graph, fig-dendrogram]
data.frame(
row = seq_along(hc$height),
distance = hc$height
) |>
ggplot(aes(x = row, y = distance)) +
geom_bar(stat = "identity", width = 0.1, fill = "#C14b14") +
labs(y = "Merge distance", x = "") +
coord_flip() +
scale_x_continuous(breaks = NULL) +
theme(axis.text.y = element_blank(), axis.ticks.y = element_blank())
```
In the context of anomaly detection, observations or small groups that merge with the rest of the data only at large merge distances are potential anomalies.
For example, in @fig-dendrogram, B and H form a small cluster that merges with the rest of the data only at the largest merge distance, so they are potential anomalies.
By contrast, the other points merge together at smaller distances, so they are less likely to be anomalies.
#### Related ideas
For single-linkage hierarchical clustering, the graph structure described above is related to the minimum spanning tree (MST) of the data, which is a tree that connects all observations together with the minimum total edge length.
The merge distances are the MST edge weights in the order they are added to the tree.
The graph structure is also related to topological data analysis (TDA), a collection of methods for summarising the shape of data.
For example, connected components are known as 0-dimensional topological features in persistent homology.
When two connected components merge, one is described as "dying" and the other as "persisting".
The merge distance is called the **death diameter**, and the bar plot of merge distances is known as a **barcode**.
Long bars in the barcode correspond to connected components that remain separate over a wide range of distance thresholds, which may include potential anomalies.
For a general introduction to TDA, see @carlsson2021topological.
## Multivariate kernel density estimation {#sec-mvkde}
Suppose our observations are $m$-dimensional vectors, $\bm{y}_1,\dots,\bm{y}_n$.
Then the multivariate version of @eq-kde is given by [@Scott2015]
$$
\hat{f}(\bm{y}) = \frac{1}{n} \sum_{i=1}^n K_{\bm{H}}(\bm{y} - \bm{y}_i),
$$ {#eq-mkde}
where $K_{\bm{H}}$ is a multivariate probability density with covariance matrix $\bm{H}$.
This book uses a multivariate Gaussian kernel given by
$$
K_{\bm{H}}(\bm{u})
= (2\pi)^{-m/2} |\bm{H}|^{-1/2} \exp \{-\textstyle\frac12 \bm{u}^\intercal\bm{H}^{-1}\bm{u} \}.
$$
### Bivariate kernel density estimation
```{r}
#| label: bivariatebandwidths
#| include: false
of2021 <- oldfaithful |>
filter(as.Date(time) > "2021-01-01") |>
head(10) |>
select(duration, waiting) |>
mutate(eruption = row_number())
H <- kde_bandwidth(of2021[, 1:2])
```
To illustrate the idea, consider a simple bivariate example of 10 observations: the first 10 eruption durations from 2021 that are in the `oldfaithful` data set, along with the corresponding waiting times until the following eruption.
These are shown in @fig-ofdw along with the contours of bivariate kernels placed over each observation.
Each kernel is a bivariate Gaussian density with bandwidth matrix $\bm{H} = \left[\begin{array}{rr}`r sprintf("%.f", H[1,1])` & `r sprintf("%.f", H[1,2])` \\ `r sprintf("%.f", H[2,1])` & `r sprintf("%.f", H[2,2])`\end{array}\right]$.