# Construct example data set
df <- n01 |>
transmute(
V1 = v1,
V2 = v1 + v2,
V3 = v1 + v2 + v3
)
# Add anomalies
df[999, ] <- tibble(V1 = -2, V2 = 3.4, V3 = 1.3)
df[1000, ] <- tibble(V1 = 1.2, V2 = -1.8, V3 = 1.1)
df$anomaly <- c(rep(FALSE, 998), TRUE, TRUE)3 Multivariate probability distributions
While this book covers anomaly detection in univariate data, most of the methods it discusses are for multivariate data. We will therefore need to understand some basic concepts of multivariate probability distributions.
3.1 Hiding in high-dimensional space
When first thinking about multivariate probability distributions, it can take some time to develop an intuition for how they behave. One way to start developing this intuition is to plot data with increasing numbers of dimensions, starting with the univariate case.
Consider the n01 data set, which contains 10 variables, each from independent standard Normal distributions. Only the first three variables are used here and, to make the example more interesting, they are replaced by their cumulative sums. A couple of anomalies are also added, and then we will see if we can find them using some data visualisations.
First, we can do a strip plot of each variable to visualise the data from a univariate perspective (Figure 3.1).
Code
df |>
tidyr::pivot_longer(V1:V3) |>
ggplot(aes(x = value, y = 0, col = anomaly)) +
geom_jitter(width = 0) +
facet_grid(name ~ .) +
scale_y_discrete() +
labs(x = "", y = "") +
scale_colour_manual(values = c("#999999", "#D55E00"))
The only obvious feature of these graphs is that the variance increases in successive panels. This is because the variance of the sum of independent random variables is the sum of their variances. The two anomalies are plotted in each panel, but they are not obviously different from the other observations.
Now we will plot pairwise scatterplots of the three variables, giving the bivariate perspective (Figure 3.2).
Code
GGally::ggpairs(
df[, 1:3],
lower = list(
continuous = GGally::wrap("points"),
mapping = aes(colour = df$anomaly)
)
) +
scale_colour_manual(values = c("#999999", "#D55E00")) +
theme(panel.spacing = unit(1, "lines"))
This shows that there are positive relationships between the variables, with the strongest between V2 and V3. One of the anomalies is now clearly separate from the other observations in the plot of V2 vs V1 (the top left scatterplot). For this anomaly, the value of V1 is -2, which is not particularly unusual compared to the other observations. Similarly, the value of V2 is 3.4, which is also not particularly unusual. But because of their positive correlation, the combination of these two values is unusual, so it shows up in the 2-dimensional scatterplot. The other anomaly does not look particularly unusual in any of the plots.
To visualise trivariate relationships, we need to use a 3D scatterplot, as in Figure 3.3. It is easiest to see this if it can spin. Try dragging the plot around with your mouse to view it from different angles. See if you can find a viewpoint where the second anomaly is clearly separated from the other observations.
Code
rgl::plot3d(
df[, 1:3],
size = 5,
col = c(rep("#999999", 998), rep("#D55E00", 2))
)This second anomaly is not particularly unusual in any combination of two variables, but it is unusual in the combination of all three variables.
When looking for anomalies, it is important to consider all the variables together, rather than looking at each variable in isolation, or even looking at all the pairwise relationships. It is possible for an observation to be unusual in m dimensions, but not unusual in any of the lower-dimensional subsets of variables. In other words, there are more places for anomalies to hide in higher dimensions.
3.2 The curse of dimensionality
The curse of dimensionality refers to the increasing sparseness of space as the number of dimensions increases.
Points in the corners
Suppose we observed a high-dimensional data set of independent U(-1,1) variables, and consider the proportion of points that lie outside the unit sphere (in the corners of the space) as the number of dimensions increases. First, let’s visualise what this means in 1, 2 and 3 dimensions. In 1 dimension, the unit sphere is just the interval [-1,1], so no points lie outside this interval. In 2 dimensions, the unit sphere is the circle with radius 1, sitting snugly within a square of side length 2, as shown in Figure 3.4.
Code
tibble(
x = runif(2000, -1, 1),
y = runif(2000, -1, 1),
within_sphere = (x^2 + y^2) < 1
) |>
ggplot(aes(x = x, y = y, colour = within_sphere)) +
geom_point() +
coord_fixed() +
scale_colour_manual(values = c("#D55E00", "#777777")) +
guides(col = "none")
The proportion of points lying outside the circle in the corners of the space (shown in orange) is 21.5%.
The equivalent plot in 3 dimensions is shown in Figure 3.5. The unit sphere is now a ball of radius 1 sitting within a box, and 47.6% of points lie outside the ball.
Code
df <- tibble(
x = runif(2000, -1, 1),
y = runif(2000, -1, 1),
z = runif(2000, -1, 1),
within_sphere = (x^2 + y^2 + z^2) < 1,
colour = if_else(within_sphere, "#777777", "#D55E00")
)
rgl::plot3d(df[, 1:3], size = 5, col = df$colour)As the number of dimensions grows, it becomes increasingly likely that points will lie in the corners of the space. In fact, the proportion of points lying outside the unit sphere in m dimensions is 1 minus the ratio of the volume of the unit sphere to the volume of the whole space. This is given by 1 - \frac{\pi^{m/2}}{2^m\Gamma(m/2 + 1)} where \Gamma is the gamma function, and is plotted in Figure 3.6.
Code
tibble(m = seq(10)) |>
mutate(outside = 100 * (1 - (pi^(m / 2) / (2^m * gamma(m / 2 + 1))))) |>
ggplot(aes(x = m, y = outside)) +
geom_line() +
labs(
x = TeX("Dimensions ($m$)"),
y = "Percentage of points outside unit sphere"
) +
scale_x_continuous(breaks = seq(10), minor_breaks = NULL)
Remarkably, by 10 dimensions, almost all points lie outside the unit sphere, and live in the corners of the space; almost no points are in the centre of the space. This occurs because an observation is only near the centre if all of its coordinates are near zero, and with enough variables, at least one of them is likely to be far from zero. For example, the probability that all m coordinates lie between -0.5 and 0.5 is 0.5^m, which is less than 0.001 when m = 10.
The size of neighbourhoods
Another way to think about this is to consider central hypercubes that contain 50% of the observations. These must have sides of length 2^{1-1/m}, in order for the volume of the hypercube to be 2^{m-1}, exactly half of the entire space. For m = 1, the hypercube is an interval of length 1; for m = 2, it is a square of side length \sqrt{2} \approx 1.41 as shown in Figure 3.7; for m = 3, the central cube must have side length 2^{2/3} \approx 1.59; and so on.
Code
tibble(
x = runif(2000, -1, 1),
y = runif(2000, -1, 1),
within_cube = (abs(x) < 2^(-1 / 2)) & (abs(y) < 2^(-1 / 2))
) |>
ggplot(aes(x = x, y = y, colour = within_cube)) +
geom_point() +
coord_fixed() +
scale_colour_manual(values = c("#D55E00", "#777777")) +
guides(col = "none")
As the dimension m increases, the size of the hypercube containing 50% of the observations must also increase. Figure 3.8 shows the side length of these hypercubes plotted against the dimension m.
Code
tibble(m = seq(20)) |>
mutate(length = 2^(1 - 1 / m)) |>
ggplot(aes(x = m, y = length)) +
geom_line() +
geom_point() +
labs(
x = TeX("Dimensions ($m$)"),
y = "Side length of hypercube containing 50% of points"
) +
scale_x_continuous(breaks = seq(2, 20, by = 2), minor_breaks = NULL) +
ylim(1, 2)
The side lengths of these hypercubes approach the maximum of 2 as the number of dimensions increases. So the size of the neighbourhood containing 50% of the observations becomes almost as large as the whole space. Therefore, methods that rely on local neighbourhoods become unreliable in high dimensions, as these neighbourhoods must become so large as to no longer be “local”.
3.3 Joint probability distributions
Now we have a sense of what it means to have data in many dimensions, let’s consider how we can describe the joint probability distribution of multiple variables.
Statistical definitions
Suppose \bm{Y} = [Y_1,\dots,Y_m]^\intercal is a random vector taking values in \mathbb{R}^m, the set of m-dimensional real vectors. Then the joint distribution of \bm{Y} is defined by the joint cdf F(\bm{y}) = \Pr(\bm{Y} \le \bm{y}), while the joint density function is given by f(\bm{y}) = \frac{\partial^m F(\bm{y})}{\partial y_1 \dots \partial y_m}.
The marginal cdfs are defined by F_i(y) = \Pr(Y_i \le y), with corresponding marginal pdfs given by f_i(y) = F_i'(y), i = 1,\dots,m.
If the variables are independent, then the joint pdf is the product of the marginal pdfs, f(\bm{y}) = \prod_{i=1}^m f_i(y_i).
The expected value of \bm{Y} is the vector of expectations of its components, and is given by \text{E}(\bm{Y}) = \int_{\mathbb{R}^m} \bm{y} f(\bm{y})d\bm{y}. The covariance matrix of \bm{Y} is given by \text{Var}(\bm{Y}) = \text{E}[(\bm{Y} - \text{E}(\bm{Y}))(\bm{Y} - \text{E}(\bm{Y}))^\intercal]. The covariance matrix is an m \times m matrix, with (i,j)th element given by \text{Cov}(Y_i,Y_j) = \text{E}[(Y_i - \text{E}(Y_i))(Y_j - \text{E}(Y_j))]. The diagonal elements are the variances of the individual variables, while the off-diagonal elements are the covariances between the variables.
The covariance matrix is always symmetric and positive semi-definite.
Two useful results we will need are for the expectation and covariance of a linear transformation of a random vector. If \bm{Y} is an m-dimensional random vector, and \bm{A} is a k \times m matrix, then \begin{align*} \text{E}(\bm{A}\bm{Y}) & = \bm{A}\text{E}(\bm{Y}), \\ \text{Var}(\bm{A}\bm{Y}) & = \bm{A}\text{Var}(\bm{Y})\bm{A}^\intercal. \end{align*}
Multivariate Normal distribution
If random vector \bm{Y} has a multivariate Normal distribution, we write \bm{Y} \sim \text{N}(\bm{\mu}, \bm{\Sigma}), where \bm{\mu} is the mean and \bm{\Sigma} is the covariance matrix.
The multivariate Normal distribution has pdf given by f(\bm{y}; \bm{\mu}, \bm{\Sigma}) = (2\pi)^{-m/2}|\bm{\Sigma}|^{-1/2} \exp\left\{ -\frac{1}{2}(\bm{y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{y} - \bm{\mu}) \right\}. The notation |\bm{\Sigma}| denotes the determinant of the matrix \bm{\Sigma}.
Multivariate Normal distributions have the interesting property that the marginal distributions are also Normal. More generally, suppose we split \bm{Y} into two parts, \bm{Y}_1 and \bm{Y}_2, with the mean and covariance matrix split in the same way: \bm{Y} = \begin{bmatrix} \bm{Y}_1 \\ \bm{Y}_2 \end{bmatrix}, \qquad \bm{\mu} = \begin{bmatrix} \bm{\mu}_1 \\ \bm{\mu}_2 \end{bmatrix}, \qquad \bm{\Sigma} = \begin{bmatrix} \bm{\Sigma}_{11} & \bm{\Sigma}_{12} \\ \bm{\Sigma}_{21} & \bm{\Sigma}_{22} \end{bmatrix}. Then the marginal distribution of \bm{Y}_1 is \text{N}(\bm{\mu}_1, \bm{\Sigma}_{11}).
Another useful result concerns the quadratic form (\bm{Y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{Y} - \bm{\mu}) that appears in the pdf. If \bm{\Sigma}^{-1} = \bm{U}^\intercal\bm{U}, then \bm{Z} = \bm{U}(\bm{Y} - \bm{\mu}) has a \text{N}(\bm{0}, \bm{I}) distribution (using the results for linear transformations above), so its elements are independent standard Normal random variables. Therefore (\bm{Y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{Y} - \bm{\mu}) = \bm{Z}^\intercal\bm{Z} = \sum_{i=1}^m Z_i^2 \sim \chi^2_m. \tag{3.1}
Further reading
A good reference on multivariate probability distributions is Kotz et al. (2000).
3.4 Highest density regions
As with univariate distributions (Section 2.7), a highest density region for a multivariate distribution is defined as the region of the sample space where the density is higher than a given threshold. Suppose we have a multivariate random variable \bm{Y} with a smooth, continuous density function f. Then the 100(1 - \alpha)% HDR is the set R_\alpha = \{\bm{y}: f(\bm{y}) \ge f_\alpha\} where f_\alpha is the largest constant such that \Pr(\bm{Y} \in R_\alpha) = 1 - \alpha.
HDRs are equivalent to level sets of the density function, and so can be plotted as contours for bivariate density functions. For example, the bivariate Normal distribution with mean (0,0) and covariance matrix \bm{\Sigma} = \begin{bmatrix} 1 & 0.5 \\ 0.5 & 1 \end{bmatrix} is shown in Figure 3.9 as a series of HDR contours, each containing an additional 10% of the probability mass.
Code
mu <- c(0, 0)
Sigma <- matrix(c(1, 0.5, 0.5, 1), 2, 2)
distributional::dist_multivariate_normal(list(mu), list(Sigma)) |>
gg_density(hdr = "fill") +
labs(
x = TeX("$y_1$"),
y = TeX("$y_2$"),
title = TeX("Contours of $f(y_1,y_2)$")
)
Similarly, we can obtain HDRs for a mixture distribution. Suppose we had two bivariate Normal distributions with means (0,0) and (3,1), and covariance matrices equal to \bm{\Sigma} = \begin{bmatrix} 1 & 0.5 \\ 0.5 & 1 \end{bmatrix} and the identity matrix \bm{I}_2 respectively. Then the HDRs for an equal mixture of these two distributions are shown in Figure 3.10.
Code
mu1 <- c(0, 0)
mu2 <- c(3, 1)
Sigma1 <- rbind(c(1, 0.5), c(0.5, 1))
Sigma2 <- diag(2)
mixture_density <- dist_mixture(
dist_multivariate_normal(mu = list(mu1), sigma = list(Sigma1)),
dist_multivariate_normal(mu = list(mu2), sigma = list(Sigma2)),
weights = c(0.5, 0.5)
)
mixture_plot <- mixture_density |>
gg_density(hdr = "fill") +
labs(
x = TeX("$y_1$"),
y = TeX("$y_2$"),
title = TeX("Contours of $f(y_1,y_2)$")
)
mixture_plot
Here, the 10%, 20%, 30% and 40% HDRs contain disconnected regions, but for the larger HDRs, there is just one region for each.
3.5 Multivariate quantiles
Unlike the univariate case, there is no unique definition of a multivariate quantile, because there is no natural way to order points in \mathbb{R}^m. Instead, multivariate quantiles are usually defined in a “centre-outward” way, so that a quantile describes a region containing a given probability, and the boundary of that region plays the role of a quantile. There are many different definitions, each with its own advantages and disadvantages (Serfling, 2002). Two of them will be particularly useful in this book.
The first uses the HDRs of the previous section. Because \Pr(\bm{Y} \in R_\alpha) = \Pr(f(\bm{Y}) \ge f_\alpha) = 1 - \alpha, the threshold f_\alpha is the \alpha quantile of the univariate random variable f(\bm{Y}), the density evaluated at a random observation. So the boundary of R_\alpha can be thought of as a multivariate quantile, and an observation lying outside R_\alpha for some small value of \alpha is in a region of low density. This idea is the basis of the density-based approach to anomaly detection that is developed in Chapter 7.
For a multivariate Normal distribution, the density is a decreasing function of (\bm{y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{y} - \bm{\mu}), so it follows from Equation 3.1 that R_\alpha = \left\{ \bm{y}: (\bm{y} - \bm{\mu})^\intercal\bm{\Sigma}^{-1}(\bm{y} - \bm{\mu}) \le \chi^2_{m,1-\alpha} \right\}, where \chi^2_{m,1-\alpha} is the (1 - \alpha) quantile of the \chi^2_m distribution. That is, the HDRs of a multivariate Normal distribution are ellipsoids centred on \bm{\mu}, such as the ellipses in Figure 3.9.
HDRs require the density to be known, or estimated. The second approach, based on data depth, works directly with a sample of observations, and does not require a density. This approach is discussed in Section 5.5.
3.6 Robust covariance estimation
The sample covariance matrix is a useful measure of the spread of a multivariate distribution, given by \bm{S} = \frac{1}{n - 1} \sum_{i=1}^n (\bm{y}_i - \bar{\bm{y}})(\bm{y}_i - \bar{\bm{y}})^\intercal. \tag{3.2} However, it is sensitive to anomalies, and so is not suitable for our purposes.
Many robust estimators of covariance have been proposed in the literature, but only one is discussed here: the Minimum Covariance Determinant (MCD) estimator (Rousseeuw & Leroy, 2003; Rousseeuw & van Driessen, 1999), which is implemented in the covMcd() function in the robustbase package (Maechler et al., 2026). This estimator finds the subset of h observations (where n/2 < h \le n) whose covariance matrix has the smallest determinant. The idea is that the subset of observations with the smallest covariance determinant is likely to be a subset of “good” observations, and so a covariance matrix computed from them will be robust to anomalies. If H denotes this subset, the raw MCD estimate of the covariance matrix is
\bm{S}_H
= \frac{c_H}{h} \sum_{i \in H} (\bm{y}_i - \bar{\bm{y}}_H)(\bm{y}_i - \bar{\bm{y}}_H)^\intercal,
where \bar{\bm{y}}_H is the mean of the observations in H. Because H deliberately leaves out the most outlying observations, the covariance of the observations in H underestimates the spread of the distribution, and c_H > 1 is a correction factor chosen so that \bm{S}_H is a consistent estimate of \bm{\Sigma} when the data come from a multivariate Normal distribution (with an additional adjustment for small samples).
The raw estimate uses only h observations, which makes it rather inefficient. So a reweighting step follows, in which every observation is compared to the raw estimate. Using Equation 3.1, an observation is retained if (\bm{y}_i - \bar{\bm{y}}_H)^\intercal\bm{S}_H^{-1}(\bm{y}_i - \bar{\bm{y}}_H) \le \chi^2_{m,0.975}, and dropped otherwise. If W is the set of n_W retained observations, with mean \bar{\bm{y}}_W, the final MCD estimate is
\bm{S}_{\text{MCD}}
= \frac{c_W}{n_W - 1} \sum_{i \in W} (\bm{y}_i - \bar{\bm{y}}_W)(\bm{y}_i - \bar{\bm{y}}_W)^\intercal,
\tag{3.3} where c_W is another correction factor. The covMcd() function returns \bm{S}_{\text{MCD}} (as cov) along with the raw estimate \bm{S}_H (as raw.cov). The subset size h is set via the argument alpha, with h \approx alpha \times\, n; the default alpha = 0.5 gives the most robust estimate, allowing almost half the observations to be anomalies. The mvscale() and kde_bandwidth() functions in the weird package use alpha = 0.9, allowing up to 10% of the observations to be anomalies, which gives a more efficient estimate, and the same value is used here.
To illustrate, consider a data set whose true distribution is known. It uses the first two variables of the n01 data set, v_1 and v_2, with y_1 = v_1 and y_2 = v_1 + v_2. Then (y_1,y_2) has a bivariate Normal distribution with mean (0,0) and covariance matrix \bm{\Sigma} = \begin{bmatrix} 1 & 1 \\ 1 & 2 \end{bmatrix} (using the results for linear transformations in Section 3.3), so the correlation between y_1 and y_2 is 1/\sqrt{2} \approx 0.71. The last 50 of the 1000 observations are then replaced with a small cluster of anomalies centred at (2,-2), constructed from two other variables in n01.
mcd_df <- n01 |>
transmute(y1 = v1, y2 = v1 + v2, anomaly = FALSE)
# Replace the last 50 observations with a cluster of anomalies
idx <- 951:1000
mcd_df$y1[idx] <- 2 + 0.3 * n01$v3[idx]
mcd_df$y2[idx] <- -2 + 0.3 * n01$v4[idx]
mcd_df$anomaly[idx] <- TRUE
# Sample and MCD estimates
mcd_y <- mcd_df |> select(y1, y2)
mcd_est <- robustbase::covMcd(mcd_y, alpha = 0.9)
cor(mcd_y) y1 y2
y1 1.0000 0.5061
y2 0.5061 1.0000
cov2cor(mcd_est$cov) y1 y2
y1 1.0000 0.6918
y2 0.6918 1.0000
The sample correlation has been pulled down to 0.51 by the anomalies, while the MCD estimate gives 0.69, close to the true value of 0.71. In the reweighting step, 49 of the 50 anomalies are dropped.
Because the bulk of these data really do come from a bivariate Normal distribution, we can use Equation 3.1 to draw the 95% HDR of the true distribution, and the corresponding ellipses obtained by plugging in the sample estimates and the MCD estimates of the mean and covariance matrix. These are shown in Figure 3.11.
Code
# Compute an ellipse containing 95% of a bivariate Normal distribution
ellipse <- function(centre, S, level = 0.95) {
theta <- seq(0, 2 * pi, length = 200)
r <- sqrt(qchisq(level, df = 2))
pts <- centre + r * t(chol(S)) %*% rbind(cos(theta), sin(theta))
tibble(y1 = pts[1, ], y2 = pts[2, ])
}
ellipses <- bind_rows(
ellipse(c(0, 0), matrix(c(1, 1, 1, 2), 2, 2)) |>
mutate(method = "True distribution"),
ellipse(colMeans(mcd_y), cov(mcd_y)) |> mutate(method = "Sample covariance"),
ellipse(mcd_est$center, mcd_est$cov) |> mutate(method = "MCD")
)
mcd_df |>
ggplot(aes(x = y1, y = y2)) +
geom_point(data = ~ filter(.x, !anomaly), colour = "#999999", alpha = 0.4) +
geom_point(data = ~ filter(.x, anomaly), colour = "black", alpha = 0.6) +
geom_path(data = ellipses, aes(colour = method), linewidth = 0.8) +
labs(
x = TeX("$y_1$"),
y = TeX("$y_2$"),
colour = ""
)
The MCD ellipse is almost identical to the true HDR, and all 50 anomalies lie outside it. In contrast, the ellipse based on the sample covariance matrix has been stretched towards the anomalies, and is less elongated because of the reduced correlation, so that some of the anomalies lie inside it.
3.7 Multivariate scaling
Some anomaly detection methods will require the data to have been scaled first, to prevent the variables with the largest ranges from dominating.
Z-scores
One common approach is to apply univariate scaling on each variable, by subtracting its mean and dividing by its standard deviation. This gives z-scores.
If our data are given by y_1,\dots,y_n, then their z-scores are given by
z_i = (y_i - \bar{y})/s_y
where \bar{y} is the mean and s_y is the standard deviation of the observations. These are easily computed using the scale() function.
However, the mean and standard deviation may be affected by anomalies, and it would be better to use an approach that was robust to anomalies.
Robust z-scores
The simplest way to make the scaling robust to anomalies is to use the median instead of the mean, and to use a robust estimate of the standard deviation such as Q_n (Section 2.8). Robust z-scores computed in this way can be obtained using the mvscale() function with the argument cov = NULL.
Multivariate z-scores
It is sometimes useful to scale a set of multivariate data, so that the scaled variables are uncorrelated with each other, and have mean zero and unit variance.
Suppose each observation is a vector \bm{y}_i, coming from a distribution with mean \bm{\mu} and covariance matrix \bm{\Sigma}. Let \bm{\Sigma}^{-1} = \bm{U}^\intercal \bm{U} be the Cholesky decomposition (see Section A.12) of \bm{\Sigma}^{-1}. Then the data can be scaled by \bm{U}, giving \bm{z}_i = \bm{U} (\bm{y}_i - \bm{\mu}), so that the covariance matrix of the scaled data is the identity matrix. This can be thought of as both scaling and rotating the data, so that the variables are uncorrelated with mean zero and unit variance. It is the multivariate equivalent of calculating z-scores. Multivariate z-scores can be computed using the mvscale() function with the arguments center = mean and cov = stats::cov.
Robust multivariate z-scores
When there may be anomalies in the data set, we can replace the mean by the pointwise median (i.e., the vector of medians for each variable), and estimate \bm{\Sigma} using the robust covariance matrix \bm{S}_{\text{MCD}} (Equation 3.3). The mvscale() function in the weird package will do this for us, by default.
Let’s consider the oldfaithful data again, where waiting times are much longer than durations. Figure 3.12 shows the data before and after scaling. The scaling has rotated the data a little, and the variables are now less correlated, and centred on zero. The right plot still appears to show some positive relationship between the variables, because the covariance matrix used for scaling was computed robustly, and so was based only on the upper cluster of points.
Code
p1 <- oldfaithful |>
ggplot(aes(x = duration, y = waiting)) +
geom_point(alpha = 0.2) +
labs(
title = "Original data",
x = "Duration of eruption (seconds)",
y = "Waiting time to next eruption (seconds)"
)
p2 <- mvscale(oldfaithful, warning = FALSE) |>
ggplot(aes(x = z1, y = z2)) +
geom_point(alpha = 0.2) +
labs(
title = "Scaled data",
x = TeX("$z_1$"),
y = TeX("$z_2$")
)
patchwork::wrap_plots(p1, p2, nrow = 1)
3.8 Clustering
Clustering methods group observations into distinct non-overlapping “clusters” based on their similarity. They are sometimes used for anomaly detection, as anomalies may form their own small clusters, or may appear as observations that do not belong to any cluster. Even if clustering is not used directly, some anomaly detection methods use tools based on clustering, and so we will need to understand some of the basic concepts. This section describes four of the most popular clustering methods: K-means clustering, the leader algorithm, DBSCAN, and hierarchical clustering.
The methods differ in what information must be supplied in advance. K-means requires the number of clusters, K. The leader algorithm and DBSCAN instead use a distance threshold, \delta, which defines a local neighbourhood around each observation. DBSCAN also uses a density parameter, M. Hierarchical clustering can be used to examine what happens across many possible values of a distance threshold.
K-means clustering
K-means clustering (Hartigan, 1975) partitions the data into K clusters, where K is a user-specified parameter. The algorithm begins by selecting K observations as initial “centroids”. Then, each observation is assigned to the cluster whose centroid is closest to it, based on some distance measure (usually Euclidean distance, but see Section 6.1 for other possibilities). After all observations have been assigned to clusters, the centroids are updated to be the mean of the observations in each cluster. This process is repeated until convergence, which occurs when the cluster assignments no longer change.
The K-means algorithm is relatively fast, but it can be sensitive to the choice of initial centroids, so it is common to run the algorithm several times using different random starts. It also assumes that the clusters are roughly spherical and of similar size, which may not always be the case. A further drawback, especially in the context of anomaly detection, is that anomalies can strongly affect the cluster centroids. The number of clusters, K, must also be specified in advance, which can be difficult to determine, and often requires some experimentation.
Leader algorithm
Rather than specify the number of clusters in advance, we can specify a maximum radius for each cluster, and then find clusters that satisfy this constraint. This is known as the leader algorithm (Hartigan, 1975), and is a fast, incremental clustering method that can be used for large data sets. The main input is \delta, the maximum distance from an observation to the leader of its cluster. The algorithm can be summarised as follows:
- Select the first observation as the first leader.
- For each subsequent observation:
- If the observation is within \delta of one or more existing leaders, assign it to the cluster of the nearest such leader.
- If the observation is not within \delta of any existing leader, make it the leader of a new cluster.
Thus, each cluster is defined by a leader and the observations assigned to that leader. The leaders remain fixed throughout the algorithm: they are observations from the original data, not cluster centroids. Every assigned observation is within \delta of its leader, so two observations in the same leader cluster can be up to 2\delta apart. The result depends on the order of the observations, since an observation that appears early in the data can become a leader and affect the assignment of all the observations that follow.
The leader algorithm is very fast because it makes only one pass through the data, although its speed also depends on how many leaders are created. It can be useful for anomaly detection because an isolated observation is not forced into a distant cluster: instead, it becomes the leader of a singleton or small cluster. However, this should not be interpreted as full robustness. An early anomaly can become a leader, and both the leaders and the resulting clusters depend on the ordering of the observations.
The leader() function from the probout package implements this algorithm. The function uses a strict comparison, requiring the distance to be less than radius, rather than less than or equal to it; this distinction is unimportant for continuous data unless a distance is exactly equal to the threshold. By default, leader() scales each variable to the unit interval, but we use scale = FALSE below because the data have already been converted to robust multivariate z-scores.
To compare K-means and the leader algorithm, we apply them to the Old Faithful data set in Figure 3.13. First, the data are converted to robust multivariate z-scores (Section 3.7) to prevent the waiting-time variable from dominating the clustering. K-means clustering is then applied with K = 2, while the leader algorithm is applied with \delta = 3.3, chosen after some experimentation. The leader() function returns each cluster as a vector of observation indices, so these partitions are converted to a vector of cluster labels for plotting.
Code
set.seed(12345)
of_scaled <- oldfaithful |>
select(duration, waiting) |>
mvscale()
km_clusters <- kmeans(of_scaled, centers = 2, nstart = 20)
leader_result <- probout::leader(
as.matrix(of_scaled),
radius = 3.3,
scale = FALSE
)[[1]]
leader_cluster <- integer(nrow(of_scaled))
for (k in seq_along(leader_result$partitions)) {
leader_cluster[leader_result$partitions[[k]]] <- k
}
oldfaithful |>
mutate(
km_cluster = factor(km_clusters$cluster),
leader_cluster = factor(leader_cluster)
) |>
tidyr::pivot_longer(
cols = c(km_cluster, leader_cluster),
names_to = "method",
values_to = "cluster"
) |>
mutate(
method = recode(
method,
km_cluster = "K-means clustering",
leader_cluster = "Leader clustering"
)
) |>
ggplot(aes(x = duration, y = waiting, colour = cluster)) +
geom_point() +
facet_wrap(~method) +
labs(x = "Duration (seconds)", y = "Waiting time (seconds)")
K-means forces every observation into one of the specified K = 2 clusters, so outlying observations can pull the cluster centroids towards themselves. The leader algorithm does not fix the number of clusters. An observation farther than \delta from every existing leader starts a new cluster, allowing isolated observations to form singleton or small clusters rather than being absorbed into one of the main clusters. Conversely, increasing K in K-means to match the number of leader clusters need not produce the same result: K-means may split the main clouds rather than separate the outlying observations.
DBSCAN clustering
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is a clustering method proposed by Ester et al. (1996) that identifies clusters as dense regions of nearby observations. Like the leader algorithm, it uses a neighbourhood radius \delta, but adds a density condition controlled by a second parameter M. It does not require the number of clusters to be specified in advance, and unlike K-means and the leader algorithm, it allows some observations to be left unclustered. These unclustered observations are called noise by the algorithm, and are often interpreted as potential anomalies. Note that this use of the word “noise” is different from the usual use of the word in statistics, where it refers to random variation in the data.
The algorithm has two main parameters: \delta, the radius of the neighbourhood around each observation, and M, the minimum number of observations required for a neighbourhood to be considered dense. For each observation \bm{y}_i, let N_{\delta}(\bm{y}_i) denote the number of observations within distance \delta of \bm{y}_i, including \bm{y}_i itself. An observation \bm{y}_i is classified as follows:
- it is a core observation if N_{\delta}(\bm{y}_i) \ge M;
- it is a border observation if it is not a core observation, but it is within distance \delta of at least one core observation;
- otherwise it is noise.
Clusters are formed by connecting nearby core observations that are within \delta of each other. Each connected group of core observations forms one cluster. Border observations are then attached to any cluster containing a core observation within distance \delta. If a border observation is within distance \delta of core observations from more than one cluster, its assignment may be arbitrary or implementation-dependent. Noise observations are not assigned to any cluster.
The DBSCAN algorithm is implemented in the dbscan() function in the dbscan package. Figure 3.14 shows the result for the Old Faithful data set, using \delta = 0.61 and M = 20 (again, chosen after some experimentation).
Code
dbscan_clusters <- dbscan::dbscan(of_scaled, eps = 0.61, minPts = 20)
oldfaithful |>
mutate(dbscan_cluster = factor(dbscan_clusters$cluster)) |>
ggplot(aes(x = duration, y = waiting, colour = dbscan_cluster)) +
geom_point() +
labs(x = "Duration (seconds)", y = "Waiting time (seconds)") +
scale_colour_manual(
values = c(
`0` = "#444444",
`1` = "#D55E0088",
`2` = "#0072B288"
),
labels = c(
`0` = "Noise",
`1` = "Cluster 1",
`2` = "Cluster 2"
)
) +
guides(colour = guide_legend(title = "DBSCAN cluster"))
The \delta-neighbourhood graph
Both the leader algorithm and DBSCAN can be understood using a graph (i.e., a network, not a plot). Each observation is a vertex, and we draw an edge between two vertices if the distance between the corresponding observations is at most \delta. This graph is sometimes called the \delta-neighbourhood graph. Points that can be reached from each other by following edges are said to be connected. A connected component is a group of vertices that are all connected to each other, but with no connections to vertices outside the group.
For example, consider the eight points labelled A to H shown in Figure 3.15, and suppose we choose \delta = 1.5. The blue disks centred on each point have radius \delta/2; so overlapping disks indicate that their central points are within \delta of each other. Points B and H form an edge, but are disconnected from all other points because they are further than \delta from the other points. The pair A and F also form an edge, and D is connected to them via F. They do not form a triangle because A and D are too far apart. The points C, E and G form a connected triangle.
The leader algorithm uses this graph in an order-dependent way. As observations (vertices) are processed, some become leaders. A new observation joins an existing leader if it is connected by an edge to at least one leader; otherwise, it becomes a new leader. This means leaders cannot be within \delta of each other. The output is a set of leader-centred, star-like clusters. These are not necessarily the same as the connected components of the full \delta-neighbourhood graph: observations in different leader clusters may still be connected by an edge, and a connected component may contain several leader clusters.
For these eight points, if we process in alphabetical order, A becomes the first leader. B, C and D also become leaders, since none are within \delta of an existing leader. The later observations E, F, G and H are assigned to existing leaders, giving clusters A–F, B–H, C–E–G, and D.
DBSCAN uses the same \delta-neighbourhood graph differently. It first identifies which vertices are core observations, using the density condition described above. Since the \delta-neighbourhood includes \bm{y}_i itself, a vertex is core when it has at least M - 1 neighbours in the graph. DBSCAN then forms clusters from connected groups of core vertices, and attaches any border vertices that are connected to those core groups. Sparse vertices that are not connected to any core vertex are labelled as noise. Thus, where the leader algorithm uses \delta to build clusters around selected representative vertices, DBSCAN uses \delta to build dense connected regions.
If we considered only the connected components of the \delta-neighbourhood graph, there would be three groups: A–F–D, C–E–G, and B–H. DBSCAN adds the density condition. With M = 3, F is a core observation because its \delta-neighbourhood contains A, F and D. The points C, E and G are also core observations because each of them has the other two points in its \delta-neighbourhood. By contrast, B and H are not core observations, because their \delta-neighbourhoods contain only B and H. They are not border observations either, because they are not connected to any core observation. Therefore, DBSCAN labels B and H as noise. So, for this example, DBSCAN gives two clusters and two noise observations:
- A–F–D is one cluster, with F as a core observation and A and D as border observations;
- C–E–G is another cluster, with all three points as core observations;
- B and H are noise observations.
This example illustrates the difference between a sparse group and a dense cluster. The pair B–H is a connected component of the \delta-neighbourhood graph, and may be a leader cluster, but it is not dense enough to be a DBSCAN cluster.
Hierarchical clustering
A related approach is to examine what happens as the distance threshold changes. If we ignore the DBSCAN density condition and simply take the connected components of the \delta-neighbourhood graph, then increasing the threshold gives a sequence of cluster mergers. This is the idea behind single-linkage hierarchical clustering.
Imagine slowly increasing a distance threshold \delta from 0 upwards. At \delta = 0, and assuming there are no duplicate observations, there are no edges, so every observation is its own cluster. As \delta increases, more edges appear, and clusters merge together. When an edge connects two clusters that were previously separate, those two clusters merge into one larger cluster. Eventually, all clusters merge into a single cluster.
For the small example of Figure 3.15, Figure 3.16 shows what happens as \delta increases from 0.5 to 2.0. With a small value of \delta, all points are disconnected, and the graph consists of eight vertices with no edges. As \delta increases, more points are connected to each other, and eventually, the graph consists of a single connected component.
In single-linkage hierarchical clustering, we start with each observation as its own cluster, and then repeatedly merge the two closest clusters together until we have one final cluster. The distance between two clusters when they merge is called the merge distance. For single-linkage clustering, the distance between two clusters is the minimum distance between any point in one cluster and any point in the other cluster.
This is different from DBSCAN in two important ways. First, single-linkage hierarchical clustering does not distinguish between core, border and noise observations — every observation belongs to some cluster at every stage, just as in K-means and the leader algorithm. Second, rather than fixing \delta in advance and returning a single partition of the data, hierarchical clustering records the complete sequence of partitions for all possible values of \delta, indexed by the merge distance. We can obtain a particular partition by cutting the hierarchy at a chosen merge distance, but the hierarchy itself shows how the clusters merge as \delta increases.
Other forms of hierarchical clustering use different measures of the distances between clusters. For example, complete-linkage is based on the maximum distance between any two points in the two clusters, while average-linkage is based on the average distance between all pairs of points across the two clusters. The graph interpretation above applies specifically to single-linkage hierarchical clustering.
Hierarchical clustering is usually displayed as a dendrogram, with the following properties:
- Each observation starts as a leaf.
- Branches join when two clusters merge.
- The axis showing the height of each join gives the merge distance.
The single-linkage dendrogram for the point cloud in Figure 3.15 is shown in Figure 3.17.
Figure 3.18 shows a bar plot of the cluster merge distances for the point cloud shown in Figure 3.15. These correspond to the merge heights in the dendrogram in Figure 3.17. The shortest distance corresponds to the merge of A and F, the first pair of vertices to be joined by an edge. The largest distance corresponds to when all points became connected, when the B–H component merged with the rest of the data. With n observations, there are n initial clusters, but only n - 1 merges are needed to end up with one final cluster. So we get n - 1 merge distances.
In the context of anomaly detection, observations or small groups that merge with the rest of the data only at large merge distances are potential anomalies. For example, in Figure 3.17, B and H form a small cluster that merges with the rest of the data only at the largest merge distance, so they are potential anomalies. By contrast, the other points merge together at smaller distances, so they are less likely to be anomalies.
3.9 Multivariate kernel density estimation
Suppose our observations are m-dimensional vectors, \bm{y}_1,\dots,\bm{y}_n. Then the multivariate version of Equation 2.4 is given by (Scott, 2015) \hat{f}(\bm{y}) = \frac{1}{n} \sum_{i=1}^n K_{\bm{H}}(\bm{y} - \bm{y}_i), \tag{3.4} where K_{\bm{H}} is a multivariate probability density with covariance matrix \bm{H}. This book uses a multivariate Gaussian kernel given by K_{\bm{H}}(\bm{u}) = (2\pi)^{-m/2} |\bm{H}|^{-1/2} \exp \{-\textstyle\frac12 \bm{u}^\intercal\bm{H}^{-1}\bm{u} \}.
Bivariate kernel density estimation
To illustrate the idea, consider a simple bivariate example of 10 observations: the first 10 eruption durations from 2021 that are in the oldfaithful data set, along with the corresponding waiting times until the following eruption. These are shown in Figure 3.19 along with the contours of bivariate kernels placed over each observation. Each kernel is a bivariate Gaussian density with bandwidth matrix \bm{H} = \left[\begin{array}{rr}728 & 10548 \\ 10548 & 202952\end{array}\right].
Code
h <- sqrt(diag(H))
k <- tidyr::expand_grid(
x = seq(-3 * h[1], 3 * h[1], l = 100),
y = seq(-3 * h[2], 3 * h[2], l = 100)
) |>
mutate(z = mvtnorm::dmvnorm(x = cbind(x, y), sigma = H))
of2021kde <- of2021 |>
mutate(k = list(k)) |>
tidyr::unnest(k) |>
mutate(x = x + duration, y = y + waiting)
ggplot() +
geom_contour(
data = of2021kde,
aes(x = x, y = y, group = eruption, z = z),
bins = 4,
col = "grey"
) +
geom_point(data = of2021, mapping = aes(x = duration, y = waiting)) +
labs(x = "Duration (seconds)", y = "Waiting time (seconds)")
oldfaithful data set.
If we add the bivariate kernel functions as in Equation 3.4, we obtain the bivariate kernel density estimate shown in Figure 3.20. The contours shown correspond to the 10%, 20%, \dots, 90% HDRs of the density estimate.
Code
oldfaithful |>
filter(as.Date(time) > "2021-01-01") |>
head(10) |>
select(duration, waiting) |>
dist_kde() |>
gg_density(show_points = TRUE) +
labs(x = "Duration (seconds)", y = "Waiting time (seconds)")
Now we will apply the method to the full data set, using the dist_kde() function, which uses a bivariate Gaussian kernel, and the bandwidth matrix given by the kde_bandwidth() function.
oldfaithful |>
select(duration, waiting) |>
dist_kde() |>
gg_density(show_points = TRUE) +
labs(x = "Duration (seconds)", y = "Waiting time (seconds)")
Here we see that the short durations tend to be followed by a short waiting time until the next eruption, while the long durations tend to be followed by a long waiting time until the next eruption. There are several anomalous eruptions including the one with the 1 second duration, and the one where a long duration was followed by a short waiting time. The unusual durations between 150 and 180 seconds can be followed by either short or long waiting times.
Bandwidth matrix selection
A common approach is to specify \bm{H} to be diagonal, with elements equal to the squares of univariate bandwidth rules. (The univariate bandwidths are usually defined as the standard deviation of the kernel, while multivariate bandwidth matrices correspond to the covariance matrix of the kernel. Hence, the univariate bandwidths need to be squared if used in a bandwidth matrix.) That is, if h_1,\dots,h_m are the univariate bandwidths for each of the variables, then the corresponding diagonal bandwidth matrix is given by \bm{H} = \text{diag}(h_1^2,\dots,h_m^2). For example, geom_density_2d() uses a bivariate Gaussian kernel with diagonal bandwidth matrix where the diagonal values are given by the squares of Equation 2.12. However, this approach leads to bandwidths that are too small, as it ignores the convergence properties of the multivariate estimator. Additionally, a diagonal bandwidth matrix cannot orient the kernels along the direction of any correlation between the variables, and so leads to more biased estimators when the variables are correlated.
The optimal bandwidth matrix (minimising the mean integrated squared error between the true density and its estimate) is of the order n^{-2/(m+4)}. If such a bandwidth matrix is used, then the mean integrated squared error of the estimator converges to zero at rate n^{-4/(m+4)}, implying that kernel density estimation becomes increasingly difficult as the dimension m increases. This is to be expected given the curse of dimensionality (Section 3.2), as the number of observations required to obtain a good estimate increases exponentially with the dimension. In practice, we rarely attempt to estimate a density in more than m = 3 dimensions.
If the underlying density is Normal with mean \bm{\mu} and covariance matrix \bm{\Sigma}, then the optimal bandwidth matrix is given by
\bm{H} = \left( \frac{4}{m + 2} \right)^{2/(m+4)} n^{-2/(m+4)} \bm{\Sigma}.
\tag{3.5} Notice that in the univariate case, when m = 1, this rule gives the same bandwidth as the rule of thumb given by Equation 2.5 (where \bm{H} = h^2). This is what is calculated by kde_bandwidth() when method = "normal", where \bm{\Sigma} is estimated using the sample covariance matrix (Equation 3.2).
Replacing \bm{\Sigma} in Equation 3.5 by the robust covariance matrix \bm{S}_{\text{MCD}} (Equation 3.3), we obtain a robust normal reference rule, calculated by kde_bandwidth() when method = "robust" (the default setting). Figure 3.21 shows a bivariate kernel density estimate computed using this approach.
A generalisation of the univariate plug-in bandwidth (Section 2.9) is the “plug-in” estimator of Chacón & Duong (2018), calculated by kde_bandwidth() when method = "plugin". While this typically leads to better estimates of the density as a whole, it can lead to worse estimates in the tails of the distribution where anomalies tend to lie.
An alternative approach to finding the bandwidth matrix uses ideas from clustering (Section 3.8). First, we compute robust multivariate z-scores, \bm{z}_i = \bm{U}(\bm{y}_i - \tilde{\bm{y}}), i = 1,\dots,n, where \tilde{\bm{y}} is a vector of medians of \{\bm{y}_1,\dots,\bm{y}_n\}, and \bm{U}^\intercal\bm{U} = \bm{S}_{\text{MCD}}^{-1} is the Cholesky decomposition of the inverse of the robust covariance matrix. Then we find the single-linkage merge distances (Section 3.8) of the z-scores: \{d_1,\dots,d_{n-1}\}. Finally, we can set
\bm{H} = d_\gamma^2\bm{S}_{\text{MCD}}
\tag{3.6} where d_\gamma is the sample quantile \hat{Q}(\gamma) computed from \{d_1,\dots,d_{n-1}\} for a large value of \gamma; kde_bandwidth() uses \gamma = 0.98, so that only about 2% of the merge distances are larger than d_\gamma. This bandwidth is matched to the spacing between neighbouring observations in the sparse parts of the data, where anomalies lie, rather than to the bulk of the data. It does not give a consistent estimate of the density as n \rightarrow \infty, but Hyndman et al. (2026) argue that consistency is not needed for anomaly detection, and show in simulations that it works well for that purpose. This is called the lookout bandwidth, because it is the basis of the lookout anomaly detection algorithm described in Section 7.5. The kde_bandwidth() function will return this bandwidth when method = "lookout". For univariate data, h = d_\gamma Q_n.
oldfaithful |>
select(duration, waiting) |>
dist_kde(method = "lookout") |>
gg_density(show_points = TRUE) +
labs(x = "Duration (seconds)", y = "Waiting time (seconds)")
Notice that the contours in Figure 3.22 are larger and smoother than in Figure 3.21. Whether the lookout bandwidth is larger or smaller than a normal reference bandwidth depends on the dimension and sample size; what matters for anomaly detection is that it is matched to the spacing of observations in the tails.
Further reading
There is a rich literature on multivariate kernel density estimation. Good starting points are Scott (2015) or Chacón & Duong (2018). The idea of using the cluster merge distances to compute the bandwidth matrix is due to Kandanaarachchi & Hyndman (2022), who framed it in terms of topological data analysis, and Hyndman et al. (2026), who expressed it using the minimum spanning tree (equivalently, single-linkage clustering).
3.10 Conditional probability distributions
A fundamental concept in statistics is a conditional probability distribution; that is, the distribution of a random variable conditional on the values of other (possibly random) variables.
Almost all statistical modelling involves the estimation of conditional distributions. For example, a regression is a model for the conditional distribution of a response variable given the values of a set of predictor variables. In its simplest form, we assume the conditional distribution is Normal, with constant variance, and mean equal to a linear function of the predictor values. Generalised linear models allow for non-Normal conditional distributions, while generalised additive models allow for non-linear relationships between the response and the predictors.
The conditional cdf of Y given X_1,\dots,X_p is defined by F(y \mid x_1, \dots, x_p) = \Pr(Y \le y \mid X_1 = x_1, \dots, X_p = x_p). The conditional pdf is given by f(y \mid x_1, \dots, x_p) = \frac{f(y, x_1, \dots, x_p)}{f(x_1, \dots, x_p)}. The conditional pdf can be thought of as slices of the joint pdf, with the values of x_1,\dots,x_p fixed, rescaled to ensure the conditional pdfs integrate to 1. For example, f(y_1 \mid y_2) is equal to a scaled slice of the joint pdf f(y_1,y_2) at y_2. Figure 3.23 shows some examples for the distribution shown in Figure 3.10 at several values of y_2. The left plot shows the joint density, with horizontal lines indicating where conditioning (or slicing) occurs at different values of y_2. The right plot shows the resulting conditional density functions.
Code
# Conditioning points
y2_slice <- -2:3
# Compute bivariate density over a grid
df <- expand.grid(
y1 = seq(-3, 6, length = 100),
y2 = y2_slice
)
df$density <- density(mixture_density, at = as.matrix(df))[[1]]
# Scaling factor for each density
scale_cond_density <- df |>
summarise(scale = sum(density), .by = y2) |>
mutate(scale = scale / max(scale))
# Scale each conditional density
df <- df |>
left_join(scale_cond_density, by = "y2") |>
mutate(
density = density / scale,
density = density / max(density) * 0.9
)
# Joint density plot
plot1 <- mixture_plot +
guides(fill = "none") +
scale_y_continuous(breaks = y2_slice, minor_breaks = NULL) +
coord_cartesian(xlim = c(-2.6, 5.5), ylim = c(-2.6, 3.6)) +
geom_hline(
aes(yintercept = y2),
data = tibble(y2 = y2_slice),
colour = "#4c93bb"
)
# Conditional density plots
plot2 <- df |>
ggplot(aes(x = y1, y = density + y2, group = y2)) +
geom_ribbon(
aes(ymin = y2, ymax = density + y2, xmin = -2, xmax = 4),
col = "#4c93bb",
fill = "#4c93bb"
) +
labs(
x = TeX("$y_1$"),
y = TeX("$y_2$"),
title = TeX("Conditional densities: $f(y_1|y_2)$")
) +
scale_y_continuous(minor_breaks = NULL, breaks = y2_slice) +
coord_cartesian(xlim = c(-2.6, 5.5), ylim = c(-2.6, 3.6))
# Show plots side by side
patchwork::wrap_plots(plot1, plot2, nrow = 1)
For the mixture distribution in Figure 3.23, the conditional densities change shape as y_2 changes, and some of them are bimodal.
For a multivariate Normal distribution, the conditional distributions are also Normal. Using the partition of \bm{Y}, \bm{\mu} and \bm{\Sigma} from Section 3.3, the conditional distribution of \bm{Y}_1 given \bm{Y}_2 = \bm{y}_2 is \bm{Y}_1 \mid \bm{Y}_2 = \bm{y}_2 \sim \text{N}\left( \bm{\mu}_1 + \bm{\Sigma}_{12}\bm{\Sigma}_{22}^{-1}(\bm{y}_2 - \bm{\mu}_2),\; \bm{\Sigma}_{11} - \bm{\Sigma}_{12}\bm{\Sigma}_{22}^{-1}\bm{\Sigma}_{21} \right). \tag{3.7} So the conditional mean in Equation 3.7 is a linear function of \bm{y}_2, while the conditional covariance matrix does not depend on \bm{y}_2 at all. That is, the slices of a multivariate Normal density are all Normal densities with the same variance, and with means lying on a straight line. This is the basis of linear regression with Normal errors.
Conditional distributions will be important when we come to define anomalies in the presence of other information. In Chapter 8, an anomaly is an observation that is unusual given the values of its predictors, while in Chapter 12, an anomaly is an observation that is unusual given the past history of the series. In both cases, we need the conditional distribution of the observation, not its marginal distribution.