Repository navigation
Expand file tree
/
Copy pathregression.qmd
More file actions
889 lines (733 loc) · 43.4 KB
/
Copy pathregression.qmd
File metadata and controls
889 lines (733 loc) · 43.4 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
# Regression methods {#sec-regression-methods}
```{r}
#| label: setup8
#| include: false
#| cache: false
source("before-each-chapter.R")
```
Regression methods arise when we want to find anomalies in a particular variable of interest (called the **response**), and we have a set of predictor variables that we think might be useful for predicting the response.
That is, we are interested in finding observations whose responses are anomalous *given their predictor values*.
For example, we might want to find wines that are unusually expensive given their points score, or find houses that are unusually cheap given their size and location.
The response is denoted by $y_i$ and its predictor vector by $\bm{x}_i$.
## Linear regression {#sec-ols}
The simplest regression model is the linear regression model, which assumes that the response is a linear function of the predictors plus a random error term:
$$
y_i = \bm{x}_i^\intercal \bm{\beta} + \varepsilon_i,
$$
where $\bm{\beta}$ is a vector of coefficients and the errors $\{\varepsilon_1,\dots,\varepsilon_n\}$ are iid with mean zero and common variance $\sigma^2$.
Here $\bm{x}_i$ may include a leading 1 if an intercept is included in the model.
Let $p$ be the length of $\bm{x}_i$.
The model can be written in matrix form as $\bm{y} = \bm{X}\bm{\beta} + \bm{\varepsilon}$, where $\bm{y}$ is the $n$-vector of responses, $\bm{X}$ is the $n \times p$ matrix of predictors, and $\bm{\varepsilon}$ is the $n$-vector of errors.
Provided $\bm{X}$ is of rank $p$ (@sec-rank), the model can be estimated using ordinary least squares (OLS) regression [@seberlee2003], resulting in the estimate
$$
\hat{\bm{\beta}} = (\bm{X}^\intercal\bm{X})^{-1}\bm{X}^\intercal\bm{y}.
$$ {#eq-ols}
The fitted values (i.e., predicted values for the training data) are given by
$$
\hat{\bm{y}} = \bm{X}\hat{\bm{\beta}} = \bm{H}\bm{y},
$$
where $\bm{H} = \bm{X}(\bm{X}^\intercal\bm{X})^{-1}\bm{X}^\intercal$ is known as the **hat matrix** because it creates the "y-hat" values $\hat{\bm{y}}$ from the data $\bm{y}$.
The residuals (or prediction errors) from the model are the differences between what was observed and what was predicted, given by
$$
\bm{e} = \bm{y} - \hat{\bm{y}} = (\bm{I} - \bm{H})\bm{y}.
$$
Many regression-based anomaly detection methods involve finding anomalies in the residuals.
The diagonals of $\bm{H}$, given by
$$
h_i = \bm{x}_i^\intercal(\bm{X}^\intercal\bm{X})^{-1}\bm{x}_i,\qquad i = 1,\dots,n,
$$ {#eq-leverage}
take values between 0 and 1.
These are known as the **leverage** values [@faraway2004linear, p. 69], and measure how much each observation influences the corresponding fitted value.
High leverage values (close to 1) correspond to observations that can have a large influence on the estimated coefficients, and so leaving those observations out can lead to very different values for the fitted values and residuals.
On the other hand, small leverage values (close to 0) correspond to observations that have little influence on the estimated coefficients, and so leaving those observations out will lead to similar values for the fitted values and residuals.
Often high leverage values are those corresponding to anomalies in the predictor space (although not necessarily in the space of the response variable).
A linear model can be estimated in R using the `stats::lm()` function, while `broom::augment()` computes the fitted values, residuals and leverage values.
### Example: Shiraz reviews
Consider the wine reviews of Shiraz (aka Syrah), plotted in @fig-shiraz.
We can fit a linear regression model to these data, using the points awarded to each wine as a predictor, and the log prices as the response variable.
```{r}
#| label: fetch-wine-reviews-regression
#| eval: false
#| code-fold: false
wine_reviews <- fetch_wine_reviews()
```
```{r}
#| label: shiraz-regression
#| code-fold: false
shiraz <- wine_reviews |>
filter(
variety %in% c("Shiraz", "Syrah"),
!is.na(price) & !is.na(points)
) |>
select(-variety)
fit_wine <- lm(log(price) ~ points, data = shiraz)
broom::tidy(fit_wine)
broom::glance(fit_wine)
```
The fitted model can be written as
$$
\log(\text{Price}) = `r sprintf("%.3f",coef(fit_wine)[1])` + `r sprintf("%.3f",coef(fit_wine)[2])` \times \text{Points} + \varepsilon,
$$
where $\varepsilon$ is a random error term with mean zero and variance $`r sprintf("%.3f",sigma(fit_wine))`^2$.
The fitted regression line is shown in @fig-shiraz-regression.
```{r}
#| label: wine_aug
#| code-fold: false
#| dependson: shiraz-regression
wine_aug <- fit_wine |>
broom::augment(data = shiraz)
```
```{r}
#| label: fig-shiraz-regression
#| warning: false
#| fig-cap: Log price of Shiraz as a function of points.
#| The points are horizontally jittered to reduce overplotting.
#| code-fold: false
#| dependson: wine_aug
wine_aug |>
ggplot(aes(y = price, x = points)) +
geom_jitter(height = 0, width = 0.1, alpha = 0.5, colour = "#999999") +
geom_line(aes(y = exp(.fitted))) +
scale_y_log10()
```
Note that `broom::augment()` returns the fitted values as `.fitted`, and the leverage values as `.hat`.
```{r}
#| label: leverage
#| code-fold: false
#| dependson: wine_aug
wine_aug |>
select(country:price, .hat) |>
arrange(desc(.hat))
```
Here the highest leverage values are due to the only two wines with 100 points, while the three on 99 points result in the next highest.
After that come the wines with the lowest points values.
For a model with an intercept and a single predictor taking values $x_1,\dots,x_n$, $h_i = 1/n + (x_i - \bar{x})^2/\sum_{j=1}^n (x_j - \bar{x})^2$, so leverage depends only on how far $x_i$ is from the mean of the predictor, and observations at the edges of the predictor space always have the highest leverage values.
In this case, none of the observations look particularly extreme in the points dimension.
### Robust regression
The ordinary least-squares estimator (@eq-ols) is fragile --- a single anomalous observation with high leverage can arbitrarily distort the fitted regression line, pulling it toward itself.
When this happens, the anomalous observation ends up with a smaller residual and so may not be flagged.
This is known as **masking**, and occurs when the presence of anomalies distorts the fitted model enough that the anomalies are undetected.
Robust regression methods address this by producing an estimate of $\bm{\beta}$ that remains stable even when a fraction of the observations are anomalous.
For example, the **least trimmed squares** (LTS) estimator [@Rousseeuw2003-ip] minimises the sum of the $h$ smallest squared residuals,
$$
\hat{\bm{\beta}}_{\text{LTS}}
= \mathop{\arg\min}_{\bm{\beta}} \sum_{i=1}^{h} e_{(i)}^2,
$$
where $e_{(1)}^2 \le e_{(2)}^2 \le \cdots \le e_{(n)}^2$ are the squared residuals in increasing order, and $h = \lfloor n/2 \rfloor + \lfloor (p + 1)/2 \rfloor$.
Observations with squared residuals beyond the $h$th smallest are effectively discarded.^[The OLS estimate given in @eq-ols is equivalent to setting $h = n$.]
This choice of $h$ gives a "breakdown point" of approximately 50%, meaning the estimated $\bm{\beta}$ cannot be pulled arbitrarily far from its true value even when nearly half the observations are anomalous.
Residuals from the LTS fit can then be used to identify anomalies, since the fit is not drawn toward them.
In R, `robustbase::ltsReg()` fits the LTS model using an efficient numerical algorithm [@robustbase].
An alternative approach that achieves similar robustness at lower computational cost is the BACON algorithm, which is discussed in @sec-bacon-reg.
Other robust regression methods are also available in the **`robustbase`** package.
For now, we will continue to use the OLS approach, as it makes many calculations much easier, but be aware that some anomalies can be masked.
## Regression residuals {#sec-residuals}
### Standardised residuals
The variance of the residuals depends on the predictor values, so we usually need to standardise them.
Standardised residuals are obtained by dividing each residual by its estimated standard deviation, giving
$$
r_i = \frac{e_i}{\hat{\sigma}\sqrt{1 - h_i}}, \qquad i = 1,\dots, n,
$$
where $h_i$ is the leverage (@eq-leverage) and
$$
\hat\sigma^2 = \frac{1}{n - p}\sum_{i=1}^n e_i^2
$$ {#eq-residual-variance}
is the estimated residual variance.
The `broom::augment()` function also computes the residuals (named `.resid`), and the standardised residuals (named `.std.resid`).
We can think of the standardised residuals as adjusted response values, after accounting for the predictor variables.
The simplest regression-based anomaly detection method looks for anomalies in these standardised residuals, rather than in the response values directly.
We could apply any of the methods considered in earlier chapters to the standardised residuals.
However, if there are anomalies, they can distort the estimated model, making anomaly detection more difficult.
### LOO residuals
The leave-one-out (LOO) residual for the $i$th observation is defined as the difference between $y_i$ and the predicted value obtained using a model fitted to all observations except the $i$th observation.
In this context, LOO residuals are often called PRESS (prediction error sum of squares) residuals.
At first, it appears that calculating LOO residuals involves a lot of computation --- estimating $n$ separate models.
However, the leave-one-out residuals are easily obtained without actually having to re-estimate the model many times.
It can be shown [@Montgomery2012, Appendix C.7] that the LOO residuals are given by
$$
e_{-i} = e_{i}/(1 - h_{i}),
$$
where $e_{i}$ is the residual obtained from fitting the model to *all* observations, and $h_i$ is the corresponding leverage value.
Since $\text{Var}(e_i) = \sigma^2(1 - h_i)$ (the diagonal of $\text{Var}(\bm{e}) = \sigma^2(\bm{I} - \bm{H})$) and $e_{-i} = e_i/(1 - h_i)$, the variance of $e_{-i}$ is given by
$$
\frac{\text{Var}(e_i)}{(1 - h_i)^2} = \frac{\sigma^2}{1 - h_i},
$$
so (if we knew $\sigma$) we could standardise each LOO residual to obtain
$$
\frac{e_i / (1 - h_i)}{\sigma/\sqrt{1 - h_i}} = \frac{e_i}{\sigma \sqrt{1 - h_i}}.
$$
Of course, we don't know $\sigma$, so we need to estimate it.
To reduce the effect of anomalies on the estimate of $\sigma$, we consider again the leave-one-out models.
If we leave out the $i$th observation, and fit a regression model to the remaining observations, then the estimated variance of the residuals is given by [@Montgomery2012, Appendix C.8]
$$
\hat\sigma_{-i}^2
= \frac{1}{n - p - 1}\left[ (n - p)\hat\sigma^2 - e_{i}^2/(1 - h_i) \right],
$$
where $\hat\sigma^2$ is given by @eq-residual-variance.
The corresponding standard deviations $\hat\sigma_{-i}$ are computed by `broom::augment()` and are returned in the column `.sigma`.
Thus, the standardised LOO residuals (also known as **externally studentised residuals**) are given by
$$
r_{-i} = \frac{e_i}{\hat\sigma_{-i} \sqrt{1 - h_i}}.
$$
### Cook's distance
Another useful "leave-one-out" measure is Cook's distance [@Cook1977], which measures how much all $n$ fitted values change when observation $i$ is omitted:
$$
D_i
= \frac{(\hat{\bm{y}} - \hat{\bm{y}}_{-i})^\intercal (\hat{\bm{y}} - \hat{\bm{y}}_{-i})}{p\hat\sigma^2},
$$
where $\hat{\bm{y}}_{-i}$ are the fitted values from the model omitting observation $i$.
As with the LOO residual, this can be computed without refitting the model $n$ times.
It can be shown that
$$
D_i = \frac{r_i^2h_i}{p(1 - h_i)},
$$ {#eq-cooks-distance}
where $r_i$ is the standardised residual and $h_i$ is the leverage.
From @eq-cooks-distance, an observation has a large Cook's distance when it combines a large residual (anomalous response given its predictors) with high leverage (extreme position in predictor space); a large value of one is not enough if the other is close to zero.
Cook's distance therefore measures *influence* on the model rather than response anomaly alone.
The `broom::augment()` function returns Cook's distances in the `.cooksd` column.
### Example: Shiraz reviews
The various types of residuals for the Shiraz reviews model are shown below.
```{r}
#| label: shiraz-residuals
#| code-fold: false
#| dependson: wine_aug
wine_aug <- wine_aug |>
mutate(std_loo_resid = .resid / .sigma / sqrt(1 - .hat)) |>
select(country:price, .resid, .std.resid, std_loo_resid)
wine_aug
```
In this example, the standardised residuals and the standardised LOO residuals are very similar, as the sample size is large, so leaving out one observation has little effect on the estimated residual standard deviation.
The standardised LOO residuals from this model are shown in @fig-shiraz-residuals.
```{r}
#| label: fig-shiraz-residuals
#| fig-cap: Standardised LOO residuals from a least-squares regression of log price on points for Shiraz wines.
#| dependson: shiraz-residuals
wine_aug |>
ggplot(aes(x = points, y = std_loo_resid)) +
geom_jitter(height = 0, width = 0.1, alpha = 0.5, colour = "#999999") +
geom_hline(yintercept = 0) +
labs(x = "Points", y = "Standardised LOO residuals")
```
Wines with large positive residuals are more expensive than expected for their points score, while wines with large negative residuals are cheaper than expected.
Both distance-based and density-based methods can be applied to the standardised residuals (or standardised LOO residuals) to identify observations with unusual response values given the corresponding predictor values.
The next two sections discuss using density-based surprisals to find anomalous residuals.
Then @sec-bacon-reg discusses a variation of the distance-based BACON algorithm for regression.
The other methods described in @sec-distance-methods and @sec-density-methods can also be applied to residuals, although these applications are not discussed here.
## Linear regression surprisals {#sec-regression-log-scores}
The surprisal approach (@sec-density-methods) extends naturally to regression by specifying a density for the residuals, then computing the surprisal of each observation under that density.
Specifying a density for the residuals is equivalent to specifying a **conditional density** for the response given the predictors,
$$
f(y \mid \bm{x}).
$$
The most common choice is to assume the residuals are Normally distributed, giving the conditional distribution
$$
y \mid \bm{x} \sim \text{N}(\bm{x}^\intercal\bm{\beta}, \sigma^2).
$$ {#eq-gaussian-regression}
Note that this does *not* mean that $y$ is Normally distributed, or that $\bm{x}$ has a Normal distribution.
The LOO surprisals under this model are computed from the standardised LOO residuals $r_{-i}$:
$$
s_{-i} = -\log\phi(r_{-i}),
$$
where $\phi(u) = (2\pi)^{-1/2}e^{-u^2/2}$ is the standard Normal density.
### Example: Shiraz reviews
We return to the Shiraz wine reviews introduced in @sec-ols.
Now that we have added a distributional assumption, the fitted model can be written as
$$
\log(\text{Price}) \mid \text{Points} \sim \text{N}(`r sprintf("%.3f",coef(fit_wine)[1])` + `r sprintf("%.3f",coef(fit_wine)[2])` \times \text{Points}, `r sprintf("%.3f",sigma(fit_wine))`^2),
$$
and we can compute 95% prediction intervals as shown in @fig-shiraz-regression-density.
```{r}
#| label: fig-shiraz-regression-density
#| warning: false
#| dependson: shiraz-regression
#| fig-cap: Log price of Shiraz as a function of points, with 95% prediction intervals.
#| The points are horizontally jittered to reduce overplotting.
#| Points outside the prediction intervals are coloured.
wine_aug <- broom::augment(fit_wine, data = shiraz, interval = "prediction") |>
mutate(
lwr = exp(.lower),
upr = exp(.upper),
location = case_when(
price < lwr ~ "below",
price > upr ~ "above",
TRUE ~ "within"
)
)
wine_aug |>
ggplot(aes(y = price, x = points, col = location)) +
geom_jitter(height = 0, width = 0.1, alpha = 0.5) +
geom_ribbon(aes(ymin = lwr, ymax = upr), fill = "#cccccc", alpha = 0.25) +
geom_line(aes(y = exp(.fitted)), colour = "#666666") +
scale_y_log10() +
guides(fill = "none", col = "none") +
scale_colour_manual(values = c("#0072B2", "#D55E00", "#AAAAAA"))
```
The LOO surprisals are computed from the standardised LOO residuals using the standard Normal density.
```{r}
#| label: shiraz-loo-surprisals
#| code-fold: false
#| dependson: fig-shiraz-regression-density
wine_aug <- wine_aug |>
mutate(
std_loo_res = .resid / (.sigma * sqrt(1 - .hat)),
loo_surprisals = -dnorm(std_loo_res, log = TRUE)
)
```
They are shown in @fig-shiraz-regression-scores, using the same colours as @fig-shiraz-regression-density to indicate whether the observation is below, within, or above the 95% prediction interval.
```{r}
#| label: fig-shiraz-regression-scores
#| dependson: shiraz-loo-surprisals
#| fig-cap: Standardised LOO residuals and LOO surprisals for the Shiraz data using a linear regression model.
#| Points are coloured to match the 95% prediction intervals in @fig-shiraz-regression-density.
#| fig-height: 6
#| fig-asp: 0.8
wine_aug |>
select(points, std_loo_res, loo_surprisals, location) |>
tidyr::pivot_longer(
c(std_loo_res, loo_surprisals),
names_to = "variable",
values_to = "value"
) |>
mutate(
variable = factor(
variable,
levels = c("std_loo_res", "loo_surprisals"),
label = c("Standardised LOO residuals", "LOO surprisals")
)
) |>
ggplot(aes(x = points, y = value, col = location)) +
facet_grid(variable ~ ., scales = "free_y") +
geom_jitter(height = 0, width = 0.1, alpha = 0.5) +
geom_hline(yintercept = 0, colour = "#666666") +
labs(x = "Points", y = "") +
guides(fill = "none", col = "none") +
scale_colour_manual(values = c("#0072B2", "#D55E00", "#AAAAAA"))
```
```{r}
#| label: shiraz-regression-scores
#| include: false
#| dependson: shiraz-loo-surprisals
most_anomalous <- wine_aug |>
filter(loo_surprisals > 17)
underpriced <- wine_aug |>
filter(std_loo_res == min(std_loo_res))
good_buy <- wine_aug |>
filter(points > 95) |>
filter(std_loo_res == min(std_loo_res))
```
The over-priced wines under this model are shown in blue, while the under-priced wines are shown in orange.
This shows that the most anomalous observations are the two with LOO surprisals above 17, and standardised residuals close to 6.
The largest LOO surprisal is for the most over-priced wine (under this model), a 2009 Shiraz from the Henschke winery in the Eden Valley region of South Australia, with `r most_anomalous$points[1]` points and a price of \$`r most_anomalous$price[1]`.
```{r}
#| label: shiraz-most-anomalous
#| code-fold: false
#| dependson: shiraz-loo-surprisals
wine_aug |>
filter(loo_surprisals == max(loo_surprisals)) |>
select(country:winery, year, points, price, std_loo_res, loo_surprisals)
```
The largest LOO surprisal corresponding to an under-priced wine is for the wine with the lowest residual value, with `r underpriced$points[1]` points and a price of \$`r underpriced$price[1]`.
Another good buy, at the higher quality end, is the 2007 Syrah from the Rulo winery in the Columbia Valley in Washington State, USA:
```{r}
#| label: shiraz-good-buy
#| code-fold: false
#| dependson: shiraz-loo-surprisals
wine_aug |>
filter(points > 95) |>
filter(std_loo_res == min(std_loo_res)) |>
select(country:winery, year, points:price, std_loo_res, loo_surprisals)
```
This corresponds to the only orange point in @fig-shiraz-regression-density that has a points score above 95 and a price below the 95% prediction interval.
### Surprisal probabilities
We will compute the surprisal probabilities using the rank approximation (@sec-approximate-surprisal-prob).
```{r}
#| label: shiraz-surprisal-prob-manual
#| code-fold: false
#| dependson: shiraz-loo-surprisals
wine_aug |>
mutate(
prob = (NROW(wine_aug) - rank(loo_surprisals, ties.method = "min") + 1) /
NROW(wine_aug)
) |>
select(country:winery, year, points, price, loo_surprisals, prob) |>
arrange(prob)
```
Those with the ten smallest surprisal probabilities are all wines that appear to be over-priced given their points values.
The preceding analysis shows the calculations of surprisal probabilities in detail.
They can be more simply computed using `surprisals_prob()` applied directly to the fitted model, as follows.
```{r}
#| label: shiraz-surprisals
#| code-fold: false
#| dependson: shiraz-regression
shiraz <- shiraz |>
mutate(prob = surprisals_prob(fit_wine, loo = TRUE, approximation = "rank"))
shiraz |>
select(country:winery, year, points, price, prob) |>
arrange(prob)
```
@fig-shiraz-surprisal shows the relationship between points and price, with the points coloured according to the surprisal probability.
The nine orange points are observations with surprisal probabilities less than 0.002 (two are almost overlapping).
```{r}
#| label: fig-shiraz-surprisal
#| dependson: shiraz-surprisals
#| fig-cap: Price vs points for Shiraz wines.
#| Points are coloured according to the surprisal probability.
#| The nine orange points are observations with surprisal probabilities less than 0.002.
shiraz |>
ggplot(aes(x = points, y = price, colour = prob < 0.002)) +
geom_jitter(height = 0, width = 0.2) +
scale_y_log10() +
scale_colour_manual(values = c("FALSE" = "grey70", "TRUE" = "#D55E00"))
```
```{r}
#| include: false
#| label: shiraz-check
#| dependson: shiraz-surprisals
shiraz_surprise <- shiraz |> filter(prob < 0.002)
if (NROW(shiraz_surprise) != 9L) {
stop("Something is wrong here.")
}
```
This shows the value of computing surprisal probabilities on the conditional distribution.
The nine observations are not simply those with the highest prices, but those whose price is anomalous given their points values.
There are two wines with prices above \$300 that are not identified as anomalous, because their prices are less extreme given their points values (their surprisal probabilities lie between 0.002 and 0.003).
```{r}
#| label: shiraz-expensive-check
#| include: false
#| dependson: shiraz-surprisals
expensive_missed <- shiraz |> filter(price > 300, prob >= 0.002)
stopifnot(NROW(expensive_missed) == 2L, all(expensive_missed$prob < 0.003))
```
## GAM surprisals {#sec-gam-surprisals}
In some applications, it is not appropriate to assume the conditional density is Normal, or that the relationships are linear.
One useful model that allows for non-Normal densities, and non-linear relationships, is a generalised additive model or GAM.
Under this model, the conditional density is given by [@Wood2017gam]
$$
y \mid \bm{x} \sim f(\mu, \bm{\theta}), \qquad \ell(\mu) = \sum_{k=1}^p g_k(x_{k}),
$$
where $\mu = \text{E}(y \mid \bm{x})$ denotes the conditional mean, $\bm{\theta}$ is a vector of any other parameters, $\ell()$ is a link function (mapping the mean to an unbounded scale), and each $g_k$ function is smooth.
If $f$ is Normal, $\bm{\theta} = \sigma^2$, $\ell$ is the identity, and $g_k(u) = \beta_k u$, then this reduces to the linear Normal model (@eq-gaussian-regression).
### Example: Cricket not-outs
```{r}
#| label: cricket-setup
#| include: false
df_no <- cricket_batting |>
filter(Innings > 0, Gender == "Men") |>
mutate(prop_no = NotOuts / Innings)
p <- sum(df_no$NotOuts) / sum(df_no$Innings)
```
Consider the number of "not-outs" for each male batter in the `cricket_batting` data set who has batted at least once.
A "not-out" occurs when a batter has not been dismissed at the end of the team's innings.
This can occur when the other ten batters have been dismissed (as the last batter cannot continue alone), or when the innings ends for some other reason (e.g., the captain declares the innings ended, or the team reaches its target and wins).
Let's consider if there are some batters who have an unusually high proportion of not-outs.
The data set contains results from `r sum(df_no$Innings)` innings, of which `r sum(df_no$NotOuts)` were not-outs.
So the overall proportion of not-outs is $`r sum(df_no[["NotOuts"]])` / `r sum(df_no[["Innings"]])` = `r sprintf("%.3f", p)`$.
Players who bat first in the batting order are more likely to be dismissed than those who bat last, simply because there is more time for them to be dismissed.
Unfortunately the data set does not include information about the position in which each player usually batted, so we can't use batting order directly.
However, the best batters tend to bat early in the order, leaving the most unskilled batters (who are usually specialist bowlers) to bat last.
A measure of a batter's skill is the number of runs they scored per innings (RPI), also known as the uncensored batting average.
This is slightly different from the conventional batting average, which is the total number of runs scored divided by the number of times a batter has been dismissed.^[The uncensored batting average is used here so that it is not directly affected by the number of not-outs for each batter, which is the response variable in the fitted model.]
@fig-notouts shows the proportion of not-outs for each batter, plotted against their RPI.
The relationship is slightly U-shaped, due to two different mechanisms.
Weaker batters (with an RPI below 25) typically bat near the end of the batting order, so they are disproportionately likely to be the "last man standing", which inflates their not-out proportion.
At the high end (RPI above about 40), a different mechanism applies: the best batters are harder to dismiss, so they often survive longer than weaker batters.
Batters with moderate RPIs (25--40) benefit from neither mechanism, so they have the lowest not-out proportions of all.
```{r}
#| label: fig-notouts
#| fig-cap: >-
#| Proportion of not-outs for each batter as a function of their runs per innings.
#| Batters with few innings (fewer than 20) are shown in grey, to highlight the pattern from batters with more innings, shown in blue.
#| message: false
#| code-fold: true
df_no <- cricket_batting |>
filter(Innings > 0, Gender == "Men") |>
mutate(
prop_no = NotOuts / Innings,
RPI = Runs / Innings
) |>
arrange(Innings)
df_no |>
ggplot(
aes(
x = RPI,
y = prop_no,
colour = Innings >= 20
)
) +
geom_point() +
scale_colour_manual(values = c("FALSE" = "grey70", "TRUE" = "#0072B2")) +
labs(y = "Proportion of not-outs", x = "Runs per innings") +
guides(alpha = "none")
```
The unusual horizontal patterns in the grey points are due to the discrete nature of the data --- batters who have played only two innings must have a not-out proportion of either 0, 1/2, or 1, while those who have played only three innings must have a not-out proportion of either 0, 1/3, 2/3, or 1, and so on.
As the number of innings played goes up, more not-out proportions become possible.
We also expect that the pattern of not-outs has changed over time.
Test cricket has been played for almost 150 years, and the style of play and the nature of playing conditions have changed considerably over that time.
Modern players tend to be more aggressive, and the pitches tend to be in better condition (and easier to bat on), than in earlier eras.
To take all this into account, we can construct a GAM for the number of not-outs for each batter as a function of their RPI and the year they started playing.
It is natural to use a Binomial distribution with a logit link function:
$$
\text{NotOuts} \mid \text{RPI}, \text{Start} \sim \text{Binomial}(\text{Innings},~ q),
$$
where $q$ denotes the probability of a batter not being dismissed in an innings, and
$$
\log(q/(1 - q)) = g_1(\text{RPI}) + g_2(\text{Start}).
$$ {#eq-gam-notouts}
We can fit this model using the **`mgcv`** package, with the resulting estimates shown in @fig-gam-notouts.
```{r}
#| label: notouts-gam
#| message: false
#| code-fold: false
#| dependson: fig-notouts
fit_notouts <- mgcv::gam(
prop_no ~ s(RPI) + s(Start),
data = df_no,
weights = Innings,
family = binomial(link = logit)
)
```
```{r}
#| label: fig-gam-notouts
#| fig-cap: "Estimated values of $g_1$ and $g_2$ from @eq-gam-notouts, with 95% confidence intervals."
#| code-fold: false
#| fig-height: 3.35
#| dependson: notouts-gam
gratia::draw(fit_notouts)
```
As expected, the probability of being not out decreases as the RPI increases to about 30, and then increases again for the very best batters.
The confidence interval on the curve is very wide after about 50, as there are very few batters with RPIs that high.
The probability of being not out also increases as the year of debut increases, until about 1975, and then decreases again.
This is likely due to the introduction of limited-overs cricket in the 1970s, which changed the style of play in Test cricket, and batters have since become more aggressive.
Now we can use the fitted model to compute the surprisals from the Binomial distribution, and find the most anomalous batters.
Unfortunately, there is not a convenient way to compute LOO surprisals for GAM models, so we will only consider regular surprisals in this example.
While the Binomial distribution is probably a good first approximation, it does assume that the probability of a batter being dismissed does not change over their career, which is an unrealistic assumption as it does not allow for the development of skill, the value of experience, or the effect of ageing.
So we will use the GPD approximation (@sec-approximate-surprisal-prob) to compute the surprisal probabilities, which allows for some mis-specification in the distribution of not-outs.
```{r}
#| code-fold: false
#| warning: false
#| label: notouts_aug
#| dependson: notouts-gam
notouts_aug <- augment(fit_notouts, data = df_no, type.predict = "response") |>
mutate(p = surprisals_prob(fit_notouts, approximation = "gpd")) |>
select(Player:End, Innings, NotOuts, RPI, .fitted, prop_no, p) |>
arrange(p)
notouts_aug
```
The `.fitted` value is the expected proportion of not-outs for each player under the fitted model, while `prop_no` gives the actual proportion of not-outs they have had.
The largest surprisal is for South African Shaun Pollock, who had `r notouts_aug$NotOuts[1]` not-outs in `r notouts_aug$Innings[1]` innings, which is much higher than the expected number of not-outs of $`r notouts_aug[["Innings"]][1]` \times `r sprintf("%.3f", notouts_aug[[".fitted"]][1])` = `r sprintf("%.1f", notouts_aug[[".fitted"]][1]*notouts_aug[["Innings"]][1])`$.
Shaun Pollock was a bowling all-rounder and a capable lower-order batter who built partnerships with the weakest batters.
The next most anomalous result is for New Zealander Trent Boult, a specialist bowler who batted last, who for a while was Test cricket's leading run-scorer in that position, showing an unusual flair for entertaining batting.
He had `r notouts_aug$NotOuts[2]` not-outs in `r notouts_aug$Innings[2]` innings, compared to the expected number of not-outs of $`r notouts_aug[["Innings"]][2]` \times `r sprintf("%.3f", notouts_aug[[".fitted"]][2])` = `r sprintf("%.1f", notouts_aug[[".fitted"]][2]*notouts_aug[["Innings"]][2])`$.
Neither batter's proportion of not-outs is exceptional by itself (`r english::words(sum(df_no$Innings >= 20 & df_no$prop_no > notouts_aug$prop_no[2]))` batters with at least 20 innings have a higher proportion than Boult), but they become anomalous once their RPI and year of debut are taken into account.
Because we have used a statistical model, we have been able to account for the particular features of this data set, such as the discrete nature of the data, and the changing variance, to identify observations that are anomalous in the context of the model.
## BACON algorithm for linear regression {#sec-bacon-reg}
In the regression version of the BACON algorithm [@Billor2000], the goal is to identify observations that are inconsistent with the regression model.
This is more complicated than the multivariate case discussed in @sec-bacon, because an observation can be anomalous in terms of its predictor values, or in terms of its response value given its predictor values, or both.
Cook's distance (@sec-residuals) captures both of these sources of influence but does not protect against masking.
Also, high leverage values can lead to residual anomalies being masked.
Like the LTS estimator (@sec-ols), BACON addresses masking by fitting the model to a subset of regular observations rather than to all the data.
Unlike LTS, which selects the subset by minimising trimmed residuals, BACON builds the subset sequentially, making it computationally efficient for large data sets.
The regression BACON algorithm begins by using the multivariate BACON algorithm on the predictors, and then uses scaled prediction errors to decide which observations are compatible with the regression model.
Let $B$ be the current basic subset, with $r$ observations, and let $\bm{X}_B$ and $\bm{y}_B$ denote the corresponding predictor matrix and response vector.
Let $\hat{\bm{\beta}}_B$ be the least-squares estimate computed using only the observations in $B$, and let
$$
\hat{\sigma}_B^2
= (r - p)^{-1}\sum_{i \in B}(y_i - \bm{x}_i^\intercal\hat{\bm{\beta}}_B)^2
$$
be the corresponding estimate of residual variance.
The leverage of observation $i$ with respect to the basic subset $B$ is
$$
h_i(B) = \bm{x}_i^\intercal(\bm{X}_B^\intercal\bm{X}_B)^{-1}\bm{x}_i.
$$
The regression discrepancy for observation $i$ is the absolute scaled residual or prediction error
$$
|t_i(B)| = \begin{cases}
\displaystyle
\left| \frac{y_i - \bm{x}_i^\intercal\hat{\bm{\beta}}_B}{\hat{\sigma}_B\sqrt{1 - h_i(B)}} \right|, & i \in B, \\
\displaystyle
\left| \frac{y_i - \bm{x}_i^\intercal\hat{\bm{\beta}}_B}{\hat{\sigma}_B\sqrt{1 + h_i(B)}} \right|, & i \notin B.
\end{cases}
$$
For observations already in the basic subset this is the usual standardised residual.
For observations outside the basic subset it is a scaled prediction error.
The sign difference arises because $1 - h_i(B)$ is the variance deflation for an in-sample residual, while $1 + h_i(B)$ is the corresponding variance inflation for an out-of-sample prediction error; an observation not used to fit the model contributes additional uncertainty beyond that of the residual variance alone.
The algorithm then proceeds as follows.
**Step 1: Initialise the basic subset.** Apply the multivariate BACON algorithm (@sec-bacon) to the predictor variables, ignoring the response, starting from an initial subset of size $s$.
This identifies observations with central predictor values and protects the first regression fit from high-leverage points.
These observations are then used to construct a full-rank initial regression subset, which is grown using the smallest scaled prediction errors until it contains approximately $cp$ observations, where $c$ is usually 4 or 5.
Larger initial subsets (larger $s$ or $c$) may be needed if the predictor variables have many repeated values, as then the initial subsets may contain too few distinct predictor values, giving a singular covariance matrix or a low-rank predictor matrix $\bm{X}_B$.
**Step 2: Fit the regression model.** Fit least squares to the current basic subset $B$, obtaining $\hat{\bm{\beta}}_B$ and $\hat{\sigma}_B$.
**Step 3: Compute discrepancies.** Compute $|t_i(B)|$ for every observation, using the formula above.
**Step 4: Expand the basic subset.** Update $B$ by admitting every observation with
$$
|t_i(B)| < \text{t}_{r-p,\,1-\alpha/(2(r+1))},
$$
where $\text{t}_{r-p,\,1-\alpha/(2(r+1))}$ is the $(1 - \alpha/(2(r + 1)))$ quantile of a t-distribution with $r - p$ degrees of freedom.
Equivalently, this is the upper $(\alpha/(2(r + 1)))$ tail quantile, as computed in R by `qt(alpha / (2 * (r + 1)), r - p, lower.tail = FALSE)`.
**Step 5: Iterate.** Repeat Steps 2--4 until the size of $B$ no longer changes.
**Step 6: Nominate outliers.** Observations excluded from the final basic subset are nominated as regression outliers.
As in the multivariate version, the algorithm grows the basic subset in blocks, rather than adding one observation at a time.
It gives a robust regression fit at relatively low computational cost.
The final values $|t_i(B)|$ provide anomaly scores: large values correspond to observations whose responses are unusually far from what would be predicted by the regression relationship fitted to the final basic subset.
```{r}
#| label: shiraz-points
#| echo: false
#| dependson: shiraz-surprisals
shiraz_points <- shiraz |> count(points) |> arrange(desc(n))
```
### Example: Shiraz reviews
We now apply regression BACON to the same `shiraz` data set containing wine reviews that was used in @sec-ols, with `points` as the predictor and `log(price)` as the response.
Multivariate BACON is first applied to the predictor variable.
Because the predictor has many repeated values (taking only integer values between 80 and 100), we need to specify the initial set to be larger than the number of observations with the most common points score, which is `r shiraz_points$points[1]` with `r shiraz_points$n[1]` observations.
So we set the initial size of the multivariate BACON subset to $s = 650$ observations to ensure it does not contain only observations with a single points score (with the default initial size, the subset collapses onto a single points score and its covariance matrix is singular).
The BACON algorithm then identifies outliers as those with large scaled prediction errors from the fitted regression line based on the final basic subset.
This initial size $s$ is set using the `m` argument of `robustX::BACON()` below.
```{r}
#| label: shiraz-bacon
#| code-fold: false
#| dependson: ["shiraz-loo-surprisals", "shiraz-surprisals"]
bacon_alpha <- 0.05
bacon_wine <- robustX::BACON(
x = shiraz$points,
y = log(shiraz$price),
m = 650,
alpha = bacon_alpha,
verbose = FALSE
)
wine_bacon <- wine_aug |>
mutate(
bacon_distance = bacon_wine$tis,
bacon_outlier = !bacon_wine$subset,
bacon_x_outlier = !bacon_wine$mv.subset
)
tibble(
observations = nrow(wine_bacon),
predictor_outliers = sum(wine_bacon$bacon_x_outlier),
regression_outliers = sum(wine_bacon$bacon_outlier),
mv_steps = bacon_wine$steps["mv"],
regression_steps = bacon_wine$steps["lm"]
)
```
No predictor outliers are identified by the multivariate BACON algorithm, as all observations have points scores that are close to those of many other observations.
However, `r english::words(sum(wine_bacon$bacon_outlier))` regression outliers are identified by the regression BACON algorithm, as their prices are inconsistent with the fitted price--points relationship.
```{r}
#| label: bacon-check2
#| include: false
#| dependson: shiraz-bacon
stopifnot(
sum(wine_bacon$bacon_x_outlier) == 0,
650 > shiraz_points$n[1],
setequal(which(wine_bacon$bacon_outlier), which(shiraz$prob < 0.002))
)
```
The largest BACON distances are shown below.
These correspond to wines with prices that are most unusual after accounting for their points score.
```{r}
#| label: shiraz-bacon-largest
#| code-fold: false
#| dependson: shiraz-bacon
wine_bacon |>
filter(bacon_outlier) |>
arrange(desc(bacon_distance)) |>
select(country, winery, year, points, price, bacon_distance)
```
These are the same nine wines that have surprisal probabilities less than 0.002 under the linear regression model (@sec-regression-log-scores).
To see the effect of the anomalies on the fitted regression relationship, we refit the least-squares model using only the final BACON basic subset.
This gives the regression line shown in @fig-shiraz-bacon that is obtained after omitting the nominated regression outliers.
The two lines are almost identical because the nominated outliers are a tiny fraction of the `r NROW(wine_bacon)` observations, and none of them has high leverage (no observation in this data set has a leverage value above 0.003).
```{r}
#| label: shiraz-leverage-check
#| include: false
#| dependson: shiraz-bacon
stopifnot(max(wine_bacon$.hat) < 0.003)
```
```{r}
#| label: shiraz-bacon-fit
#| dependson: shiraz-bacon
#| echo: true
#| code-fold: false
fit_bacon_wine <- lm(
log(price) ~ points,
data = wine_bacon,
subset = !bacon_outlier
)
```
```{r}
#| label: fig-shiraz-bacon
#| fig-cap: >-
#| Regression BACON applied to Shiraz wine reviews.
#| Points in orange are nominated regression outliers.
#| The dashed line is the ordinary least-squares fit using all observations, while the solid line is the least-squares fit after omitting BACON-nominated outliers.
#| warning: false
#| dependson: shiraz-bacon-fit
wine_grid <- tibble(points = range(wine_bacon$points)) |>
mutate(
least_squares = exp(predict(fit_wine, newdata = pick(everything()))),
bacon = exp(predict(fit_bacon_wine, newdata = pick(everything())))
)
wine_bacon |>
ggplot(aes(y = price, x = points)) +
geom_jitter(
aes(colour = bacon_outlier),
height = 0,
width = 0.1,
alpha = 0.6
) +
geom_line(
data = wine_grid,
aes(x = points, y = least_squares, linetype = "Least squares"),
inherit.aes = FALSE
) +
geom_line(
data = wine_grid,
aes(x = points, y = bacon, linetype = "BACON subset"),
inherit.aes = FALSE
) +
scale_y_log10() +
scale_colour_manual(
values = c("FALSE" = "#999999", "TRUE" = "#D55E00")
) +
scale_linetype_manual(
values = c("Least squares" = "dashed", "BACON subset" = "solid")
) +
labs(x = "Points", y = "Price", linetype = "Fit") +
guides(colour = "none")
```
Finally, @fig-shiraz-bacon-distance shows the absolute scaled prediction errors used by the regression BACON algorithm.
The dashed horizontal line is the final $t$ cutoff.
Observations above this line are those excluded from the final basic subset.
```{r}
#| label: fig-shiraz-bacon-distance
#| fig-cap: >-
#| Absolute scaled prediction errors from regression BACON for Shiraz wine reviews.
#| The dashed line shows the final cutoff used to nominate regression outliers.
#| dependson: shiraz-bacon-fit
regression_p <- length(coef(fit_bacon_wine))
regression_r <- sum(bacon_wine$subset)
bacon_wine_limit <- qt(
bacon_alpha / (2 * (regression_r + 1)),
df = regression_r - regression_p,
lower.tail = FALSE
)
wine_bacon |>
ggplot(aes(x = points, y = bacon_distance, colour = bacon_outlier)) +
geom_jitter(height = 0, width = 0.1, alpha = 0.6) +
geom_hline(yintercept = bacon_wine_limit, linetype = "dashed") +
scale_colour_manual(
values = c("FALSE" = "#999999", "TRUE" = "#D55E00")
) +
labs(x = "Points", y = "Absolute scaled prediction error") +
guides(colour = "none")
```
## Summary {#sec-regression-summary}
Regression methods look for observations whose response is unusual given the values of the predictors, rather than observations that are unusual in themselves.
The key idea is to work with the conditional distribution of the response given the predictors.
The simplest approach is to fit a regression model and look for anomalies in the residuals, after standardising them to allow for their different variances.
Leave-one-out residuals, which can be computed without refitting the model, prevent each observation from influencing its own fitted value.
Leverage and Cook's distance are useful diagnostics, but they measure the influence of an observation on the fitted model rather than whether its response is anomalous.
Because least squares estimates can be pulled towards anomalous observations with high leverage, anomalies can be masked; robust methods such as least trimmed squares or the regression version of the BACON algorithm avoid this by fitting the model to a subset of regular observations.
Specifying a conditional density for the response turns the residuals into surprisals.
The surprisal probabilities of @sec-density-methods then provide a natural threshold for identifying anomalies.
A linear model with Normal errors is the simplest choice.
When the conditional distribution is not Normal, or the relationships are not linear, a generalised additive model can be used instead, allowing for other response distributions (such as Binomial counts) and smooth nonlinear effects of the predictors.
Where a model is mis-specified, the GPD approximation to the surprisal probabilities still gives reasonable estimates for the most extreme observations.