7 Density-based methods
Anomalies are observations that are unlikely to have come from the same distribution as the rest of the data. One method to identify anomalies is to first estimate the probability distribution of the data, and then find observations that are improbable under that distribution. This is the approach taken by density-based methods, where anomalies are defined as observations with low probability.
Any density-based method of anomaly detection first requires a density estimate at each observation, denoted by f(\bm{y}_i). This may be an assumed density, or estimated from the data; it may be a parametric function, or a nonparametric estimate; it may be a conditional density or a marginal density. Wherever it comes from, f is treated as an appropriate probability density function for the data set. When \bm{y}_i takes values on a discrete space (such as the integers), then f is a probability mass function, but it is still called a “density” for convenience when discussing methods that can apply to both discrete and continuous data. In many cases, f(\bm{y}_i) is the estimated likelihood of the observation from a given model.
Note that some of the methods discussed in Chapter 6 are often called “density-based” methods, including LOF (Section 6.6) and GLOSH (Section 6.7). These methods use an implicit measure of density, based on the crowdedness of the neighbourhood of each observation. This chapter discusses only methods that explicitly involve a density function.
7.1 Surprisals
“Surprisal” is a term coined by American engineer Myron Tribus (1961) in the context of information theory. In the statistical literature it is better known as a log score. But since we are considering anomaly detection, “surprisal” seems a more appropriate word to use here.
The surprisal of an observation \bm{y}_i is defined as s_i = -\log f(\bm{y}_i), \tag{7.1} measuring the surprise in seeing the observation. So it is a measure of how surprising (or anomalous) that observation is, given the density f. A large value of s_i indicates that \bm{y}_i is not a likely value, and so is a potential anomaly. On the other hand, typical values will have low surprisals. In information theory, the average surprisal is known as the entropy of a random variable (Cover & Thomas, 2006; Stone, 2022), and provides a measure of uncertainty.
Although the term “surprisal” may not be in common use amongst statisticians and other data scientists, the underlying idea is widely used. For example, if f is obtained from a model with parameters that need to be estimated from the data, then the sum of the surprisals is equal to minus the log likelihood of the data. Therefore, finding parameters that minimise the sum of the surprisals is equivalent to maximum likelihood estimation.
Surprisals are also commonly used in forecasting and prediction problems (where they are called log scores) to assess whether an estimated distribution f provides a good description of the future data values y (Gneiting & Katzfuss, 2014). In that context, the data are thought to be a reliable reflection of the underlying processes, and once the data are observed, the surprisal is used to assess how well the estimated distribution f matches what actually happened. This book uses surprisals in reverse: f is assumed to be a good description of the underlying processes, and the surprisals are then used to identify observations that are unlikely to have come from that distribution.
Let’s look at some specific examples.
Normal distribution
Suppose our observations come from a N(0,1) distribution, and that f denotes the corresponding density function. Then s_i = -\log\left( \frac{1}{\sqrt{2\pi}} e^{-y_i^2/2} \right) = \frac12 y_i^2 + \frac12\log(2\pi). So the surprisals are simply equal to half the squared observations plus a constant. This is easily extended to any Normal distribution, showing that surprisals are equal to half the squared standardised observations plus a constant.
\chi^2 distribution
For a \chi^2_k distribution, a surprisal is given by s_i = -\log\left( \frac{y_i^{k/2-1}e^{-y_i/2}}{2^{k/2}\Gamma(k/2)} \right) = \frac{1}{2} y_i - (k/2 - 1)\log(y_i) + c_k where c_k is a constant.
Poisson distribution
Surprisals can also be computed for discrete distributions. For a Poisson(\lambda) distribution, a surprisal is given by s_i = -\log\left( \frac{\lambda^{y_i} e^{-\lambda}}{y_i!} \right) = \log(y_i!) - y_i\log(\lambda) + \lambda
Multivariate Normal distribution
The definition of a surprisal also works for multivariate distributions. For an m-dimensional N(\bm{0}, \bm{\Sigma}) distribution, a surprisal is given by s_i = -\log\left( (2\pi)^{-m/2}|\bm{\Sigma}|^{-1/2} \exp\Big\{-\frac{1}{2}\bm{y}_i^\intercal\bm{\Sigma}^{-1}\bm{y}_i\Big\} \right) = \frac{1}{2} \bm{y}_i^\intercal\bm{\Sigma}^{-1}\bm{y}_i + \frac{m}{2}\log(2\pi) + \frac{1}{2} \log|\bm{\Sigma}| When \bm{\Sigma} = \bm{I}, this is simply the sum of surprisals computed on each of the marginal distributions.
7.2 Surprisal probabilities
The surprisal probability of an observation is the probability of observing a value that is at least as surprising as the observation, under the distribution f. This is easier to interpret than the surprisal itself, because it is on the familiar probability scale between 0 and 1. It also allows us to set a threshold for identifying anomalies in terms of a false positive rate.
Specifically, for an observation \bm{y}_i under the distribution f, its surprisal probability is given by p_i = \int f(\bm{u}) 𝟙(-\log f(\bm{u}) \ge s_i) d\bm{u} = \int f(\bm{u}) 𝟙(f(\bm{u}) \le f(\bm{y}_i)) d\bm{u}, \tag{7.2} where 𝟙(z) is an indicator function taking value 1 when z is true and 0 otherwise.
Figure 7.1 shows the calculation for a \chi^2_5 distribution.
The surprisals() function takes values of the data \bm{y}_i and returns values of s_i (Equation 7.1), where the assumed density f can be provided as a distribution object from the distributional package. The values of p_i in Equation 7.2 can be obtained using surprisals_prob().
tibble(
y = -5:5,
s = surprisals(y, distribution = dist_normal()),
p = surprisals_prob(y, distribution = dist_normal())
)# A tibble: 11 × 3
y s p
<int> <dbl> <dbl>
1 -5 13.4 0.000000573
2 -4 8.92 0.0000633
3 -3 5.42 0.00270
4 -2 2.92 0.0455
5 -1 1.42 0.317
6 0 0.919 1.000
7 1 1.42 0.317
8 2 2.92 0.0455
9 3 5.42 0.00270
10 4 8.92 0.0000633
11 5 13.4 0.000000573
The value of p_i is the probability of an observation being at least as anomalous (or surprising) as \bm{y}_i if the observations come from the distribution f. So if we label points as anomalous when p_i < \alpha, we will have a false positive rate of \alpha.
This approach allows for anomalies to occur anywhere in the distribution, not just in the tails. For example, anomalies may lie between modes in a multimodal distribution, or in otherwise low-density regions of the distribution. The surprisal approach converts the problem of working with a potentially complicated distribution into a problem of working with a simple univariate distribution on the surprisal scale, where large values correspond to anomalies. If \bm{Y} has density f, its surprisal S = -\log f(\bm{Y}) is a univariate random variable, and Equation 7.2 says that p_i = \Pr(S \ge s_i). So an anomaly is an observation whose surprisal lies far in the upper tail of the distribution of S, which is why extreme value theory is useful for estimating surprisal probabilities (Section 7.3).
Connection to highest density regions
Surprisal probabilities are related to highest density regions (discussed in Section 2.7 and Section 3.4). If we identify anomalies as observations with p_i < \alpha, then the non-anomalous observations will lie in the 100(1 - \alpha)\% highest density region, and all the anomalies will lie outside this region. This is a useful way to visualise the anomalies, by plotting the data with the highest density region superimposed. Some examples are shown later in this chapter (Figure 7.5 and Figure 7.6).
Connection to z-scores
If f is the Normal distribution \text{N}(\mu, \sigma^2), then the points of lowest density are those furthest from \mu. In fact, p_i = 2[1 - \Phi(|y_i - \mu|/\sigma)], where \Phi is the standard Normal distribution function. Therefore, identifying anomalies as observations with p_i < \alpha is equivalent to a z-score test (Section 4.2) with the threshold set to the (1 - \alpha/2) quantile of the standard Normal distribution.
This link can be extended to any symmetric unimodal distribution. If f is a symmetric unimodal distribution centred at c, then the most anomalous observations will be those with the largest absolute distance from c. If F is the distribution function corresponding to f, then p_i = 2[1 - F(c + |y_i - c|)].
7.3 Approximate surprisal probabilities
If we do not know what the distribution of the data should be, or if we think our assumed distribution is incorrect for some reason, there are some ways to find approximate surprisal probabilities that can still be accurate even when the assumed distribution is wrong.
Approximate GPD surprisal probabilities
Let f^* denote the assumed (and possibly incorrect) density function. For example, it might be a poor estimate of the true density. Using this assumed density, we can compute the surprisals, s_i = -\log f^*(\bm{y}_i).
Then we can fit a Generalised Pareto Distribution (GPD) to the largest surprisals using the POT approach discussed in Section 2.10. This can work even when f^* is incorrect or poorly estimated.
Why should this work? The POT result in Section 2.10 says that, for almost any continuous distribution, the values above a high threshold approximately follow a GPD. Here the GPD is fitted to the surprisals, not to the data, so the result needs to hold only for the surprisals. Using the wrong density f^* changes the surprisal values, but in most cases the largest surprisals still follow a GPD. What f^* and the data affect is the shape parameter \xi in Equation 2.15, which describes how quickly the upper tail of the surprisals dies away. For example, suppose f^* is the N(0,1) density, so that s_i = \frac12 y_i^2 + \frac12\log(2\pi) (Section 7.1). Then the tail of the surprisals depends on how large y_i^2 can get:
- \xi < 0 if the data are Uniform on [-1, 1], because the surprisals can be no larger than \frac12 + \frac12\log(2\pi).
- \xi = 0 if the data are N(0,1), because y_i^2 has a \chi^2_1 distribution, whose tail decays exponentially.
- \xi > 0 if the data are \text{t}_4, because occasional very large observations give very large surprisals.
The GPD includes all three cases, and \xi is estimated from the largest surprisals, so we don’t need to know in advance which case applies. In effect, the estimated probabilities depend on where each surprisal lies among the others, so f^* only needs to put the most extreme observations in roughly the right order. Hyndman & Frazier (2026) give the precise conditions under which this works, and show that it leads to good estimates of the surprisal probabilities for the largest surprisals, which are the ones that matter for anomaly detection.
Let \beta denote the tail probability used in the GPD threshold, and let u denote the (1 - \beta) sample quantile of the surprisal values. For example, \beta = 0.1 is a common choice, and then u is the 90^{\text{th}} percentile of the s_i values. We fit a GPD to the surprisals above u, and then compute the approximate surprisal probability of each observation with s_i > u by
\hat{p}_i = \beta\int_{s_i}^\infty \hat g(s) ds,
\tag{7.3} where \hat g denotes the estimated GPD density of the surprisals above u (that is, the GPD fitted to the exceedances s_i - u, shifted to start at u). This approximation only gives us surprisal probabilities for the surprisals above the threshold u. For any s_i \le u, all we can say is that p_i is at least about \beta, and surprisals_prob() returns \hat{p}_i = \beta for these observations.
Figure 7.2 illustrates the calculation, using surprisals computed from 1000 N(0,1) observations with an incorrect \text{t}_4 density. The top panel shows all the surprisals, with the largest 10% (those above u) highlighted. The bottom panel shows only these largest surprisals, along with the fitted GPD density multiplied by \beta. The multiplication is needed because these surprisals are only 10% of the total, so the bars in the bottom panel have total area \beta = 0.1 rather than 1. The shaded area to the right of s_i is the estimated surprisal probability \hat{p}_i.
The approach does require a relatively large number of surprisals to be available, in order to adequately estimate the GPD from the largest 100\beta% of them. So we would typically need at least a few hundred observations to start with.
The surprisals_prob() function uses this GPD approximation (Equation 7.3) when approximation = "gpd". The argument threshold_probability is used to specify \beta, with the default value of 0.1.
Approximate rank-based surprisal probabilities
An alternative approach that does not require a GPD is to estimate p_i as the proportion of observations with surprisal values at least as large as s_i. That is, \hat{p}_i = (n - \text{rank}(s_i) + 1)/n, where \text{rank}(s_i) is the rank of s_i among the s_1,\dots,s_n values, with the smallest value having rank 1, and tied values all given the smallest of their ranks. For large n, this provides a quick and convenient estimate of p_i. Hyndman & Frazier (2026) show that this approach works well when the ordering of the largest surprisal values under f and f^* is similar, which should be the case when f^* is a reasonable approximation to f.
The approximation argument of surprisals_prob() can be set to "rank" to use these rank-based surprisal probabilities.
Example: Standard Normal values
For example, consider the 1000 values contained in the first column of n01. These were generated from a standard Normal distribution. We can use surprisals_prob() to identify anomalies with surprisal probability less than 1%. This is equivalent to z-scores greater than 2.576 in absolute value.
We will use all three methods described above, first using the correct density in computing the surprisals, and then repeating the calculation using an incorrect density. For the incorrect density, we will use a \text{t}_4 distribution, which has much longer tails than the true N(0,1) distribution.
# Compute surprisal probabilities of v1 assuming a standard Normal distribution
# and a t4 distribution
norm_prob <- tibble(
y = n01$v1,
p = surprisals_prob(y, distribution = dist_normal()),
p_gpd = surprisals_prob(
y,
distribution = dist_normal(),
approximation = "gpd"
),
p_emp = surprisals_prob(
y,
distribution = dist_normal(),
approximation = "rank"
),
pt = surprisals_prob(y, distribution = dist_student_t(4)),
pt_gpd = surprisals_prob(
y,
distribution = dist_student_t(4),
approximation = "gpd"
),
pt_emp = surprisals_prob(
y,
distribution = dist_student_t(4),
approximation = "rank"
)
)
norm_prob |> arrange(p)# A tibble: 1,000 × 7
y p p_gpd p_emp pt pt_gpd pt_emp
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 3.81 0.000139 0.000135 0.001 0.0189 0.000132 0.001
2 3.06 0.00225 0.00261 0.002 0.0378 0.00284 0.002
3 -3.01 0.00263 0.00308 0.003 0.0396 0.00334 0.003
4 -3.00 0.00273 0.00320 0.004 0.0401 0.00346 0.004
5 -2.94 0.00328 0.00389 0.005 0.0424 0.00418 0.005
6 -2.89 0.00387 0.00461 0.006 0.0446 0.00492 0.006
7 2.68 0.00746 0.00913 0.007 0.0555 0.00948 0.007
8 2.65 0.00807 0.00991 0.008 0.0570 0.0102 0.008
9 -2.60 0.00943 0.0116 0.009 0.0603 0.0119 0.009
10 -2.59 0.00953 0.0118 0.01 0.0605 0.0121 0.01
# ℹ 990 more rows
The true values are in column p, as this uses the correct distribution applied to the correct surprisals. Notice that p_gpd and p_emp are both relatively accurate: the GPD and rank approximations work. The last three columns show the probabilities based on surprisals using the incorrect distribution. Here, pt is very inaccurate, with probabilities much larger than they should be, especially in the extreme tails. This is because the \text{t}_4 distribution has much heavier tails than the true N(0,1) distribution, so the probability of observations more extreme than those observed is much larger than it should be. But pt_gpd and pt_emp are both reasonable estimates, despite being based on an incorrect distribution for computing the surprisals. In fact, p_emp and pt_emp are identical, because the ordering of the surprisals is unchanged despite the incorrect distribution being used.
The various estimates are displayed in Figure 7.3 for values of y greater than 2.5, showing that the estimates (other than pt) are close to the true values in the tail, where we need them for anomaly detection. The rank estimates can never be smaller than 1/n, so they overstate the probability of the most extreme observation, whereas the GPD estimates are not bounded below in this way.
Code
norm_prob |>
filter(y > 2.5) |>
tidyr::pivot_longer(
p:pt_emp,
names_to = "Estimate",
values_to = "Probability"
) |>
ggplot(aes(x = y, y = Probability, col = Estimate)) +
geom_line()
Example: \text{t}_4 values
In the previous example, the incorrect density had heavier tails than the data, so the errors made observations look less anomalous than they really were. The opposite mistake is more serious: if the assumed density has lighter tails than the data, then ordinary observations will look anomalous.
To see this, consider 1000 values generated from a \text{t}_4 distribution, and compute their surprisals using an N(0,1) density.
set.seed(1)
t4_prob <- tibble(
y = rt(1000, df = 4),
p = surprisals_prob(y, distribution = dist_student_t(4)),
pn = surprisals_prob(y, distribution = dist_normal()),
pn_gpd = surprisals_prob(
y,
distribution = dist_normal(),
approximation = "gpd"
),
pn_emp = surprisals_prob(
y,
distribution = dist_normal(),
approximation = "rank"
)
)
t4_prob |> arrange(p)# A tibble: 1,000 × 5
y p pn pn_gpd pn_emp
<dbl> <dbl> <dbl> <dbl> <dbl>
1 -10.8 0.000416 0 0.00153 0.001
2 -10.3 0.000500 0 0.00173 0.002
3 8.95 0.000863 0 0.00253 0.003
4 8.93 0.000869 0 0.00254 0.004
5 -8.81 0.000917 0 0.00263 0.005
6 8.04 0.00130 8.88e-16 0.00336 0.006
7 -7.74 0.00150 9.77e-15 0.00371 0.007
8 6.74 0.00252 1.54e-11 0.00536 0.008
9 -5.70 0.00469 1.21e- 8 0.00839 0.009
10 5.47 0.00545 4.58e- 8 0.00937 0.01
# ℹ 990 more rows
Now the true values are in column p, computed using the \text{t}_4 density. The probabilities in pn, computed using the N(0,1) density, are far too small. Using a threshold of 0.01, pn would flag 72 observations as anomalies, compared to 15 using the true probabilities. The GPD and rank estimates are much closer to the true values, flagging 10 and 9 observations respectively. Figure 7.4 shows the estimates for values of y greater than 2.5.
Code
t4_prob |>
filter(y > 2.5) |>
tidyr::pivot_longer(
p:pn_emp,
names_to = "Estimate",
values_to = "Probability"
) |>
ggplot(aes(x = y, y = Probability, col = Estimate)) +
geom_line()
To summarise, even when we don’t know the distribution of the data, we can use some incorrect assumed distribution to compute the surprisals, and then apply either a GPD or the rank approximation to obtain good estimates of the surprisal probabilities.
7.4 KDE surprisals
Suppose we estimate f using a kernel density estimate. In fact, when the surprisals() or surprisals_prob() functions are applied to data without specifying a probability distribution, a kernel density estimate of the data is used by default. The kernel density estimate at each observation is (Equation 3.4)
f_i = \hat{f}(\bm{y}_i) = \frac{1}{n} \sum_{j=1}^n K_{\bm{H}}(\bm{y}_i - \bm{y}_j),
\tag{7.4} and so the KDE surprisal at each observation is defined as
s_i = -\log(f_i).
The largest possible surprisal occurs when an observation has no other observations nearby. Then f_i \approx K_{\bm{H}}(\bm{0})/n because K_{\bm{H}}(\bm{y}_i - \bm{y}_j) \approx 0 when \|\bm{y}_i - \bm{y}_j\| is large. So the largest possible KDE surprisal, when using a Gaussian kernel, is
-\log(K_{\bm{H}}(\bm{0})/n) = \log(n) + \frac{m}{2}\log(2\pi)
+ \frac{1}{2}\log|\bm{H}|,
where \bm{H} is the bandwidth matrix. For univariate data, when m = 1 and \bm{H} = h^2, this simplifies to
-\log(K_h(0)/n) = \log(nh\sqrt{2\pi}).
Identifying anomalies using KDE surprisals is related to the local outlier factor method (Section 6.6). However, the local outlier factor method is based on the ratio of the average density at the neighbours of a point to the density at the point itself, while the KDE surprisal method is based on the density at a point alone. This means that the KDE surprisal method is more likely to identify points in low-density regions as anomalies, even when their neighbours are equally sparse.
7.5 LOO surprisals
If the density f has been estimated from the data (whether from a parametric model or a nonparametric method such as KDE), then there is a problem of circular reasoning. Any genuine anomalies may affect the estimated density, and then they may not appear to be anomalies. Therefore, it is sometimes useful to consider the leave-one-out (LOO) estimate given by f_{-i}. That is, f_{-i} is the density estimate using all observations other than the ith observation. Then an unusual observation can’t influence the density estimate, giving us a better measure of how anomalous it really is. In this case, the associated surprisal is called a LOO surprisal, given by s_{-i} = -\log f_{-i}(\bm{y}_i).
LOO KDE surprisals
Let’s take the example of KDE surprisals. The contribution of the ith point to the kernel density estimate at that point is K_{\bm{H}}(\bm{0})/n. Therefore, the leave-one-out kernel density estimate is given by f_{-i} = \left[ nf_i - K_{\bm{H}}(\bm{0}) \right]/(n - 1), \tag{7.5} where f_i is the kernel density estimate from Equation 7.4 using all data, so that the leave-one-out KDE surprisal is s_{-i} = -\log (f_{-i}). Thus, we can compute the leave-one-out KDE surprisals without needing to re-estimate the density many times.
The largest possible LOO KDE surprisal is infinite, occurring when there are no observations nearby, so that nf_i = K_{\bm{H}}(\bm{0}) (to numerical precision) and hence f_{-i} = 0 in Equation 7.5.
The lookout algorithm
The lookout algorithm (standing for Leave-One-Out Kernel density estimates for OUTlier detection) was proposed by Kandanaarachchi & Hyndman (2022), and later modified by Hyndman et al. (2026). It computes surprisal probabilities using a GPD approximation applied to the LOO KDE surprisals, where the bandwidth matrix is the lookout bandwidth (Equation 3.6). These probabilities can be calculated using the surprisals_prob() function with loo = TRUE, approximation = "gpd", and method = "lookout".
7.6 Example: Old Faithful eruption durations
Let’s apply the KDE surprisals method to the Old Faithful eruptions contained in the oldfaithful data set. We will use the LOO KDE surprisal probabilities to identify anomalies in the eruption durations (but using the default robust normal reference bandwidth, rather than the lookout bandwidth).
of_surprisals <- oldfaithful |>
mutate(
loo_kde_surprisal = surprisals(duration, loo = TRUE),
prob = surprisals_prob(duration, loo = TRUE, approximation = "gpd"),
)
of_surprisals |> arrange(desc(loo_kde_surprisal))# A tibble: 2,097 × 6
time recorded_duration duration waiting loo_kde_surprisal prob
<dttm> <chr> <dbl> <dbl> <dbl> <dbl>
1 2018-04-25 19:08:00 1s 1 5700 Inf 0
2 2022-12-07 17:19:00 ~4 30s 30 5220 Inf 0
3 2023-07-04 12:03:00 ~1 minute 55ish secon… 60 4920 Inf 0
4 2022-11-17 22:53:00 1m 28s 88 3540 8.57 6.78e-5
5 2022-11-20 22:43:00 1m 29s 89 3480 8.36 9.65e-4
6 2020-10-25 16:31:00 5m05s 305 6060 8.18 2.72e-3
7 2020-05-07 22:55:00 5m04s 304 6180 8.07 4.34e-3
8 2020-05-21 00:27:00 5m04s 304 5640 8.07 4.34e-3
9 2020-09-15 18:01:00 >2m40s 160 5880 8.01 5.30e-3
10 2020-09-16 14:44:00 >2m40s 160 6120 8.01 5.30e-3
# ℹ 2,087 more rows
The three largest LOO surprisals correspond to the three erroneous short durations. The prob column contains the associated surprisal probabilities.
If we omit the three extreme values, we obtain different results.
of_surprisals <- oldfaithful |>
filter(duration > 60) |>
mutate(
loo_kde_surprisal = surprisals(duration, loo = TRUE),
prob = surprisals_prob(duration, loo = TRUE, approximation = "gpd"),
)
of_surprisals |> arrange(desc(loo_kde_surprisal))# A tibble: 2,094 × 6
time recorded_duration duration waiting loo_kde_surprisal prob
<dttm> <chr> <dbl> <dbl> <dbl> <dbl>
1 2022-11-17 22:53:00 1m 28s 88 3540 8.52 0.0000914
2 2022-11-20 22:43:00 1m 29s 89 3480 8.32 0.000972
3 2020-10-25 16:31:00 5m05s 305 6060 8.21 0.00194
4 2020-05-07 22:55:00 5m04s 304 6180 8.09 0.00340
5 2020-05-21 00:27:00 5m04s 304 5640 8.09 0.00340
6 2020-09-15 18:01:00 >2m40s 160 5880 8.00 0.00466
7 2020-09-16 14:44:00 >2m40s 160 6120 8.00 0.00466
8 2017-09-01 01:18:00 2m 35s 155 4560 7.99 0.00486
9 2017-09-07 04:56:00 2m 35s 155 4740 7.99 0.00486
10 2022-10-31 23:15:00 2m35s 155 4800 7.99 0.00486
# ℹ 2,084 more rows
Now there are thirteen points with probabilities less than 0.005: four with durations above 300 seconds, two below 90 seconds, and the rest between 155 and 165 seconds.
Figure 7.5 shows an HDR boxplot of the data, with those points with surprisal probabilities less than 0.005 highlighted in black.
oldfaithful |>
filter(duration > 60) |>
gg_hdrboxplot(duration)
The same algorithm is easily applied in two dimensions. For example, we can consider the bivariate distribution of eruption duration and waiting time.
of <- oldfaithful |>
select(duration, waiting)
of |>
mutate(
loo_scores = surprisals(of, loo = TRUE),
prob = surprisals_prob(of, loo = TRUE, approximation = "gpd")
) |>
filter(prob < 0.005) |>
arrange(prob, duration)# A tibble: 19 × 4
duration waiting loo_scores prob
<dbl> <dbl> <dbl> <dbl>
1 1 5700 Inf 0
2 30 5220 Inf 0
3 60 4920 Inf 0
4 110 6240 Inf 0
5 120 6060 Inf 0
6 180 6540 Inf 0
7 240 3060 Inf 0
8 241 4500 Inf 0
9 300 5280 20.5 0.000249
10 170 3600 20.4 0.000277
11 201 4380 18.6 0.00133
12 160 5880 18.2 0.00177
13 106 3000 18.2 0.00182
14 186 4320 18.0 0.00210
15 165 4440 17.9 0.00242
16 170 3840 17.9 0.00245
17 160 6120 17.8 0.00259
18 270 5040 17.3 0.00401
19 180 4740 17.3 0.00406
Now, nineteen anomalies are identified, with eight of them having infinite LOO surprisals. We can visualise them in an HDR scatterplot, shown in Figure 7.6.
oldfaithful |>
gg_hdrboxplot(duration, waiting, show_points = TRUE)
7.7 Gaussian mixture model surprisal probabilities
A Gaussian mixture model (GMM) is a flexible parametric model for the joint distribution of the data, which can capture multimodality and other complex features. It comprises a weighted sum of multivariate Normal distributions, each with its own mean vector and covariance matrix. That is,
f(\bm{y}) = \sum_{k=1}^K \pi_k \phi(\bm{y}; \bm{\mu}_k, \bm{\Sigma}_k),
where K is the number of components, the weights \pi_k \ge 0 sum to 1, and \phi(\bm{y}; \bm{\mu}_k, \bm{\Sigma}_k) is the multivariate Normal density with mean \bm{\mu}_k and covariance matrix \bm{\Sigma}_k. In fact, a KDE with a Gaussian kernel can be considered a Gaussian mixture model with a large number of equally-weighted components, each centred at an observation and with a common covariance matrix given by the bandwidth matrix. However, we can also fit a GMM with a smaller number of components, which may provide a more parsimonious model for the data. The mclust package provides a convenient way to fit GMMs to data.
library(mclust)
set.seed(2)
gmm <- oldfaithful |>
select(duration, waiting) |>
Mclust() |>
dist_mclust()
gmm<distribution[1]>
[1] mixture(0.735616570140725*MVN[2], 0.118399144053157*MVN[2], 0.145984285806118*MVN[2])
The algorithm initialises by clustering a random subset of the data (because there are more than 2000 observations), so different results may be obtained on different runs. The set.seed() function is used here to ensure reproducibility.
We have estimated a 3-component GMM for the Old Faithful data, with means \bm{\mu}_1 = \begin{bmatrix} 245.6 \\ 5843.1 \end{bmatrix}, \quad \bm{\mu}_2 = \begin{bmatrix} 218.7 \\ 5698.6 \end{bmatrix}, \quad\text{and}\quad \bm{\mu}_3 = \begin{bmatrix} 116.8 \\ 4047.5 \end{bmatrix}, covariances \bm{\Sigma}_1 = \begin{bmatrix} 221.8 & 1966.6 \\ 1966.6 & 167998.0 \end{bmatrix} , \quad \bm{\Sigma}_2 = \begin{bmatrix} 2057.0 & 12122.3 \\ 12122.3 & 399827.7 \end{bmatrix} , \quad\text{and}\quad \bm{\Sigma}_3 = \begin{bmatrix} 125.4 & 1169.4 \\ 1169.4 & 138726.9 \end{bmatrix} , and weights 0.736, 0.146, and 0.118, respectively. The component multivariate Normal densities are shown in Figure 7.7.
When the components are added together, we get the density shown in Figure 7.8.
gmm |>
gg_density() +
geom_point(data = oldfaithful, aes(x = duration, y = waiting), alpha = 0.1) +
labs(x = "Duration", y = "Waiting time")
We can compute the density at each observation under this fitted model, and then compute surprisal probabilities based on that density.
of <- oldfaithful |>
mutate(
gmm_prob = surprisals_prob(
pick(duration, waiting),
distribution = gmm,
approximation = "gpd"
)
) |>
arrange(gmm_prob)
of# A tibble: 2,097 × 5
time recorded_duration duration waiting gmm_prob
<dttm> <chr> <dbl> <dbl> <dbl>
1 2018-04-25 19:08:00 1s 1 5700 0.0000594
2 2022-12-03 16:20:00 ~4m 240 3060 0.000121
3 2022-12-07 17:19:00 ~4 30s 30 5220 0.000296
4 2023-07-04 12:03:00 ~1 minute 55ish seconds 60 4920 0.00117
5 2021-01-22 18:35:00 2m50s 170 3600 0.00159
6 2020-09-04 01:38:00 >1m 50s 110 6240 0.00218
7 2022-11-29 14:51:00 ~3m 180 3840 0.00307
8 2020-08-31 09:56:00 ~2m50s 170 3840 0.00321
9 2020-06-01 21:04:00 2 minutes 120 6060 0.00473
10 2022-09-08 05:13:00 5 min 300 5280 0.00879
# ℹ 2,087 more rows
Code
of |>
ggplot(aes(x = duration, y = waiting, colour = gmm_prob < 0.005)) +
geom_point() +
labs(
x = "Duration",
y = "Waiting time",
colour = "Surprisal probability < 0.005"
) +
scale_colour_manual(values = c("FALSE" = "grey70", "TRUE" = "#D55E00"))
As shown in Figure 7.9, the model has highlighted the nine points that do not appear to belong to the two main clusters of observations.
7.8 Summary
Density-based methods define an anomaly as an observation that is improbable under the distribution of the data. The surprisal, s_i = -\log f(\bm{y}_i), measures how improbable each observation is, and the surprisal probability puts this on a probability scale, as the chance of seeing an observation at least as surprising. Flagging observations with surprisal probability below \alpha then gives a false positive rate of \alpha, and the non-anomalous observations are those lying in the 100(1 - \alpha)% highest density region. Unlike z-scores, this allows anomalies to lie anywhere in the distribution, including between the modes of a multimodal distribution, although for Normal data the two approaches are equivalent.
The main practical difficulty is that we rarely know f. Two ideas make the approach work in practice. First, the surprisal probabilities of the most extreme observations can be estimated accurately even when the density used to compute the surprisals is wrong, by fitting a Generalised Pareto Distribution to the largest surprisals, or by using their ranks. Second, when the density is estimated from the data, using leave-one-out estimates stops each anomaly from inflating its own density estimate; for kernel density estimates, the leave-one-out values can be computed without re-estimating the density.
The density estimate can be nonparametric, such as a kernel density estimate, which makes few assumptions but requires a bandwidth, or parametric, such as a Gaussian mixture model, which is more parsimonious and can still capture multimodality. The surprisal approach is used throughout the rest of the book, with the density replaced by a conditional distribution when we want to find observations that are unusual given other information, such as predictor values in Chapter 8 or the past history of a time series in Chapter 12.