Skip to main content

8  Regression methods

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.

8.1 Linear regression

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 (Section A.7), the model can be estimated using ordinary least squares (OLS) regression (Seber & Lee, 2003), resulting in the estimate \hat{\bm{\beta}} = (\bm{X}^\intercal\bm{X})^{-1}\bm{X}^\intercal\bm{y}. \tag{8.1} 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, \tag{8.2} take values between 0 and 1. These are known as the leverage values (Faraway, 2014, p69), 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 Figure 1.5. 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.

wine_reviews <- fetch_wine_reviews()
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)
# A tibble: 2 × 5
  term        estimate std.error statistic   p.value
  <chr>          <dbl>     <dbl>     <dbl>     <dbl>
1 (Intercept)   -6.12    0.206       -29.7 2.58e-177
2 points         0.108   0.00231      46.7 0        
broom::glance(fit_wine)
# A tibble: 1 × 12
  r.squared adj.r.squared sigma statistic p.value    df logLik   AIC   BIC deviance
      <dbl>         <dbl> <dbl>     <dbl>   <dbl> <dbl>  <dbl> <dbl> <dbl>    <dbl>
1     0.324         0.323 0.484     2177.       0     1 -3157. 6320. 6339.    1067.
# ℹ 2 more variables: df.residual <int>, nobs <int>

The fitted model can be written as \log(\text{Price}) = -6.115 + 0.108 \times \text{Points} + \varepsilon, where \varepsilon is a random error term with mean zero and variance 0.484^2.

The fitted regression line is shown in Figure 8.1.

wine_aug <- fit_wine |>
  broom::augment(data = shiraz)
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()
Figure 8.1: Log price of Shiraz as a function of points. The points are horizontally jittered to reduce overplotting.

Note that broom::augment() returns the fitted values as .fitted, and the leverage values as .hat.

wine_aug |>
  select(country:price, .hat) |>
  arrange(desc(.hat))
# A tibble: 4,553 × 8
   country   state            region          winery         year points price    .hat
   <chr>     <chr>            <chr>           <chr>         <dbl>  <dbl> <dbl>   <dbl>
 1 US        Washington       Columbia Valley Charles Smith  2006    100    80 0.00284
 2 US        Washington       Columbia Valley Cayuse         2008    100    80 0.00284
 3 US        Oregon           Oregon Other    Cayuse         2009     99    75 0.00237
 4 US        Oregon           Oregon Other    Cayuse         2011     99    75 0.00237
 5 Australia South Australia  South Australia Penfolds       2010     99   850 0.00237
 6 US        California       Central Coast   Four Vines     2005     80    18 0.00216
 7 US        California       Central Coast   San Simeon     2009     80    25 0.00216
 8 Australia South Australia  South Australia Red Knot       2007     80    12 0.00216
 9 Chile     Central Valley   <NA>            Corinto        2009     80    16 0.00216
10 Argentina Mendoza Province Mendoza         Caligiore      2006     80    15 0.00216
# ℹ 4,543 more rows

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 (Equation 8.1) 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 (Rousseeuw & Leroy, 2003) 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 hth smallest are effectively discarded.1 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 (Maechler et al., 2026). An alternative approach that achieves similar robustness at lower computational cost is the BACON algorithm, which is discussed in Section 8.5. 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.

8.2 Regression 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 (Equation 8.2) and \hat\sigma^2 = \frac{1}{n - p}\sum_{i=1}^n e_i^2 \tag{8.3} 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 ith observation is defined as the difference between y_i and the predicted value obtained using a model fitted to all observations except the ith 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 (Montgomery et al., 2021, 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 ith observation, and fit a regression model to the remaining observations, then the estimated variance of the residuals is given by (Montgomery et al., 2021, 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 Equation 8.3.

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 (Cook, 1977), 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)}, \tag{8.4} where r_i is the standardised residual and h_i is the leverage. From Equation 8.4, 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.

wine_aug <- wine_aug |>
  mutate(std_loo_resid = .resid / .sigma / sqrt(1 - .hat)) |>
  select(country:price, .resid, .std.resid, std_loo_resid)
wine_aug
# A tibble: 4,553 × 10
   country      state  region winery  year points price  .resid .std.resid std_loo_resid
   <chr>        <chr>  <chr>  <chr>  <dbl>  <dbl> <dbl>   <dbl>      <dbl>         <dbl>
 1 US           Calif… Centr… Rideau  2014     87    44  0.542       1.12          1.12 
 2 US           Calif… Centr… Alta …  2012     91    46  0.156       0.322         0.322
 3 US           Calif… Centr… Big B…  2013     91    36 -0.0894     -0.185        -0.185
 4 US           Calif… Sonoma Kenwo…  2005     88    25 -0.131      -0.271        -0.271
 5 Israel       Judea… <NA>   Yatir   2011     90    50  0.347       0.716         0.716
 6 Australia    South… South… Angov…  2006     85    12 -0.543      -1.12         -1.12 
 7 US           Calif… Centr… Testa…  2006     85    49  0.864       1.79          1.79 
 8 South Africa Stell… <NA>   Jardin  2007     89    19 -0.513      -1.06         -1.06 
 9 Australia    South… Baros… Kilik…  2009     92    70  0.468       0.967         0.967
10 New Zealand  Hawke… <NA>   Otto'…  2008     87    18 -0.352      -0.728        -0.728
# ℹ 4,543 more rows

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 Figure 8.2.

Code
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")
Figure 8.2: Standardised LOO residuals from a least-squares regression of log price on points for Shiraz wines.

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 Section 8.5 discusses a variation of the distance-based BACON algorithm for regression. The other methods described in Chapter 6 and Chapter 7 can also be applied to residuals, although these applications are not discussed here.

8.3 Linear regression surprisals

The surprisal approach (Chapter 7) 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). \tag{8.5} 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 Section 8.1. Now that we have added a distributional assumption, the fitted model can be written as \log(\text{Price}) \mid \text{Points} \sim \text{N}(-6.115 + 0.108 \times \text{Points}, 0.484^2), and we can compute 95% prediction intervals as shown in Figure 8.3.

Code
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"))
Figure 8.3: 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.

The LOO surprisals are computed from the standardised LOO residuals using the standard Normal 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 Figure 8.4, using the same colours as Figure 8.3 to indicate whether the observation is below, within, or above the 95% prediction interval.

Code
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"))
Figure 8.4: 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 Figure 8.3.

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 91 points and a price of $780.

wine_aug |>
  filter(loo_surprisals == max(loo_surprisals)) |>
  select(country:winery, year, points, price, std_loo_res, loo_surprisals)
# A tibble: 1 × 9
  country   state           region  winery  year points price std_loo_res loo_surprisals
  <chr>     <chr>           <chr>   <chr>  <dbl>  <dbl> <dbl>       <dbl>          <dbl>
1 Australia South Australia Eden V… Hensc…  2009     91   780        6.19           20.1

The largest LOO surprisal corresponding to an under-priced wine is for the wine with the lowest residual value, with 85 points and a price of $4. Another good buy, at the higher quality end, is the 2007 Syrah from the Rulo winery in the Columbia Valley in Washington State, USA:

wine_aug |>
  filter(points > 95) |>
  filter(std_loo_res == min(std_loo_res)) |>
  select(country:winery, year, points:price, std_loo_res, loo_surprisals)
# A tibble: 1 × 9
  country state      region         winery  year points price std_loo_res loo_surprisals
  <chr>   <chr>      <chr>          <chr>  <dbl>  <dbl> <dbl>       <dbl>          <dbl>
1 US      Washington Columbia Vall… Rulo    2007     96    20       -2.51           4.08

This corresponds to the only orange point in Figure 8.3 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 (Section 7.3).

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)
# A tibble: 4,553 × 9
   country   state           region     winery  year points price loo_surprisals    prob
   <chr>     <chr>           <chr>      <chr>  <dbl>  <dbl> <dbl>          <dbl>   <dbl>
 1 Australia South Australia Eden Vall… Hensc…  2009     91   780          20.1  2.20e-4
 2 US        California      Central C… Law     2013     92   750          18.3  4.39e-4
 3 Australia South Australia Eden Vall… Hensc…  2010     96   820          14.3  6.59e-4
 4 Australia South Australia South Aus… Penfo…  2008     98   850          12.5  8.79e-4
 5 Italy     Tuscany         Toscana    Tua R…  2011     89   300          11.7  1.10e-3
 6 Australia South Australia South Aus… Penfo…  2010     99   850          11.4  1.32e-3
 7 Italy     Tuscany         Toscana    Tua R…  2013     90   300          10.7  1.76e-3
 8 Italy     Tuscany         Toscana    Tua R…  2012     90   300          10.7  1.76e-3
 9 France    Rhône Valley    Côte Rôtie Domai…  2013     93   391          10.2  1.98e-3
10 Australia South Australia South Aus… Penfo…  2004     96   500           9.53 2.20e-3
# ℹ 4,543 more rows

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.

shiraz <- shiraz |>
  mutate(prob = surprisals_prob(fit_wine, loo = TRUE, approximation = "rank"))
shiraz |>
  select(country:winery, year, points, price, prob) |>
  arrange(prob)
# A tibble: 4,553 × 8
   country   state           region          winery            year points price    prob
   <chr>     <chr>           <chr>           <chr>            <dbl>  <dbl> <dbl>   <dbl>
 1 Australia South Australia Eden Valley     Henschke          2009     91   780 2.20e-4
 2 US        California      Central Coast   Law               2013     92   750 4.39e-4
 3 Australia South Australia Eden Valley     Henschke          2010     96   820 6.59e-4
 4 Australia South Australia South Australia Penfolds          2008     98   850 8.79e-4
 5 Italy     Tuscany         Toscana         Tua Rita          2011     89   300 1.10e-3
 6 Australia South Australia South Australia Penfolds          2010     99   850 1.32e-3
 7 Italy     Tuscany         Toscana         Tua Rita          2013     90   300 1.76e-3
 8 Italy     Tuscany         Toscana         Tua Rita          2012     90   300 1.76e-3
 9 France    Rhône Valley    Côte Rôtie      Domaine Jean-Mi…  2013     93   391 1.98e-3
10 Australia South Australia South Australia Penfolds          2004     96   500 2.20e-3
# ℹ 4,543 more rows

Figure 8.5 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).

Code
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"))
Figure 8.5: 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.

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

8.4 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 (Wood, 2017) 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 (Equation 8.5).

Example: Cricket not-outs

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 92646 innings, of which 11943 were not-outs. So the overall proportion of not-outs is 11943 / 92646 = 0.129.

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

Figure 8.6 shows the proportion of not-outs for each batter, plotted against their RPI. The relationship turns out to be 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 simply 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.

Code
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")
Figure 8.6: 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.

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}). \tag{8.6} We can fit this model using the mgcv package, with the resulting estimates shown in Figure 8.7.

fit_notouts <- mgcv::gam(
  prop_no ~ s(RPI) + s(Start),
  data = df_no,
  weights = Innings,
  family = binomial(link = logit)
)
gratia::draw(fit_notouts)
Figure 8.7: Estimated values of g_1 and g_2 from Equation 8.6, with 95% confidence intervals.

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 (Section 7.3) to compute the surprisal probabilities, which allows for some mis-specification in the distribution of not-outs.

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
# A tibble: 3,214 × 10
   Player        Country      Start   End Innings NotOuts   RPI .fitted prop_no        p
   <chr>         <chr>        <int> <int>   <int>   <int> <dbl>   <dbl>   <dbl>    <dbl>
 1 SM Pollock    South Africa  1995  2008     156      39 24.2   0.0907  0.25   0.000252
 2 TA Boult      New Zealand   2011  2022      94      46  8.07  0.234   0.489  0.000444
 3 RA Jadeja     India         2012  2025     129      26 30.9   0.0720  0.202  0.00100 
 4 S Chanderpaul West Indies   1994  2015     280      49 42.4   0.0867  0.175  0.00100 
 5 SR Waugh      Australia     1985  2004     260      46 42.0   0.0903  0.177  0.00152 
 6 W Rhodes      England       1899  1930      98      21 23.7   0.0741  0.214  0.00165 
 7 JR Hazlewood  Australia     2014  2025      96      47  5.89  0.282   0.490  0.00177 
 8 M Dillon      West Indies   1997  2004      68       3  8.07  0.244   0.0441 0.00187 
 9 JM Anderson   England       2003  2024     265     114  5.11  0.315   0.430  0.00245 
10 Imran Khan    Pakistan      1971  1992     126      25 30.2   0.0832  0.198  0.00259 
# ℹ 3,204 more rows

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 39 not-outs in 156 innings, which is much higher than the expected number of not-outs of 156 \times 0.091 = 14.1. Shaun Pollock was a bowling all-rounder and a capable batter in the lower order, playing a crucial role in building 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 46 not-outs in 94 innings, compared to the expected number of not-outs of 94 \times 0.234 = 22.0.

Neither batter’s proportion of not-outs is exceptional by itself (sixteen 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.

8.5 BACON algorithm for linear regression

In the regression version of the BACON algorithm (Billor et al., 2000), the goal is to identify observations that are inconsistent with the regression model. This is more complicated than the multivariate case discussed in Section 6.3, 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 (Section 8.2) captures both of these sources of influence, but it does not protect against masking. Also, high leverage values can lead to residual anomalies being masked. Like the LTS estimator (Section 8.1), 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 (Section 6.3) 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.

Example: Shiraz reviews

We now apply regression BACON to the same shiraz data set containing wine reviews that was used in Section 8.1, with points as the predictor and log(price) as the response. Multivariate BACON is first applied to the predictor variable, and then the regression version of the algorithm uses scaled prediction errors. 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 91 with 603 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.

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"]
)
# A tibble: 1 × 5
  observations predictor_outliers regression_outliers mv_steps regression_steps
         <int>              <int>               <int>    <int>            <int>
1         4553                  0                   9        5                5

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, nine regression outliers are identified by the regression BACON algorithm, as their prices are inconsistent with the fitted price–points relationship.

The largest BACON distances are shown below. These correspond to wines with prices that are most unusual after accounting for their points score.

wine_bacon |>
  filter(bacon_outlier) |>
  arrange(desc(bacon_distance)) |>
  select(country, winery, year, points, price, bacon_distance)
# A tibble: 9 × 6
  country   winery                     year points price bacon_distance
  <chr>     <chr>                     <dbl>  <dbl> <dbl>          <dbl>
1 Australia Henschke                   2009     91   780           6.34
2 US        Law                        2013     92   750           6.03
3 Australia Henschke                   2010     96   820           5.32
4 Australia Penfolds                   2008     98   850           4.95
5 Italy     Tua Rita                   2011     89   300           4.76
6 Australia Penfolds                   2010     99   850           4.72
7 Italy     Tua Rita                   2013     90   300           4.54
8 Italy     Tua Rita                   2012     90   300           4.54
9 France    Domaine Jean-Michel Gerin  2013     93   391           4.43

These are the same nine wines that have surprisal probabilities less than 0.002 under the linear regression model (Section 8.3).

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 Figure 8.8 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 4553 observations, and none of them has high leverage (no observation in this data set has a leverage value above 0.003).

fit_bacon_wine <- lm(
  log(price) ~ points,
  data = wine_bacon,
  subset = !bacon_outlier
)
Code
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" = discrete_colours[1])
  ) +
  scale_linetype_manual(
    values = c("Least squares" = "dashed", "BACON subset" = "solid")
  ) +
  labs(x = "Points", y = "Price", linetype = "Fit") +
  guides(colour = "none")
Figure 8.8: 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.

Finally, Figure 8.9 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.

Code
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" = discrete_colours[1])
  ) +
  labs(x = "Points", y = "Absolute scaled prediction error") +
  guides(colour = "none")
Figure 8.9: Absolute scaled prediction errors from regression BACON for Shiraz wine reviews. The dashed line shows the final cutoff used to nominate regression outliers.

8.6 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, and the surprisal probabilities of Chapter 7 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.


  1. The OLS estimate given in Equation 8.1 is equivalent to setting h = n.↩︎

  2. 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.↩︎