7 Cluster Analysis
R code for this chapter: clustering_figures.R (data and figures) and _common.R (shared helpers). Save both in one folder and run source("clustering_figures.R"); every figure is then one function call, as shown under the Code buttons.
Slides for this chapter: clustering_slides.html (opens in a new tab; use the arrow keys to move between slides).
Some data come in groups. The penguins of Chapter 2 belong to three species, and their bill measurements form three hills, one for each species. Cluster analysis looks for such groups when nobody has told us the labels: it sorts the observations into clusters, so that observations in the same cluster are close to each other and observations in different clusters are not.
The Introduction described clustering as a model with a discrete latent variable (Section 1.7.2), and this chapter starts from there. It then presents three ways to find clusters. Hierarchical clustering merges the closest observations, step by step, into larger and larger clusters. k-means describes each cluster by its centre and puts each observation in the cluster of the nearest centre. Model-based clustering writes down a model, a mixture of normal distributions, and estimates it by maximum likelihood, which also gives a way to choose the number of clusters. The three methods are first tried on the penguins, where the species let us check the answer, and then on the US states of Chapter 2, where no answer is known.
7.1 Groups behind the data
7.1.1 A discrete latent variable
In the factor model of Chapter 6, a continuous latent variable moves the observed variables. With one factor \(f_t\) and loadings \(\lambda\), observation \(t\) lies at \(\lambda f_t\) plus its unique shocks, and as \(f_t\) varies, this centre slides along a line. In a cluster model the latent variable is discrete: each observation belongs to one of a few groups, and its centre jumps among a few points, which need not lie on a line. The Introduction showed the three cases side by side:
fig_factor_to_cluster <- function() {
set.seed(11)
lam_b <- c(1.2, 0.8); psi_b <- 0.22
circle_at <- function(mu, r = sqrt(psi_b) * sqrt(qchisq(0.8, 2)))
tibble(x1 = mu[1] + r * cos(seq(0, 2 * pi, length.out = 120)),
x2 = mu[2] + r * sin(seq(0, 2 * pi, length.out = 120)))
f_draw <- rnorm(240)
cont_pts <- tibble(x1 = lam_b[1] * f_draw + rnorm(240, sd = sqrt(psi_b)),
x2 = lam_b[2] * f_draw + rnorm(240, sd = sqrt(psi_b)), f = f_draw)
cont_circ <- purrr::map_dfr(c(-1.5, -0.75, 0, 0.75, 1.5), function(f)
circle_at(lam_b * f) |> mutate(g = f))
on_centers <- tibble(g = c("1", "2", "3"), x1 = lam_b[1] * c(-1.5, 0, 1.5), x2 = lam_b[2] * c(-1.5, 0, 1.5))
off_centers <- tibble(g = c("1", "2", "3"), x1 = c(-1.8, 1.5, 1.3), x2 = c(0.3, 1.5, -1.6))
draw_clusters <- function(centers, n = 80) purrr::map_dfr(seq_len(nrow(centers)), function(i)
tibble(g = centers$g[i],
x1 = centers$x1[i] + rnorm(n, sd = sqrt(psi_b)),
x2 = centers$x2[i] + rnorm(n, sd = sqrt(psi_b))))
on_pts <- draw_clusters(on_centers)
off_pts <- draw_clusters(off_centers)
circles_for <- function(centers) purrr::map_dfr(seq_len(nrow(centers)), function(i)
circle_at(c(centers$x1[i], centers$x2[i])) |> mutate(g = centers$g[i]))
factor_line <- geom_line(data = tibble(x1 = lam_b[1] * c(-2.4, 2.4), x2 = lam_b[2] * c(-2.4, 2.4)),
aes(x1, x2), colour = col_f, linetype = 2)
pal3 <- c("1" = "#1b9e77", "2" = "#d95f02", "3" = "#7570b3")
lims <- coord_equal(xlim = c(-3.2, 3.2), ylim = c(-2.6, 2.6))
p1 <- ggplot() + factor_line +
geom_point(data = cont_pts, aes(x1, x2, colour = f), size = 1.3, alpha = 0.8) +
geom_path(data = cont_circ, aes(x1, x2, group = g), colour = "grey25", linewidth = 0.6) +
scale_colour_gradient2(low = "#b35806", mid = "#d4d4d4", high = "#542788", guide = "none") +
lims + labs(title = "Continuous factor", subtitle = "Centers λf slide\nalong the line", x = expression(italic(x)[1]), y = expression(italic(x)[2]))
p2 <- ggplot() + factor_line +
geom_point(data = on_pts, aes(x1, x2, colour = g), size = 1.3, alpha = 0.8) +
geom_path(data = circles_for(on_centers), aes(x1, x2, group = g), colour = "grey25", linewidth = 0.8) +
scale_colour_manual(values = pal3, guide = "none") +
lims + labs(title = "Clusters on the line", subtitle = "The center jumps\namong three points", x = expression(italic(x)[1]), y = expression(italic(x)[2]))
p3 <- ggplot() +
geom_point(data = off_pts, aes(x1, x2, colour = g), size = 1.3, alpha = 0.8) +
geom_path(data = circles_for(off_centers), aes(x1, x2, group = g), colour = "grey25", linewidth = 0.8) +
scale_colour_manual(values = pal3, guide = "none") +
lims + labs(title = "Clusters anywhere", subtitle = "No single line\nexplains the cloud", x = expression(italic(x)[1]), y = expression(italic(x)[2]))
p1 + p2 + p3
}
# draw the figure
fig_factor_to_cluster()
On the left, the centres \(\lambda f\) slide along the dashed line, and the points spread along it. In the middle, the centre takes only three values, all on the line, and the points form three separate clouds. On the right, the three centres lie anywhere, and no single line explains the cloud. The circles show the spread of the points around a few of the centres.
7.1.2 The cluster model
Write \(k\) for the number of groups, numbered \(l=1,\dots,k\). Each observation belongs to exactly one group, and \(g_t\) records which one:
\[ g_t=\begin{cases} 1 & \text{if observation } t \text{ belongs to group } 1,\\ 2 & \text{if observation } t \text{ belongs to group } 2,\\ \vdots & \\ k & \text{if observation } t \text{ belongs to group } k. \end{cases} \]
Read \(g_t\) as a function of \(t\): give it the number of an observation, \(t=1,\dots,n\), and it returns the number of that observation’s group. The numbers only name the groups, so numbering the groups in another order describes the same grouping.
Each group has its own mean for each variable: \(\mu_{li}\) is the mean of variable \(i\) in group \(l\). With two variables, observation \(t\) is
\[ \begin{aligned} x_{t1}&=\mu_{g_t1}+u_{t1},\\ x_{t2}&=\mu_{g_t2}+u_{t2}, \end{aligned} \]
where \(u_{t1}\) and \(u_{t2}\) are its deviations from the means of its group. The first subscript of \(\mu\) names a group, and \(g_t\) puts the group of observation \(t\) there: \(\mu_{g_ti}\) is the mean of variable \(i\) in the group of observation \(t\). If penguin \(t\) belongs to group 2, for example, then \(g_t=2\), and its bill length is \(x_{t1}=\mu_{21}+u_{t1}\): the mean bill length of group 2 plus its own deviation. With \(p\) variables, collect the means of group \(l\) in the vector \(\mu_l=(\mu_{l1},\dots,\mu_{lp})'\) and the deviations of observation \(t\) in \(\mathbf u_t\):
\[ \mathbf x_t=\mu_{g_t}+\mathbf u_t . \]
Here \(\mathbf x_t\) is the observation as measured, not centred, so the group means also carry the overall level of the variables. The deviations have mean zero, and within group \(l\) their covariance matrix is \(\Sigma_l\), which sets the size, the shape and the tilt of the group’s cloud. The share of group \(l\) is the probability that an observation belongs to it, \(\pi_l=P(g_t=l)\), and the shares add up to one.
The factor model of Chapter 6, \(\mathbf x_t=\Lambda\mathbf f_t+\mathbf u_t\), has the same form. Its centre is \(\Lambda\mathbf f_t\): setting \(\mu_{g_t}=\Lambda\mathbf f_t\) turns the cluster model into the factor model. The difference is where the centre can be. In the factor model, \(\Lambda\mathbf f_t\) can be any point of a line or a plane, but it cannot leave that line or plane. In the cluster model, \(\mu_{g_t}\) is one of only \(k\) points, \(\mu_1,\dots,\mu_k\), but these points can lie anywhere in space, as in the right panel of the figure above. The cluster model has fewer centres, but more freedom in where they lie.
The groups \(g_t\) are latent: the data show only the observations \(\mathbf x_t\). Cluster analysis estimates the group of each observation, and the group means, from the observations alone. Factor analysis looks for groups of variables that move together, because they depend on the same continuous latent factor. Cluster analysis looks for groups of observations that lie together, because they have the same value of the discrete latent variable: the same group \(g_t\), and so the same centre \(\mu_{g_t}\).
7.1.3 Three hills
Chapter 3 estimated the density of the bill length and bill depth of the 333 penguins (Section 3.4). The density has three hills, and colouring the penguins by species shows that each hill is one species:
fig_kde_contour <- function(colour_species = FALSE) {
p <- ggplot() +
geom_contour_filled(data = peng_kde$df, aes(x, y, z = z), bins = 9, alpha = 0.85) +
scale_fill_manual(values = colorRampPalette(c("white", "#c6dbef", "#6baed6", "#2171b5", "#08306b"))(9),
guide = "none")
p <- if (colour_species) {
p + geom_point(data = peng, aes(bill_length_mm, bill_depth_mm, colour = species), size = 1.2, alpha = 0.8) +
scale_colour_manual(values = pal_species, name = NULL) +
theme(legend.position = c(0.86, 0.9), legend.background = element_rect(fill = "white", colour = NA))
} else {
p + geom_point(data = peng, aes(bill_length_mm, bill_depth_mm), colour = "grey20", size = 0.9, alpha = 0.6)
}
p + coord_cartesian(xlim = c(31, 61), ylim = c(13, 22), expand = FALSE) +
labs(x = "bill length (mm)", y = "bill depth (mm)")
}
# draw the figure
fig_kde_contour(colour_species = TRUE)
The species are Adelie (146 penguins), Chinstrap (68) and Gentoo (119). In the language of the model, \(k=3\), \(g_t\) is the species of penguin \(t\), \(\mu_l\) holds the mean bill length and depth of species \(l\), and \(\pi_l\) is the share of species \(l\). Since the species are known, the penguins make a good test. Each method of this chapter sees only the measurements, and afterwards we check how well its clusters match the species.
The hills suggest how to find the groups: an observation belongs with the observations close to it. The next three sections turn “close” into three methods.
Check your understanding
- In the cluster model \(\mathbf x_t=\mu_{g_t}+\mathbf u_t\), the latent variable \(g_t\) is
- a continuous factor, like the quality of a restaurant in Chapter 6
- the group of observation \(t\), one of the numbers \(1,\dots,k\)
- the distance between two observations
- the number of groups
- Factor analysis and cluster analysis both look for structure. Cluster analysis groups
- the variables that move together
- the observations that lie together
- the correlations
- the principal components
Answers
1 b. 2 b.7.2 Hierarchical clustering
7.2.1 Merging step by step
Start with every observation in a cluster of its own. Then repeat one step: merge the two clusters that are closest to each other. After \(n-1\) merges, all \(n\) observations form a single cluster. This is agglomerative hierarchical clustering (Everitt and Hothorn, Section 6.3).
“Closest” needs a distance. Between two observations \(s\) and \(t\), take the Euclidean distance of Chapter 5 (Section 5.2):
\[ d_{st}=\lVert\mathbf x_s-\mathbf x_t\rVert=\sqrt{\sum_{i=1}^p(x_{si}-x_{ti})^2} . \]
Once a cluster has several members, we also need a distance between clusters. For now, take the average of the distances between their members (average linkage). Section 7.2.2 shows other choices.
Here are the bill length and depth of ten of the penguins, numbered from the shortest bill to the longest. Move the slider to step through the merges. The left panel shows the clusters, with the newest one in yellow, and the right panel records each merge.
f2 <- function(x, d = 2) formatC(x, format = "f", digits = d)
as_path <- function(d) tibble(x = as.vector(rbind(d$x, d$xend, NA)), y = as.vector(rbind(d$y, d$yend, NA)))
blob <- function(P, r, sx, sy) {
a <- seq(0, 2 * pi, length.out = 25)[-25]
Q <- do.call(rbind, lapply(seq_len(nrow(P)), function(i) cbind(P[i, 1] + r * sx * cos(a), P[i, 2] + r * sy * sin(a))))
h <- chull(Q); Q[c(h, h[1]), , drop = FALSE]
}
dendro_segments <- function(hc) {
n <- length(hc$order); pos <- match(seq_len(n), hc$order); mid <- numeric(n - 1)
x_of <- function(m) if (m < 0) pos[-m] else mid[m]
h_of <- function(m) if (m < 0) 0 else hc$height[m]
out <- vector("list", n - 1)
for (i in seq_len(n - 1)) {
a <- hc$merge[i, 1]; b <- hc$merge[i, 2]
mid[i] <- (x_of(a) + x_of(b)) / 2
out[[i]] <- tibble(step = i, x = c(x_of(a), x_of(b), x_of(a)), xend = c(x_of(a), x_of(b), x_of(b)),
y = c(h_of(a), h_of(b), hc$height[i]), yend = rep(hc$height[i], 3))
}
bind_rows(out)
}
merge_members <- function(hc) {
mem <- vector("list", nrow(hc$merge))
for (i in seq_len(nrow(hc$merge)))
mem[[i]] <- unlist(lapply(hc$merge[i, ], function(m) if (m < 0) -m else mem[[m]]))
mem
}
fig_hc_small <- function() {
hc <- hc_small; n <- nrow(hc_X); mem <- merge_members(hc); seg <- dendro_segments(hc)
xr <- c(35, 54.5); yr <- c(12.5, 22.5); col_new <- "#e6ab02"
steps <- 0:(n - 1)
cut_at <- function(s) if (s == 0) hc$height[1] / 2 else if (s < n - 1) (hc$height[s] + hc$height[s + 1]) / 2 else
hc$height[n - 1] + 0.6
empty <- function(s) tibble(x = -100, y = -100, s = s) # a point outside the plot, so that every frame has data
blobs <- purrr::map_dfr(steps, function(s) {
cl <- cutree(hc, k = n - s)
purrr::map_dfr(unique(cl), function(g) {
B <- blob(hc_X[cl == g, , drop = FALSE], 0.04, diff(xr), diff(yr))
tibble(x = c(B[, 1], NA), y = c(B[, 2], NA))
}) |> mutate(s = s)
})
newest <- purrr::map_dfr(steps, function(s) if (s == 0) empty(0) else {
B <- blob(hc_X[mem[[s]], , drop = FALSE], 0.04, diff(xr), diff(yr)); tibble(x = B[, 1], y = B[, 2], s = s) })
done <- purrr::map_dfr(steps, function(s) if (s == 0) empty(0) else as_path(filter(seg, step <= s)) |> mutate(s = s))
last <- purrr::map_dfr(steps, function(s) if (s == 0) empty(0) else as_path(filter(seg, step == s)) |> mutate(s = s))
cut_line <- purrr::map_dfr(steps, function(s) tibble(x = c(0.5, n + 0.5), y = cut_at(s), s = s))
info <- tibble(x = 0.7, y = 11.9, s = steps,
txt = ifelse(steps == 0, "10 clusters: each penguin alone",
sprintf("%d %s, merge %d at height %s mm", n - steps, ifelse(steps == n - 1, "cluster", "clusters"),
steps, f2(hc$height[pmax(steps, 1)]))))
pts <- tibble(x = hc_X[, 1], y = hc_X[, 2], lab = rownames(hc_X),
pos = ifelse(lab == "1", "top left", ifelse(lab == "2", "bottom right", "top right")))
scatter <- plot_ly() |>
add_trace(data = blobs, x = ~x, y = ~y, frame = ~s, type = "scatter", mode = "lines", fill = "toself",
fillcolor = "rgba(120,120,120,0.16)", line = list(color = "#9a9a9a", width = 1),
hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = newest, x = ~x, y = ~y, frame = ~s, type = "scatter", mode = "lines", fill = "toself",
fillcolor = "rgba(230,171,2,0.30)", line = list(color = col_new, width = 2),
hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = pts, x = ~x, y = ~y, text = ~lab, type = "scatter", mode = "markers+text",
textposition = ~pos, marker = list(color = "#333333", size = 7),
textfont = list(size = 12, color = "#333333"), hoverinfo = "skip", showlegend = FALSE)
dendro <- plot_ly() |>
add_trace(data = as_path(seg), x = ~x, y = ~y, type = "scatter", mode = "lines",
line = list(color = "#dddddd", width = 1.5), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = done, x = ~x, y = ~y, frame = ~s, type = "scatter", mode = "lines",
line = list(color = "#333333", width = 2), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = last, x = ~x, y = ~y, frame = ~s, type = "scatter", mode = "lines",
line = list(color = col_new, width = 4), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = cut_line, x = ~x, y = ~y, frame = ~s, type = "scatter", mode = "lines",
line = list(color = col_a2, width = 1.5, dash = "dash"), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = info, x = ~x, y = ~y, frame = ~s, text = ~txt, type = "scatter", mode = "text",
textposition = "middle right", textfont = list(size = 12, color = "#2c3e50"),
hoverinfo = "skip", showlegend = FALSE)
jump <- function(lab, s) list(label = lab, method = "animate",
args = list(list(as.character(s)), list(mode = "immediate",
frame = list(duration = 0, redraw = TRUE), transition = list(duration = 0))))
subplot(scatter, dendro, nrows = 1, widths = c(0.5, 0.5), margin = 0.07, titleX = TRUE, titleY = TRUE) |>
layout(xaxis = list(title = lab_len, range = xr, zeroline = FALSE),
yaxis = list(title = lab_dep, range = yr, zeroline = FALSE),
xaxis2 = list(title = "penguin", tickvals = seq_len(n), ticktext = rownames(hc_X)[hc$order],
range = c(0.4, n + 0.6), zeroline = FALSE, showgrid = FALSE),
yaxis2 = list(title = "distance between clusters (mm)", range = c(0, 12.4), zeroline = FALSE),
margin = list(t = 50)) |>
animation_opts(frame = 700, transition = 0, redraw = TRUE) |>
animation_slider(currentvalue = list(prefix = "merges done: ")) |>
animation_button(label = "Play") |>
finalize_animation(list(jump("10 clusters", 0), jump("3 clusters", n - 3), jump("1 cluster", n - 1)),
start_frame = "0", prefix = "merges done: ")
}
# draw the figure
fig_hc_small()The right panel is a dendrogram, a tree of the merges. Each merge is drawn as a bracket at the height of the distance between the two clusters it joins. Penguins 1 and 2 merge first: their bills differ by 0.4 mm in length and 0.3 mm in depth, so \(d_{12}=\sqrt{0.4^2+0.3^2}=0.5\) mm. Clusters that are far apart merge last, high up in the tree.
Cutting the tree at a height gives clusters: every merge below the cut has been made, and none above it. The dashed line at three clusters cuts three branches, and they are the three species: penguins 1 to 4 are Adelie, 5 to 7 Gentoo and 8 to 10 Chinstrap. A long stretch of the tree without merges, as below the two highest brackets, means that the clusters at that level are well apart.
The clusters are nested: each of the three clusters is a union of clusters one step earlier, and so on down. One run gives the clusters for every number of clusters at once. A merge, once made, is never undone, though.
7.2.2 The distance between two clusters
Write \(G\) and \(H\) for two clusters, with \(n_G\) and \(n_H\) members. The distance between them, called the linkage, can be defined in several ways. Four are common:
- Single linkage: the distance of the closest pair, one member from each cluster, \(d(G,H)=\min_{s\in G,\,t\in H}d_{st}\).
- Complete linkage: the distance of the farthest pair, \(d(G,H)=\max_{s\in G,\,t\in H}d_{st}\).
- Average linkage: the average over all \(n_Gn_H\) pairs, \(d(G,H)=\frac{1}{n_Gn_H}\sum_{s\in G}\sum_{t\in H}d_{st}\).
- Ward’s method: merge the two clusters for which the spread within the clusters grows least.
fig_linkage <- function(ncol = 4, base = 13) {
pairs <- expand_grid(s = 1:nrow(link_G), t = 1:nrow(link_H)) |>
mutate(x = link_G[s, 1], y = link_G[s, 2], xend = link_H[t, 1], yend = link_H[t, 2],
d = sqrt((x - xend)^2 + (y - yend)^2))
pts <- bind_rows(tibble(x = link_G[, 1], y = link_G[, 2], g = "G"), tibble(x = link_H[, 1], y = link_H[, 2], g = "H"))
mG <- colMeans(link_G); mH <- colMeans(link_H)
base_plot <- function(title, subtitle) ggplot() +
geom_point(data = pts, aes(x, y, colour = g), size = 2.6) +
annotate("text", x = c(0.55, 6.15), y = c(2.75, 2.75), label = c("G", "H"), size = 5, fontface = "bold",
colour = pal_cl[1:2]) +
scale_colour_manual(values = c(G = unname(pal_cl[1]), H = unname(pal_cl[2])), guide = "none") +
coord_equal(xlim = c(0.3, 6.4), ylim = c(0.1, 3.3)) +
labs(title = title, subtitle = subtitle, x = NULL, y = NULL) +
theme_minimal(base_size = base) +
theme(axis.text = element_blank(), panel.grid = element_blank(), plot.title = element_text(face = "bold"))
p1 <- base_plot("Single", "the closest pair") +
geom_segment(data = pairs, aes(x, y, xend = xend, yend = yend), colour = "grey85", linewidth = 0.3) +
geom_segment(data = slice_min(pairs, d), aes(x, y, xend = xend, yend = yend), colour = "grey10", linewidth = 1.2)
p2 <- base_plot("Complete", "the farthest pair") +
geom_segment(data = pairs, aes(x, y, xend = xend, yend = yend), colour = "grey85", linewidth = 0.3) +
geom_segment(data = slice_max(pairs, d), aes(x, y, xend = xend, yend = yend), colour = "grey10", linewidth = 1.2)
p3 <- base_plot("Average", sprintf("the mean of all %d pairs", nrow(pairs))) +
geom_segment(data = pairs, aes(x, y, xend = xend, yend = yend), colour = "grey35", linewidth = 0.45)
p4 <- base_plot("Ward", "how much W would rise") +
geom_segment(aes(x = mG[1], y = mG[2], xend = mH[1], yend = mH[2]), colour = "grey10", linewidth = 1.2) +
annotate("point", x = c(mG[1], mH[1]), y = c(mG[2], mH[2]), shape = 4, size = 5, stroke = 1.6,
colour = pal_cl[1:2])
# put the layers of points on top
lift <- function(p) { p$layers <- c(p$layers[-1], p$layers[1]); p }
wrap_plots(lift(p1), lift(p2), lift(p3), lift(p4), ncol = ncol)
}
# draw the figure
fig_linkage()
Ward’s method measures the spread within the clusters by the within-cluster sum of squares \(W\): the sum of the squared distances of the observations from the mean of their cluster. Write \(\bar x_{li}\) for the mean of variable \(i\) over the observations in cluster \(l\), and \(\bar{\mathbf x}_l\) for the vector of these means. Then
\[ W=\sum_{l=1}^k\ \sum_{t\text{ in cluster }l}\ \sum_{i=1}^p\big(x_{ti}-\bar x_{li}\big)^2 =\sum_{l=1}^k\ \sum_{t\text{ in cluster }l}\big\lVert\mathbf x_t-\bar{\mathbf x}_l\big\rVert^2 . \]
Merging \(G\) and \(H\) raises \(W\) by
\[ \frac{n_Gn_H}{n_G+n_H}\,\big\lVert\bar{\mathbf x}_G-\bar{\mathbf x}_H\big\rVert^2 , \]
where \(\bar{\mathbf x}_G\) and \(\bar{\mathbf x}_H\) are the means of the two clusters. So Ward’s method merges clusters whose means are close, and among those it prefers small clusters. The same \(W\) is what k-means minimises (Section 7.3).
Why merging raises W by this amount
For the observations of \(G\), the sum of squared distances from any point \(\mathbf m\) splits into two parts,
\[ \sum_{t\in G}\lVert\mathbf x_t-\mathbf m\rVert^2=\sum_{t\in G}\lVert\mathbf x_t-\bar{\mathbf x}_G\rVert^2 +n_G\lVert\bar{\mathbf x}_G-\mathbf m\rVert^2 , \]
because the cross term contains \(\sum_{t\in G}(\mathbf x_t-\bar{\mathbf x}_G)\), which is zero. After the merge, the observations of both clusters are measured from the joint mean \(\mathbf m=(n_G\bar{\mathbf x}_G+n_H\bar{\mathbf x}_H)/(n_G+n_H)\), so \(W\) rises by \(n_G\lVert\bar{\mathbf x}_G-\mathbf m\rVert^2+n_H\lVert\bar{\mathbf x}_H-\mathbf m\rVert^2\). With \(\bar{\mathbf x}_G-\mathbf m=n_H(\bar{\mathbf x}_G-\bar{\mathbf x}_H)/(n_G+n_H)\) and \(\bar{\mathbf x}_H-\mathbf m=-n_G(\bar{\mathbf x}_G-\bar{\mathbf x}_H)/(n_G+n_H)\), the rise is \(\frac{n_Gn_H^2+n_Hn_G^2}{(n_G+n_H)^2}\lVert\bar{\mathbf x}_G-\bar{\mathbf x}_H\rVert^2 =\frac{n_Gn_H}{n_G+n_H}\lVert\bar{\mathbf x}_G-\bar{\mathbf x}_H\rVert^2\).
7.2.3 All 333 penguins
Now take all four measurements of every penguin: bill length, bill depth, flipper length and body mass. They come in different units, millimetres and grams, and the Euclidean distance adds them up as they are: a difference of 100 g in body mass, which is small, counts as much as a difference of 100 mm in flipper length, which is enormous. As in PCA (Section 4.5), we therefore first standardise each measurement to mean zero and standard deviation one. Section 7.5.1 shows what happens without it. Here are the dendrograms of the four linkages, with the species of each penguin in a bar below the tree:
dendro_segments <- function(hc) {
n <- length(hc$order); pos <- match(seq_len(n), hc$order); mid <- numeric(n - 1)
x_of <- function(m) if (m < 0) pos[-m] else mid[m]
h_of <- function(m) if (m < 0) 0 else hc$height[m]
out <- vector("list", n - 1)
for (i in seq_len(n - 1)) {
a <- hc$merge[i, 1]; b <- hc$merge[i, 2]
mid[i] <- (x_of(a) + x_of(b)) / 2
out[[i]] <- tibble(step = i, x = c(x_of(a), x_of(b), x_of(a)), xend = c(x_of(a), x_of(b), x_of(b)),
y = c(h_of(a), h_of(b), hc$height[i]), yend = rep(hc$height[i], 3))
}
bind_rows(out)
}
fig_dendros <- function(methods = names(hc4), ncol = 2, base = 13) {
# the height of a merge: the distance between the two clusters it joins, as each linkage measures it
ylab <- list(single = "distance of the closest pair", complete = "distance of the farthest pair",
average = "average distance of all pairs", Ward = quote(sqrt(2 %*% "rise in" ~ italic(W))))
panels <- lapply(methods, function(m) {
hc <- hc4[[m]]; n <- length(hc$order); top <- max(hc$height)
sizes <- sort(table(cutree(hc, 3)), decreasing = TRUE)
h3 <- mean(rev(hc$height)[2:3]) # a cut between the merges that leave three and two clusters
runs <- rle(as.character(peng$species[hc$order])) # one bar for each run of the same species
strip <- tibble(species = runs$values, xmax = cumsum(runs$lengths) + 0.5, xmin = xmax - runs$lengths)
ggplot() +
geom_segment(data = dendro_segments(hc), aes(x, y, xend = xend, yend = yend), linewidth = 0.25, colour = "grey25") +
geom_rect(data = strip, aes(xmin = xmin, xmax = xmax, ymin = -0.115 * top, ymax = -0.025 * top, fill = species)) +
geom_hline(yintercept = h3, linetype = 2, colour = col_a2, linewidth = 0.6) +
scale_fill_manual(values = pal_species, name = NULL) +
scale_x_continuous(expand = c(0.01, 0)) +
labs(title = paste(m, "linkage"), subtitle = paste("sizes of the three clusters:", paste(sizes, collapse = ", ")),
x = NULL, y = ylab[[m]]) +
theme_minimal(base_size = base) +
theme(axis.text.x = element_blank(), panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank(),
plot.title = element_text(face = "bold"))
})
wrap_plots(panels, ncol = ncol, guides = "collect") & theme(legend.position = "bottom")
}
# draw the figure
fig_dendros()
The height of a merge is the distance between the two clusters it joins, as its linkage measures it: the
distance of the closest pair for single linkage, of the farthest pair for complete linkage, and the average over all
pairs for average linkage. Since the measurements are standardised, a distance of 1 is as large as a difference of one
standard deviation in a single measurement. For Ward’s method, hclust() draws each merge at the height
\(\sqrt{2\times\text{rise in }W}\), so a merge sits higher the more it raises \(W\). The last merge of Ward’s tree, which
joins the Gentoo with the other penguins, raises \(W\) from 551 to 1,328.
Each tree is cut at three clusters (dashed line). Complete linkage, average linkage and Ward’s method find the three species, up to a few penguins: 7, 7 and 11 of the 333 are in a cluster that is mostly another species. Single linkage does not find them. Its three clusters are the Gentoo, a single Chinstrap penguin, and all the other Adelie and Chinstrap penguins together. Single linkage merges two clusters as soon as one pair of their members is close, so a chain of close neighbours can link observations that are far apart, and the Adelie and Chinstrap clouds touch. The other linkages look at all members and keep the clusters compact. Everitt and Hothorn (Section 6.3) find the same with the chest, waist and hip measurements of ten men and ten women: single linkage chains, while complete and average linkage separate the men from the women.
In R, hclust() builds the tree from the distances, and cutree() cuts it:
hc <- hclust(dist(meas4_z), method = "average") # meas4_z: the four measurements, standardised
table(cluster = cutree(hc, k = 3), species = peng$species)
## species
## cluster Adelie Chinstrap Gentoo
## 1 144 5 0
## 2 2 63 0
## 3 0 0 119Check your understanding
- Single linkage measures the distance between two clusters by
- the distance between their means
- the closest pair, one member from each cluster
- the farthest pair
- the average over all pairs
- A dendrogram is cut between its second-highest and its highest merge. This gives
- one cluster
- two clusters
- three clusters
- as many clusters as observations
- Single linkage can chain because
- it uses squared distances
- one close pair is enough to merge two clusters, so a chain of close neighbours links distant observations
- it standardises the data
- it merges the largest clusters first
Answers
1 b. 2 b. 3 b.7.3 k-means
7.3.1 Centres and the within-cluster sum of squares
k-means fixes the number of clusters \(k\) in advance and describes each cluster by its centre, the mean of its members (Everitt and Hothorn, Section 6.4). Write \(\hat g_t\) for the cluster of observation \(t\); the hat marks it as an estimate of the latent group \(g_t\). k-means looks for the clusters with the smallest within-cluster sum of squares of Section 7.2.2, which, summed observation by observation, is
\[ W=\sum_{t=1}^n\sum_{i=1}^p\big(x_{ti}-\bar x_{\hat g_ti}\big)^2=\sum_{t=1}^n\big\lVert\mathbf x_t-\bar{\mathbf x}_{\hat g_t}\big\rVert^2 . \]
\(W\) is small when every observation is close to the centre of its cluster. There are far too many ways to split 333 penguins into three clusters to try them all, so k-means searches step by step. Lloyd’s algorithm starts from \(k\) centres, for example \(k\) observations picked at random, and repeats two steps:
- Assign: put each observation in the cluster of its nearest centre.
- Update: move each centre to the mean of the observations in its cluster.
It stops when no observation changes its cluster.
7.3.2 Lloyd’s algorithm at work
Here are the bill length and depth of all 333 penguins, in millimetres, with three Adelie penguins as the starting centres. The shading shows which centre is nearest to each point of the plane. Move the slider to step through the rounds:
slim_frames <- function(w) {
w$x$frames <- lapply(w$x$frames, function(f) {
f$data <- lapply(f$data, function(d) {
if (identical(d$type, "heatmap")) d[c("type", "z")]
else if (!is.null(d$marker$size) && d$marker$size == 6) { d$x <- NULL; d$y <- NULL; d } else d
})
f
})
w
}
W_of <- function(X, C, cl) sum((X - C[cl, ])^2)
f0 <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
nearest <- function(X, C) max.col(-sapply(seq_len(nrow(C)), function(l) colSums((t(X) - C[l, ])^2)), ties.method = "first")
fig_kmeans_anim <- function() {
gx <- seq(31.125, 60.875, by = 0.25); gy <- seq(13.0625, 21.9375, by = 0.125)
grid <- expand_grid(y = gy, x = gx)
steps <- seq_along(lloyd_path) - 1
shade <- purrr::map_dfr(steps, function(s) {
C <- lloyd_path[[s + 1]]$C; tibble(x = grid$x, y = grid$y, z = nearest(as.matrix(grid[, c("x", "y")]), C), s = s)
})
pts <- purrr::map_dfr(steps, function(s) {
o <- lloyd_path[[s + 1]]
tibble(x = bills[, 1], y = bills[, 2], col = if (is.null(o$cl)) "#555555" else unname(pal_cl[o$cl]), s = s)
})
ctr <- purrr::map_dfr(steps, function(s) {
C <- lloyd_path[[s + 1]]$C; tibble(x = C[, 1], y = C[, 2], col = unname(pal_cl[1:3]), s = s)
})
round_no <- cumsum(vapply(lloyd_path, function(o) o$what == "assign", logical(1)))
info <- purrr::map_dfr(steps, function(s) {
o <- lloyd_path[[s + 1]]
txt <- switch(o$what,
start = "Start: three penguins serve as centres.",
assign = sprintf("Round %d, assign: each penguin joins its nearest centre. W = %s mm²", round_no[s + 1],
f0(W_of(bills, o$C, o$cl))),
update = sprintf("Round %d, update: each centre moves to the mean of its penguins. W = %s mm²", round_no[s + 1],
f0(W_of(bills, o$C, o$cl))),
done = sprintf("No penguin changes its centre: done. W = %s mm²", f0(W_of(bills, o$C, o$cl))))
tibble(x = 31.6, y = 21.5, txt = txt, s = s)
})
cs <- list(c(0, pal_cl[[1]]), c(1/3, pal_cl[[1]]), c(1/3, pal_cl[[2]]), c(2/3, pal_cl[[2]]), c(2/3, pal_cl[[3]]),
c(1, pal_cl[[3]]))
jump <- function(lab, s) list(label = lab, method = "animate",
args = list(list(as.character(s)), list(mode = "immediate",
frame = list(duration = 0, redraw = TRUE), transition = list(duration = 0))))
plot_ly() |>
add_trace(data = shade, x = ~x, y = ~y, z = ~z, frame = ~s, type = "heatmap", colorscale = cs, zmin = 1, zmax = 3,
opacity = 0.17, showscale = FALSE, hoverinfo = "skip") |>
add_trace(data = pts, x = ~x, y = ~y, frame = ~s, type = "scatter", mode = "markers",
marker = list(color = ~col, size = 6, opacity = 0.85), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = ctr, x = ~x, y = ~y, frame = ~s, type = "scatter", mode = "markers",
marker = list(color = ~col, size = 17, symbol = "x", line = list(color = "black", width = 1.5)),
hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = info, x = ~x, y = ~y, frame = ~s, text = ~txt, type = "scatter", mode = "text",
textposition = "middle right", textfont = list(size = 13, color = "#2c3e50"),
hoverinfo = "skip", showlegend = FALSE) |>
layout(xaxis = list(title = lab_len, range = c(31, 61), zeroline = FALSE),
yaxis = list(title = lab_dep, range = c(13, 22), zeroline = FALSE),
margin = list(t = 50)) |>
animation_opts(frame = 900, transition = 0, redraw = TRUE) |>
animation_slider(currentvalue = list(prefix = "step ")) |>
animation_button(label = "Play") |>
finalize_animation(list(jump("start", 0), jump("end", max(steps))), start_frame = "0", prefix = "step ") |>
slim_frames()
}
# draw the figure
fig_kmeans_anim()In the first round, the centre at the top takes the penguins with deep bills and the middle one those with shallow bills, so both move far to the right. Round by round, the three centres spread out along bill length, and after 10 rounds no penguin changes its cluster.
\(W\) never rises. In the assignment step, an observation moves only to a nearer centre, which lowers its squared
distance. In the update step, the mean is the point with the smallest sum of squared distances to the observations of
a cluster. Since \(W\) never rises and there are only finitely many ways to form the clusters, the algorithm stops. It
can stop at a local minimum, though: from another start, it may end in other clusters with a larger \(W\). R’s
kmeans() therefore takes the argument nstart, the number of random starts, and keeps the best result. (By default
it also uses a refinement of Lloyd’s steps, the Hartigan–Wong algorithm.) For the bill measurements, every one of
1,000 random starts ends in the same three clusters.
7.3.3 Round clusters
Do the three clusters match the species? The upper panel shows the species, the lower panel the clusters of k-means. Each cluster is drawn in the colour of one species, matched one to one so that as many penguins as possible are in the cluster of their own species. Both panels use one scale on both axes: a millimetre of bill length is as long as a millimetre of bill depth, so a round cloud looks round.
nearest <- function(X, C) max.col(-sapply(seq_len(nrow(C)), function(l) colSums((t(X) - C[l, ])^2)), ties.method = "first")
ell_df <- function(mu, S, level = 0.8) {
e <- ellipse_xy(sym_root(S), sqrt(qchisq(level, 2)))
tibble(x = mu[1] + e[1, ], y = mu[2] + e[2, ])
}
bill_panel <- function(what = c("species", "kmeans", "mixture"), base = 14, subtitle = NULL) {
what <- match.arg(what)
sub_or <- function(default) if (is.null(subtitle)) default else subtitle
pts <- tibble(x = bills[, 1], y = bills[, 2], species = peng$species)
p <- ggplot() + bill_lims + labs(x = lab_len, y = lab_dep) + theme_minimal(base_size = base) +
theme(plot.title = element_text(face = "bold"))
if (what == "species") {
ell <- purrr::map_dfr(levels(peng$species), function(s) {
X <- bills[peng$species == s, ]; ell_df(colMeans(X), cov(X)) |> mutate(species = s) })
p + geom_point(data = pts, aes(x, y, colour = species), size = 1.4, alpha = 0.75) +
geom_path(data = ell, aes(x, y, colour = species), linewidth = 1) +
scale_colour_manual(values = pal_species, name = NULL) +
theme(legend.position = "top", legend.justification = "right", legend.direction = "horizontal",
legend.margin = margin(0, 0, 0, 0), legend.box.spacing = unit(2, "pt")) +
labs(title = "Species", subtitle = sub_or("ellipses: 80% of each species"))
} else if (what == "kmeans") {
grid <- expand_grid(x = seq(31.1, 60.9, by = 0.2), y = seq(13.05, 21.95, by = 0.1))
grid$cl <- factor(nearest(as.matrix(grid), km_bills$centers))
pts$cl <- factor(km_bills$cluster); off <- km_bills$cluster != as.integer(peng$species)
# Round groups of one size, with the variance within the clusters: drawn, like the ellipses, to hold 80%
circ <- purrr::map_dfr(1:3, function(l) ell_df(km_bills$centers[l, ], diag(2) * km_s2) |> mutate(cl = factor(l)))
p + geom_raster(data = grid, aes(x, y, fill = cl), alpha = 0.16) +
geom_point(data = pts, aes(x, y, colour = cl), size = 1.4, alpha = 0.8) +
geom_point(data = pts[off, ], aes(x, y), shape = 21, size = 2.6, stroke = 0.7, colour = "black") +
geom_path(data = circ, aes(x, y, colour = cl), linewidth = 1, linetype = "22") +
annotate("point", x = km_bills$centers[, 1], y = km_bills$centers[, 2], shape = 4, size = 5, stroke = 2) +
scale_fill_manual(values = pal_cl, guide = "none") + scale_colour_manual(values = pal_cl, guide = "none") +
labs(title = "k-means: three clusters",
subtitle = sub_or(sprintf("circles: round groups of one size, 80%% of each\nringed: %d penguins not in their species' cluster",
sum(off))))
} else {
ell <- purrr::map_dfr(1:3, function(l) ell_df(mix2$parameters$mean[, l], mix2$parameters$variance$sigma[, , l]) |>
mutate(cl = factor(mix2_p[l])))
pts$cl <- factor(mix2_cl)
p + geom_point(data = pts, aes(x, y, colour = cl), size = 1.4, alpha = 0.8) +
geom_path(data = ell, aes(x, y, colour = cl), linewidth = 1) +
geom_point(data = pts[mix2_uncertain, ], aes(x, y), shape = 21, size = 2.6, stroke = 0.7, colour = "black") +
scale_colour_manual(values = pal_cl, guide = "none") +
labs(title = "Mixture: three groups",
subtitle = sub_or(sprintf("ringed: %d penguins with P(most likely group) < 0.8", sum(mix2_uncertain))))
}
}
fig_bills <- function(panels = c("species", "kmeans"), base = 14, ncol = 1) { # one column: the panels share the x-axis
ps <- lapply(panels, bill_panel, base = base)
if (ncol == 1 && length(ps) > 1) for (i in seq_len(length(ps) - 1)) ps[[i]] <- ps[[i]] + labs(x = NULL)
wrap_plots(ps, ncol = ncol)
}
# draw the figure
fig_bills(c("species", "kmeans"))
The clusters are three slices of bill length, not the species. They match the species for 75% of the penguins: the 84 ringed penguins sit in a cluster that is mostly another species. Two features of k-means explain the slices. Each penguin goes to its nearest centre, so the borders between clusters are straight lines halfway between neighbouring centres. And \(W\) counts a millimetre of bill length the same as a millimetre of bill depth, so k-means favours round clusters of similar spread. The dashed circles show such clusters: round, and all of one size. Like the ellipses in the upper panel, each holds 80% of a normal group, here one with the same variance in every direction, \(W/(2n)\), the average variance within the clusters.
The species are not round in millimetres. Within each species, bill length varies 2.2 to 3.2 times as much as bill depth, and the two are correlated, so each species is a long, flat ellipse, tilted a little. Chinstrap and Gentoo lie one above the other, a few millimetres apart in bill depth, while each spreads widely along bill length. Round clusters cannot follow these ellipses: cutting across bill length lowers \(W\) more than cutting between the two species.
Standardising the two measurements makes the ellipses rounder, and k-means then matches the species for 92% of the penguins. Model-based clustering (Section 7.4) goes further: it lets each cluster be an ellipse of its own. Everitt and Hothorn (Section 6.4) name the same two weaknesses of k-means: it depends on the units, and it imposes a round, “spherical” shape on the clusters.
7.3.4 How many clusters?
k-means needs \(k\) in advance. More clusters always give a smaller \(W\), so the smallest \(W\) cannot choose \(k\): with one cluster per observation, \(W\) is zero. Instead, plot \(W\) against \(k\) and look for an elbow, the point after which more clusters lower \(W\) only a little, as for the scree plot of Chapter 4 (Section 4.6). Everitt and Hothorn (Section 6.4) choose the number of clusters with the same plot:
f0 <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
fig_wss <- function(W = km_W, unit = "mm²", base = 14) {
d <- tibble(k = seq_along(W), W = W)
ggplot(d, aes(k, W)) + geom_line(colour = "grey50") + geom_point(size = 2.6, colour = col_a1) +
scale_x_continuous(breaks = d$k) + scale_y_continuous(labels = function(x) f0(x), limits = c(0, NA)) +
labs(x = "number of clusters k", y = paste0("W (", unit, ")")) + theme_minimal(base_size = base)
}
# draw the figure
fig_wss()
The sharpest bend is at two clusters, the Adelie against the rest, and the step from two to three clusters still lowers \(W\) by a third. The plot suggests a number but does not decide it. The model of the next section turns the choice of \(k\) into a comparison of likelihoods.
In R:
set.seed(1)
km <- kmeans(bills, centers = 3, nstart = 25) # bills: bill length and depth (mm) of the 333 penguins
km$centers # the three centres
## bill_length_mm bill_depth_mm
## 1 50.90353 17.33647
## 2 45.50982 15.68304
## 3 38.42426 18.27794
km$tot.withinss # W
## [1] 2265.067
table(cluster = km$cluster, species = peng$species)
## species
## cluster Adelie Chinstrap Gentoo
## 1 0 40 45
## 2 11 27 74
## 3 135 1 0Check your understanding
- In each step of Lloyd’s algorithm, the within-cluster sum of squares \(W\)
- can rise or fall
- never rises
- halves
- stays the same
- In millimetres, k-means cuts the penguins into slices of bill length because
- bill length is measured more precisely
- it counts a millimetre of length like a millimetre of depth, and within each species bill length varies much more
- the Gentoo penguins have the longest bills
- k-means ignores bill depth
- Plotted against the number of clusters \(k\), \(W\)
- is smallest at the true number of groups
- always falls as \(k\) grows, so we look for an elbow
- rises with \(k\)
- is the same for every \(k\)
Answers
1 b. 2 b. 3 b.7.4 Model-based clustering
7.4.1 A mixture of two normal densities
The cluster model of Section 7.1 becomes a statistical model once each group gets a distribution. Model-based clustering takes each group to be normal (Everitt and Hothorn, Section 6.5). Start with one variable, the flipper length, and two species, the Adelie and the Gentoo. The Chinstrap are left out for now: their flippers are about as long as those of the Adelie, so with this one variable the two species would form a single hill. In group \(l\), the flipper length has the normal density
\[ f_l(x)=\frac{1}{\sqrt{2\pi}\,\sigma_l}\exp\!\Big(-\frac{(x-\mu_l)^2}{2\sigma_l^2}\Big), \]
with mean \(\mu_l\) and variance \(\sigma_l^2\) (Section 3.4). A penguin drawn at random belongs to group \(l\) with probability \(\pi_l\), and its flipper length then has the density \(f_l\). So the flipper length of a random penguin has the mixture density
\[ f(x)=\pi_1f_1(x)+\pi_2f_2(x) : \]
each group adds its own hill, weighted by its share. Here is the mixture fitted to the flipper lengths of the 265 Adelie and Gentoo penguins (the next sections show how):
f0 <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
post2 <- function(x, par = mix1_par) dens_l(x, 2, par) / (dens_l(x, 1, par) + dens_l(x, 2, par))
dens_l <- function(x, l, par = mix1_par) par$pi[l] * dnorm(x, par$mu[l], par$sd[l])
fig_mixture_1d <- function(base = 14) {
xs <- seq(165, 240, by = 0.25)
curves <- bind_rows(tibble(x = xs, y = dens_l(xs, 1), g = "1"), tibble(x = xs, y = dens_l(xs, 2), g = "2"))
tot <- tibble(x = xs, y = dens_l(xs, 1) + dens_l(xs, 2))
top <- ggplot() +
geom_histogram(data = peng_ag, aes(flipper_length_mm, after_stat(density)), binwidth = 2, boundary = 0,
fill = "grey88", colour = "white") +
geom_area(data = curves, aes(x, y, fill = g), position = "identity", alpha = 0.25) +
geom_line(data = curves, aes(x, y, colour = g), linewidth = 1) +
geom_line(data = tot, aes(x, y), linewidth = 0.9, colour = "black") +
annotate("text", x = mix1_par$mu[1] - 6, y = 1.06 * max(dens_l(xs, 1)), label = "π[1]*f[1](x)", parse = TRUE,
colour = pal_cl[1], size = 4.8, hjust = 1) +
annotate("text", x = mix1_par$mu[2] + 6, y = 1.06 * max(dens_l(xs, 2)), label = "π[2]*f[2](x)", parse = TRUE,
colour = pal_cl[3], size = 4.8, hjust = 0) +
annotate("text", x = 232, y = 0.6 * max(tot$y), label = "f(x)", parse = TRUE, size = 4.8) +
annotate("segment", x = 229, xend = 222, y = 0.6 * max(tot$y), yend = 0.4 * max(tot$y), linewidth = 0.4) +
scale_fill_manual(values = c("1" = unname(pal_cl[1]), "2" = unname(pal_cl[3])), guide = "none") +
scale_colour_manual(values = c("1" = unname(pal_cl[1]), "2" = unname(pal_cl[3])), guide = "none") +
coord_cartesian(xlim = c(168, 237)) +
labs(x = NULL, y = "density") + theme_minimal(base_size = base)
bottom <- ggplot() +
geom_hline(yintercept = c(0, 1), colour = "grey85") +
geom_line(data = tibble(x = xs, y = post2(xs)), aes(x, y), colour = pal_cl[3], linewidth = 1.1) +
geom_rug(data = peng_ag, aes(x = flipper_length_mm, colour = species), alpha = 0.5, length = unit(0.07, "npc")) +
annotate("segment", x = x_half, xend = x_half, y = 0, yend = 0.5, linetype = 2, colour = "grey40") +
annotate("text", x = x_half + 1, y = 0.42, label = paste0("equally likely at ", f0(x_half), " mm"), hjust = 0,
size = 3.9, colour = "grey30") +
scale_colour_manual(values = pal_species, name = NULL) +
scale_y_continuous(breaks = c(0, 0.5, 1)) +
coord_cartesian(xlim = c(168, 237)) +
labs(x = "flipper length (mm)", y = "P(group 2 | x)") +
theme_minimal(base_size = base) + theme(legend.position = "bottom")
top / bottom + plot_layout(heights = c(2, 1.15))
}
# draw the figure
fig_mixture_1d()
Group 1 has a mean of 190 mm and a share of 53%, group 2 a mean of 217 mm and a share of 47%. The black curve, the sum of the two weighted hills, follows the histogram. The marks at the bottom show the species of each penguin: group 1 is the Adelie, and group 2 the Gentoo.
7.4.2 Membership probabilities
To which group does a penguin with flipper length \(x_t\) belong? Look at all penguins with a flipper length near \(x_t\). A share \(\pi_l\) of all penguins belongs to group \(l\), and among those, the density \(f_l(x_t)\) sets how many have a flipper length near \(x_t\). So the penguins near \(x_t\) from group \(l\) are in proportion to \(\pi_lf_l(x_t)\), the height of the group’s weighted curve at \(x_t\). The penguins near \(x_t\) from all groups together are in proportion to \(f(x_t)\), the height of the black curve. The share from group \(l\) is the ratio of the two, the membership probability
\[ P(g_t=l\mid x_t)=\frac{\pi_lf_l(x_t)}{f(x_t)} . \]
This calculation is called Bayes’ rule: the probability of a group, given the observation, is the share of the group times the density of the observation in the group, divided by the density of the observation over all groups.
The lower panel of the figure shows \(P(g_t=2\mid x_t)\). It is close to zero for short flippers and close to one for long flippers, and it is one half at 203 mm, where the two weighted curves cross. Each penguin is assigned to its most likely group, and the probability tells how sure that assignment is: a penguin with a flipper length of 203 mm could belong to either group. Assigned this way, 98% of the penguins land in the group of their own species.
7.4.3 The EM algorithm
The shares, means and variances are estimated by maximum likelihood, as the factor model was in Chapter 6 (Section 6.5): they are chosen to make the log-likelihood
\[ \ln L=\sum_{t=1}^n\ln f(x_t) \]
as large as possible. There is no formula for the maximum. The EM algorithm climbs to it in rounds of two steps, much like Lloyd’s algorithm:
- E-step (expectation): with the current parameters, compute the membership probabilities \(P(g_t=l\mid x_t)\) of every observation.
- M-step (maximisation): update the parameters, counting each observation in each group with its membership probability as a weight:
\[ \pi_l=\frac1n\sum_{t=1}^nP(g_t=l\mid x_t),\qquad \mu_l=\frac{\sum_tP(g_t=l\mid x_t)\,x_t}{\sum_tP(g_t=l\mid x_t)},\qquad \sigma_l^2=\frac{\sum_tP(g_t=l\mid x_t)\,(x_t-\mu_l)^2}{\sum_tP(g_t=l\mid x_t)} . \]
If the membership probabilities were all zeros and ones, these would be the share, the mean and the variance of the observations in each group, as in the update step of k-means. EM is k-means with soft assignments. Each round raises \(\ln L\) or leaves it unchanged (Dempster, Laird and Rubin 1977). Here EM starts from two wide groups in the middle:
loglik_of <- function(par) sum(log(dens_l(flip, 1, par) + dens_l(flip, 2, par)))
f0 <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
mns <- function(s) sub("^-", "\u2212", s)
post2 <- function(x, par = mix1_par) dens_l(x, 2, par) / (dens_l(x, 1, par) + dens_l(x, 2, par))
dens_l <- function(x, l, par = mix1_par) par$pi[l] * dnorm(x, par$mu[l], par$sd[l])
fig_em_anim <- function(show = c(0:12, 14, 16, 18, 20, 25, 30, 40)) {
xs <- seq(165, 240, by = 0.5)
h <- hist(flip, breaks = seq(170, 236, by = 2), plot = FALSE)
bars <- tibble(x = h$mids, y = h$density)
curves <- purrr::map_dfr(show, function(r) { par <- em_path[[r + 1]]
tibble(x = xs, g1 = dens_l(xs, 1, par), g2 = dens_l(xs, 2, par), p2 = post2(xs, par), s = r) |>
mutate(tot = g1 + g2) })
info <- purrr::map_dfr(show, function(r) tibble(x = 167, y = 0.0505, s = r,
txt = paste0(if (r == 0) "Start: two wide groups in the middle." else paste0("Round ", r, "."),
" ln L = ", mns(f0(loglik_of(em_path[[r + 1]]))))))
jump <- function(lab, s) list(label = lab, method = "animate",
args = list(list(as.character(s)), list(mode = "immediate",
frame = list(duration = 0, redraw = TRUE), transition = list(duration = 0))))
top <- plot_ly() |>
add_bars(data = bars, x = ~x, y = ~y, width = 2, marker = list(color = "#e3e3e3"), hoverinfo = "skip",
showlegend = FALSE) |>
add_trace(data = curves, x = ~x, y = ~tot, frame = ~s, type = "scatter", mode = "lines",
line = list(color = "black", width = 2), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = curves, x = ~x, y = ~g1, frame = ~s, type = "scatter", mode = "lines",
line = list(color = pal_cl[[1]], width = 2.5), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = curves, x = ~x, y = ~g2, frame = ~s, type = "scatter", mode = "lines",
line = list(color = pal_cl[[3]], width = 2.5), hoverinfo = "skip", showlegend = FALSE) |>
add_trace(data = info, x = ~x, y = ~y, frame = ~s, text = ~txt, type = "scatter", mode = "text",
textposition = "middle right", textfont = list(size = 13, color = "#2c3e50"), hoverinfo = "skip",
showlegend = FALSE)
bottom <- plot_ly() |>
add_trace(data = curves, x = ~x, y = ~p2, frame = ~s, type = "scatter", mode = "lines",
line = list(color = pal_cl[[3]], width = 2.5), hoverinfo = "skip", showlegend = FALSE)
key <- sprintf(paste0("<span style='color:%s'><b>π<sub>1</sub>f<sub>1</sub>(x)</b></span> ",
"<span style='color:%s'><b>π<sub>2</sub>f<sub>2</sub>(x)</b></span> <b>f(x)</b>"),
pal_cl[[1]], pal_cl[[3]])
subplot(top, bottom, nrows = 2, heights = c(0.66, 0.34), shareX = TRUE, margin = 0.04, titleY = TRUE) |>
layout(xaxis = list(title = "flipper length (mm)", range = c(166, 238), zeroline = FALSE),
yaxis = list(title = "density", range = c(0, 0.053), zeroline = FALSE),
yaxis2 = list(title = "P(group 2 | x)", range = c(-0.05, 1.05), zeroline = FALSE, tickvals = c(0, 0.5, 1)),
annotations = list(list(text = key, x = 1, xref = "paper", xanchor = "right", y = 1.02, yref = "paper",
yanchor = "bottom", showarrow = FALSE, font = list(size = 13))),
showlegend = FALSE, margin = list(t = 60)) |>
animation_opts(frame = 700, transition = 0, redraw = TRUE) |>
animation_slider(currentvalue = list(prefix = "round ")) |>
animation_button(label = "Play") |>
finalize_animation(list(jump("start", 0), jump("round 40", 40)), start_frame = "0", prefix = "round ")
}
# draw the figure
fig_em_anim()In the first rounds the two groups overlap almost completely. Then they pull apart, and after 16 rounds
they sit on the two hills of the histogram, both means within 1 mm of where they end, while \(\ln L\) rises from −1,105 to −1,043. Like Lloyd’s
algorithm, EM can stop at a local maximum, so the start matters. R’s mclust package starts EM from a
hierarchical clustering.
7.4.4 Three ellipses
With \(p\) variables, group \(l\) has the multivariate normal density \(f_l(x)\) of Section 3.4, with mean vector \(\mu_l\) and covariance matrix \(\Sigma_l\), and the mixture density is
\[ f(x)=\pi_1f_1(x)+\dots+\pi_kf_k(x)=\sum_{l=1}^k\pi_lf_l(x) . \]
The membership probabilities, the likelihood and the EM algorithm work as before, with mean vectors and covariance matrices in place of means and variances. The contours of each group’s density are ellipses (Section 3.4), and \(\Sigma_l\) sets their size, shape and tilt. For the bill length and depth of all three species, again with one scale on both axes:
nearest <- function(X, C) max.col(-sapply(seq_len(nrow(C)), function(l) colSums((t(X) - C[l, ])^2)), ties.method = "first")
ell_df <- function(mu, S, level = 0.8) {
e <- ellipse_xy(sym_root(S), sqrt(qchisq(level, 2)))
tibble(x = mu[1] + e[1, ], y = mu[2] + e[2, ])
}
bill_panel <- function(what = c("species", "kmeans", "mixture"), base = 14, subtitle = NULL) {
what <- match.arg(what)
sub_or <- function(default) if (is.null(subtitle)) default else subtitle
pts <- tibble(x = bills[, 1], y = bills[, 2], species = peng$species)
p <- ggplot() + bill_lims + labs(x = lab_len, y = lab_dep) + theme_minimal(base_size = base) +
theme(plot.title = element_text(face = "bold"))
if (what == "species") {
ell <- purrr::map_dfr(levels(peng$species), function(s) {
X <- bills[peng$species == s, ]; ell_df(colMeans(X), cov(X)) |> mutate(species = s) })
p + geom_point(data = pts, aes(x, y, colour = species), size = 1.4, alpha = 0.75) +
geom_path(data = ell, aes(x, y, colour = species), linewidth = 1) +
scale_colour_manual(values = pal_species, name = NULL) +
theme(legend.position = "top", legend.justification = "right", legend.direction = "horizontal",
legend.margin = margin(0, 0, 0, 0), legend.box.spacing = unit(2, "pt")) +
labs(title = "Species", subtitle = sub_or("ellipses: 80% of each species"))
} else if (what == "kmeans") {
grid <- expand_grid(x = seq(31.1, 60.9, by = 0.2), y = seq(13.05, 21.95, by = 0.1))
grid$cl <- factor(nearest(as.matrix(grid), km_bills$centers))
pts$cl <- factor(km_bills$cluster); off <- km_bills$cluster != as.integer(peng$species)
# Round groups of one size, with the variance within the clusters: drawn, like the ellipses, to hold 80%
circ <- purrr::map_dfr(1:3, function(l) ell_df(km_bills$centers[l, ], diag(2) * km_s2) |> mutate(cl = factor(l)))
p + geom_raster(data = grid, aes(x, y, fill = cl), alpha = 0.16) +
geom_point(data = pts, aes(x, y, colour = cl), size = 1.4, alpha = 0.8) +
geom_point(data = pts[off, ], aes(x, y), shape = 21, size = 2.6, stroke = 0.7, colour = "black") +
geom_path(data = circ, aes(x, y, colour = cl), linewidth = 1, linetype = "22") +
annotate("point", x = km_bills$centers[, 1], y = km_bills$centers[, 2], shape = 4, size = 5, stroke = 2) +
scale_fill_manual(values = pal_cl, guide = "none") + scale_colour_manual(values = pal_cl, guide = "none") +
labs(title = "k-means: three clusters",
subtitle = sub_or(sprintf("circles: round groups of one size, 80%% of each\nringed: %d penguins not in their species' cluster",
sum(off))))
} else {
ell <- purrr::map_dfr(1:3, function(l) ell_df(mix2$parameters$mean[, l], mix2$parameters$variance$sigma[, , l]) |>
mutate(cl = factor(mix2_p[l])))
pts$cl <- factor(mix2_cl)
p + geom_point(data = pts, aes(x, y, colour = cl), size = 1.4, alpha = 0.8) +
geom_path(data = ell, aes(x, y, colour = cl), linewidth = 1) +
geom_point(data = pts[mix2_uncertain, ], aes(x, y), shape = 21, size = 2.6, stroke = 0.7, colour = "black") +
scale_colour_manual(values = pal_cl, guide = "none") +
labs(title = "Mixture: three groups",
subtitle = sub_or(sprintf("ringed: %d penguins with P(most likely group) < 0.8", sum(mix2_uncertain))))
}
}
fig_bills <- function(panels = c("species", "kmeans"), base = 14, ncol = 1) { # one column: the panels share the x-axis
ps <- lapply(panels, bill_panel, base = base)
if (ncol == 1 && length(ps) > 1) for (i in seq_len(length(ps) - 1)) ps[[i]] <- ps[[i]] + labs(x = NULL)
wrap_plots(ps, ncol = ncol)
}
# draw the figure
fig_bills("mixture")
The three fitted ellipses are tilted like those of the species in Section 7.3, and the groups match the species for 97% of the penguins, against 75% for k-means. The ringed penguins are the 13 whose most likely group has a probability below 0.8. They lie where two ellipses meet, and the model says that their group is uncertain.
In R, the function Mclust() of the mclust package fits the mixture:
mc <- Mclust(bills) # library(mclust); bills: bill length and depth (mm)
summary(mc)
## ----------------------------------------------------
## Gaussian finite mixture model fitted by EM algorithm
## ----------------------------------------------------
##
## Mclust EVE (ellipsoidal, equal volume and orientation) model with 3 components:
##
## log-likelihood n df BIC ICL
## -1597.358 333 13 -3270.223 -3290.239
##
## Clustering table:
## 1 2 3
## 148 65 1207.4.5 Choosing the shape and the number of groups
A covariance matrix for every group has many parameters: each \(\Sigma_l\) has \(p(p+1)/2\) of them. mclust
therefore also fits simpler shapes. To describe them, write each covariance matrix as in PCA (Section 4.4):
\[ \Sigma_l=\Gamma_l\Delta_l^2\Gamma_l' , \]
where the columns of \(\Gamma_l\) point along the axes of the ellipse of group \(l\), and \(\Delta_l=\operatorname{diag}(\delta_{l1},\dots,\delta_{lp})\) holds the standard deviations along these axes. With two variables, \(\Gamma_l\) turns the axes by an angle \(\theta_l\), and three features describe the ellipse:
- its volume, the size: the area of the ellipse is proportional to \(\delta_{l1}\delta_{l2}\);
- its shape, how stretched it is: \(\delta_{l1}/\delta_{l2}\), the long axis over the short one;
- its orientation, the tilt \(\theta_l\).
Each model of mclust has a code of three letters, and each letter is one of three:
- E (equal): the feature is the same for all groups.
- V (variable): the feature varies from group to group.
- I (identity): the feature is the same for all groups and equal to one, or, for a matrix, to the identity
matrix \(I\):
- for the shape, \(\delta_{l1}/\delta_{l2}=1\): each ellipse is a circle, and \(\Sigma_l=\delta_{l1}^2I\);
- for the orientation, \(\Gamma_l=I\): no tilt, so the axes of each ellipse lie along the variables, and \(\Sigma_l=\Delta_l^2\) is diagonal.
The position of a letter tells which feature it describes. In the code EVE, for example,
- the first letter, E, is the volume: all groups have the same size;
- the second letter, V, is the shape: each group is stretched in its own way;
- the third letter, E, is the orientation: all groups have the same tilt.
The first letter is always E or V: an I describes a shape or an orientation, not a size. Here are all fourteen shapes, for three groups:
fig_mclust_shapes <- function(base = 12, notes = c(EII = "k-means", EVE = "the bills", VEE = "four measurements")) {
centres <- rbind(c(-1.75, -1.05), c(1.75, -1.05), c(0, 1.4))
size <- list(E = c(1, 1, 1), V = c(0.45, 0.95, 1.6)) # area of each group's ellipse, relative
shape <- list(I = c(1, 1, 1), E = c(2.6, 2.6, 2.6), V = c(1.3, 2.6, 4.2)) # long axis over short axis
tilt <- list(I = c(0, 0, 0), E = c(35, 35, 35), V = c(35, -40, 95)) # degrees
cols <- c(II = "round", EI = "along the axes,\nsame shape", VI = "along the axes,\nown shape",
EE = "same shape,\nsame tilt", VE = "own shape,\nsame tilt", EV = "same shape,\nown tilt",
VV = "own shape,\nown tilt")
rows <- c(E = "same size", V = "own size")
codes <- expand_grid(v = names(rows), so = names(cols)) |> mutate(code = paste0(v, so))
ell <- purrr::map_dfr(seq_len(nrow(codes)), function(r) {
v <- codes$v[r]; s <- substr(codes$so[r], 1, 1); o <- substr(codes$so[r], 2, 2)
purrr::map_dfr(1:3, function(l) {
area <- 0.38 * size[[v]][l]; ratio <- shape[[s]][l]
M <- rotation_matrix(tilt[[o]][l] * pi / 180) %*% diag(c(sqrt(area * ratio), sqrt(area / ratio)))
e <- ellipse_xy(M)
tibble(x = centres[l, 1] + e[1, ], y = centres[l, 2] + e[2, ], g = factor(l))
}) |> mutate(v = codes$v[r], so = codes$so[r])
}) |> mutate(row = factor(rows[v], levels = rows), col = factor(cols[so], levels = cols))
lab <- codes |> mutate(row = factor(rows[v], levels = rows), col = factor(cols[so], levels = cols),
note = ifelse(code %in% names(notes), notes[code], NA))
ggplot() +
geom_polygon(data = ell, aes(x, y, group = g, fill = g), alpha = 0.25) +
geom_path(data = ell, aes(x, y, group = g, colour = g), linewidth = 0.8) +
geom_text(data = lab, aes(x = -3.15, y = 3.05, label = code), hjust = 0, vjust = 1, fontface = "bold",
size = base / 3) +
geom_label(data = filter(lab, !is.na(note)), aes(x = 0, y = -3.05, label = note), vjust = 0,
size = base / 3.7, label.size = 0, fill = "#fff3c4", label.padding = unit(0.12, "lines")) +
facet_grid(row ~ col, switch = "y") +
scale_fill_manual(values = pal_cl, guide = "none") + scale_colour_manual(values = pal_cl, guide = "none") +
coord_equal(xlim = c(-3.2, 3.2), ylim = c(-3.1, 3.1), expand = FALSE) +
theme_minimal(base_size = base) +
theme(axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank(),
panel.background = element_rect(fill = "#fafafa", colour = "#dddddd"),
strip.text.x = element_text(size = base * 0.85, lineheight = 0.95),
strip.text.y.left = element_text(size = base * 0.95, face = "bold", angle = 90),
strip.placement = "outside", panel.spacing = unit(4, "pt"))
}
# draw the figure
fig_mclust_shapes()
The first letter gives the row, the other two give the column. Round groups (left column) have no tilt, so their code
ends in II. mclust calls the three families of shapes spherical (round), diagonal (along the axes) and
ellipsoidal (any tilt), after their shapes with three variables: a sphere is a round ball, and an ellipsoid a
stretched and turned one. The yellow labels mark the shape behind k-means (Section 7.4.6) and
the shapes that BIC picks in this chapter, for the bills and for all four measurements (Section 7.5.1).
Everitt and Hothorn (Section 6.5 and Table 6.4) write the same split of \(\Sigma_l\) with other letters.
A more flexible shape, or more groups, means more parameters, and a model with more parameters always fits at least as well: its largest likelihood is never lower. The likelihood alone would therefore always pick the most flexible model, VVV with as many groups as we allow, and overfit: it would describe chance features of this sample as groups. To choose between models, we need a criterion that charges for each extra parameter. The Bayesian information criterion (BIC) does this:
\[ \text{BIC}=2\ln\hat L-(\text{number of parameters})\times\ln n , \]
where \(\ln\hat L\) is the largest log-likelihood that the model reaches. mclust fits every shape with
\(k=1,2,\dots\) groups and picks the model with the largest BIC. (Many books define BIC with the opposite sign, and
then the smallest value wins.) BIC can also pick a single group, a sign that the data hold no clusters at all.
f0 <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
mns <- function(s) sub("^-", "\u2212", s)
fig_bic <- function(base = 14) {
b <- as.data.frame(unclass(mix2_bic)[, , drop = FALSE]); b$k <- seq_len(nrow(b))
lab <- c(EII = "EII: round, all of the same size", EEE = "EEE: one ellipse for all groups",
EVE = "EVE: same size and orientation", VVV = "VVV: each group its own ellipse")
d <- pivot_longer(b, -k, names_to = "model", values_to = "BIC") |> mutate(model = factor(lab[model], levels = lab))
best <- slice_max(d, BIC)
ggplot(d, aes(k, BIC, colour = model)) + geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
geom_point(data = best, size = 5, shape = 21, stroke = 1.3, colour = "black") +
annotate("text", x = best$k, y = best$BIC + 25, label = "largest BIC", size = 4, vjust = 0) +
scale_colour_manual(values = c("#999999", col_a1, col_a2, "#2ca02c"), name = NULL) +
scale_x_continuous(breaks = 1:6) + scale_y_continuous(labels = function(x) mns(f0(x))) +
labs(x = "number of groups k", y = "BIC") +
theme_minimal(base_size = base) + theme(legend.position = "right")
}
# draw the figure
fig_bic()
BIC picks three groups with ellipses of the same size and tilt (EVE). Five groups with one ellipse for all (EEE) come close, a reminder that BIC weighs the evidence but does not settle it. Round groups (EII, grey) fit far worse for every \(k\): to cover long, tilted ellipses with round ones, they need many groups, and their BIC still rises at six.
7.4.6 k-means is a mixture with round groups
Suppose that all groups are round, with the same variance \(\sigma^2\) in every direction (\(\Sigma_l=\sigma^2I\)), and
have equal shares. In the letters of mclust, this is the shape EII: the same volume for all groups (E), a round
shape (I) and no tilt (I), here with equal shares as well. Then the weighted density of group \(l\) is
\[ \pi_lf_l(\mathbf x_t)=\frac1k\,(2\pi\sigma^2)^{-p/2}\exp\!\Big(-\frac{\lVert\mathbf x_t-\mu_l\rVert^2}{2\sigma^2}\Big), \]
and only the distance \(\lVert\mathbf x_t-\mu_l\rVert\) differs between groups. So the most likely group is the one with the nearest mean, as in k-means. As \(\sigma^2\) shrinks, the membership probabilities become zeros and ones, and EM turns into Lloyd’s algorithm. k-means is model-based clustering with round groups of equal size, the shape EII, and the BIC figure shows how poorly that shape describes the penguins in millimetres.
7.4.7 Labels, and estimates for each observation
Swapping the numbers of two groups, together with their shares, means and covariance matrices, leaves the mixture density and the likelihood unchanged. The labels of the groups are not identified, just as the turn of the factors was not (Section 6.6), and as there, we name the groups after what they contain. The membership probabilities play the part of the factor scores (Section 6.7). They are estimates for each observation, computed from its measurements and the estimated parameters, and they are never certain: a penguin between two hills keeps an uncertain group, however many penguins are measured.
Check your understanding
- The membership probability \(P(g_t=l\mid x_t)\) is
- the share \(\pi_l\) of group \(l\)
- the weighted density of group \(l\) at \(x_t\), divided by the mixture density \(f(x_t)\)
- the distance from \(x_t\) to \(\mu_l\)
- one for the group of observation \(t\) and zero for the others
- The EM algorithm differs from Lloyd’s algorithm in that
- it needs no starting values
- each observation counts in every group, weighted by its membership probability
- it always finds the global maximum
- it uses medians instead of means
mclustpicks the model with- the largest log-likelihood
- the largest BIC, which charges \(\ln n\) for each parameter
- the most groups
- round groups
- k-means corresponds to a mixture whose groups are
- ellipses of any shape
- round, of equal size and with equal shares
- the species
- tilted like the data
Answers
1 b. 2 b. 3 b. 4 b.7.5 All four measurements
7.5.1 Units matter for some methods
Back to all four measurements: bill length, bill depth and flipper length in millimetres, and body mass in grams. Their standard deviations are 5.5 mm, 2.0 mm, 14 mm and 805 g. In the Euclidean distance, body mass dominates: a typical difference in body mass adds 805 to the distance, a typical difference in flipper length only 14. The tables show how the clusters of k-means and of the mixture with three groups match the species. For the mixture, BIC picks the shape VEE, in both units. Since k-means is the mixture EII (Section 7.4.6), the tables compare two shapes, EII and VEE:
agree <- function(cl, ref) mean(match_labels(cl, ref) == as.integer(factor(ref)))
pct <- function(x, d = 0) paste0(formatC(100 * x, format = "f", digits = d), "%")
perms <- function(v) if (length(v) <= 1) list(v) else
do.call(c, lapply(seq_along(v), function(i) lapply(perms(v[-i]), function(p) c(v[i], p))))
match_labels <- function(cl, ref) {
ref <- as.integer(factor(ref)); k <- max(c(cl, ref))
tab <- table(factor(cl, 1:k), factor(ref, 1:k))
all_p <- perms(1:k)
p <- all_p[[which.max(sapply(all_p, function(p) sum(tab[cbind(1:k, p)])))]]
p[cl] # cluster l becomes number p[l]
}
cross_tab <- function(cl, ref) table(cluster = match_labels(cl, ref), group = ref)
fig_units <- function(base = 13) {
tabs <- setNames(list(km4_raw, km4_z, mix4_3$classification), # k-means is the mixture EII
c("k-means (EII), grams and mm", "k-means (EII), standardised",
paste0("mixture ", mix4_3$modelName, ", either units")))
panels <- lapply(names(tabs), function(nm) {
tab <- as.data.frame(cross_tab(tabs[[nm]], peng$species))
ggplot(tab, aes(group, factor(cluster, levels = 3:1), fill = Freq)) + geom_tile(colour = "white") +
geom_text(aes(label = Freq, colour = Freq > 70), size = 4.6) +
scale_fill_gradient(low = "#f7fbff", high = "#08306b", limits = c(0, 150), guide = "none") +
scale_colour_manual(values = c("FALSE" = "black", "TRUE" = "white"), guide = "none") +
labs(title = nm, subtitle = paste(pct(agree(tabs[[nm]], peng$species)), "in their species' cluster"),
x = NULL, y = "cluster") +
theme_minimal(base_size = base) + theme(panel.grid = element_blank(), plot.title = element_text(face = "bold"))
})
wrap_plots(panels, nrow = 1)
}
# draw the figure
fig_units()
On the measurements as they are, k-means sorts the penguins mainly by body mass, and its clusters match the species for only 58% of them. After standardising, they match for 92%. The mixture VEE matches for 98%, and it finds exactly the same groups for the measurements as they are and for the standardised ones.
The reason is the same as for factor analysis (Section 6.5.4). Record body mass in kilograms instead of grams, and a mixture for the old units has a twin for the new ones that fits equally well: the same mixture with the body-mass entries of the means divided by 1,000, and those of the covariance matrices rescaled to match. The twin has the same membership probabilities, because the mixture measures how far observation \(t\) lies from group \(l\) by the Mahalanobis distance \((\mathbf x_t-\mu_l)'\Sigma_l^{-1}(\mathbf x_t-\mu_l)\) of Chapter 2 (Section 2.6.2), which does not depend on the units.
The twin must also have the shape of the model, and here EII and VEE differ. VEE gives all groups the same ellipse up to its size: \(\Sigma_l=c_l\Sigma\), with a number \(c_l\) for each group. The rescaling stretches all the ellipses in the same way, so they are still the same up to their size. The twin is again VEE, and the best fit in kilograms is the best fit in grams, rescaled, with the same groups. EII gives all groups the same circle. A circle in grams and millimetres is a flat disc in kilograms and millimetres, which EII does not allow. The twin is not EII, so EII settles for other groups. That is why k-means depends on the units, as PCA does. VVV, with an ellipse of its own for each group, survives the rescaling too.
7.5.2 A fourth group
Left to choose the number of groups, BIC picks four, all of shape VEE:
mc4 <- Mclust(meas4_z) # meas4_z: the four measurements, standardised
summary(mc4)
## ----------------------------------------------------
## Gaussian finite mixture model fitted by EM algorithm
## ----------------------------------------------------
##
## Mclust VEE (ellipsoidal, equal shape and orientation) model with 4 components:
##
## log-likelihood n df BIC ICL
## -1126.211 333 32 -2438.283 -2477.667
##
## Clustering table:
## 1 2 3 4
## 149 65 61 58
table(group = mc4$classification, peng_group4) # peng_group4: the species, with the Gentoo split by sex
## peng_group4
## group Adelie Chinstrap Gentoo female Gentoo male
## 1 145 4 0 0
## 2 1 64 0 0
## 3 0 0 53 8
## 4 0 0 5 53The model has split the Gentoo penguins in two, and the split follows their sex: one group holds 53 females and 8 males, the other 53 males and 5 females. Gentoo males are larger. On average they weigh 5,485 g against 4,680 g for the females, and their bills are 49.5 mm long against 45.6 mm. The plane of the first two principal components of the standardised measurements (Chapter 4) shows the four groups, with the ellipses of their normal densities as seen in this plane:
pct <- function(x, d = 0) paste0(formatC(100 * x, format = "f", digits = d), "%")
ell_df <- function(mu, S, level = 0.8) {
e <- ellipse_xy(sym_root(S), sqrt(qchisq(level, 2)))
tibble(x = mu[1] + e[1, ], y = mu[2] + e[2, ])
}
fig_peng_four <- function(base = 14) {
pal4 <- setNames(unname(pal_cl), levels(peng_group4))
pts <- tibble(x = peng_pc$scores[, 1], y = peng_pc$scores[, 2], g = factor(levels(peng_group4)[mix4_cl],
levels = levels(peng_group4)), sex = peng$sex)
p_of <- match(1:4, mix4_cl[match(1:4, mix4$classification)])
ell <- purrr::map_dfr(1:4, function(l) {
mu <- drop(t(peng_pc$G) %*% mix4$parameters$mean[, l])
S <- t(peng_pc$G) %*% mix4$parameters$variance$sigma[, , l] %*% peng_pc$G
ell_df(mu, S) |> mutate(g = factor(levels(peng_group4)[p_of[l]], levels = levels(peng_group4)))
})
ggplot() + axes0 +
geom_point(data = pts, aes(x, y, colour = g, shape = sex), size = 1.9, alpha = 0.8) +
geom_path(data = ell, aes(x, y, colour = g), linewidth = 1) +
scale_colour_manual(values = pal4, name = "group, named after\nmost of its penguins") +
scale_shape_manual(values = c(female = 16, male = 2), name = "sex") +
coord_equal() +
labs(x = sprintf("first principal component (%s)", pct(peng_pc$share[1])),
y = sprintf("second principal component (%s)", pct(peng_pc$share[2]))) +
theme_minimal(base_size = base)
}
# draw the figure
fig_peng_four()
The model was never told the sex of a penguin. As in factor analysis, the data find the groups and we name them, here after the species and the sex of most of their penguins. With other data, there may be no labels to compare with, and the names must come from the group means alone, as for the US states below. Plotting the clusters on the first two principal components is a common way to show them. Everitt and Hothorn do the same (Sections 6.3 and 6.4), and their Section 6.6 adds two other displays, neighbourhood graphs and stripes plots.
Check your understanding
- On the measurements in grams and millimetres, k-means sorts the penguins mainly by
- bill depth
- body mass, the measurement with by far the largest variance
- species
- flipper length
- The mixture finds the same groups whether body mass is in grams or kilograms, because
- it ignores body mass
- its Mahalanobis distances do not depend on the units, as long as the covariance matrices can adapt to them
- it standardises the data first
- it has fewer parameters than k-means
Answers
1 b. 2 b.7.6 The US states
The penguins form real hills. The six indicators of the 50 US states from Chapter 2 need not: income, illiteracy, life expectancy, the murder rate, the high-school graduation rate and the number of days with frost. Standardised, as for PCA with the correlation matrix (Section 4.5), and clustered by k-means into three clusters:
X <- scale(state.x77[, c("Income", "Illiteracy", "Life Exp", "Murder", "HS Grad", "Frost")])
set.seed(1)
km_st <- kmeans(X, centers = 3, nstart = 25)
split(state.abb, km_st$cluster)
## $`1`
## [1] "AK" "AZ" "CA" "DE" "FL" "HI" "IL" "IN" "MD" "MI" "MO" "NV" "NJ" "NY" "OH"
## [16] "OK" "OR" "PA" "VA" "WA"
##
## $`2`
## [1] "CO" "CT" "ID" "IA" "KS" "ME" "MA" "MN" "MT" "NE" "NH" "ND" "RI" "SD" "UT"
## [16] "VT" "WI" "WY"
##
## $`3`
## [1] "AL" "AR" "GA" "KY" "LA" "MS" "NM" "NC" "SC" "TN" "TX" "WV"
round(km_st$centers, 2)
## Income Illiteracy Life Exp Murder HS Grad Frost
## 1 0.67 -0.18 -0.07 0.23 0.31 -0.31
## 2 0.08 -0.74 0.80 -0.99 0.56 0.86
## 3 -1.23 1.42 -1.08 1.11 -1.36 -0.77The left panel shows the clusters on the map of the first two principal components from Chapter 4 (Section 4.2.5), and the right panel the means of each cluster, in standard deviations:
pct <- function(x, d = 0) paste0(formatC(100 * x, format = "f", digits = d), "%")
fig_states_clusters <- function(base = 13) {
d <- tibble(x = st_pc$x[, 1], y = st_pc$x[, 2], abb = rownames(X6), cl = km_states$cluster)
share <- st_pc$sdev^2 / sum(st_pc$sdev^2)
map <- ggplot(d, aes(x, y, colour = cl)) + axes0 +
geom_point(size = 2) +
geom_text_repel(aes(label = abb), size = 3.3, seed = 4, max.overlaps = 40, show.legend = FALSE) +
scale_colour_manual(values = pal_states, name = NULL) +
coord_equal() +
labs(title = "The 50 states, by cluster",
x = sprintf("PC1 score (%s of the variance)", pct(share[1])), y = sprintf("PC2 score (%s)", pct(share[2]))) +
theme_minimal(base_size = base) + theme(legend.position = "bottom", plot.title = element_text(face = "bold"))
ctr <- as_tibble(km_states$centers, rownames = "cl") |> pivot_longer(-cl, names_to = "var", values_to = "z") |>
mutate(cl = factor(cl, levels = c("South", "North", "Rest")), var = factor(var, levels = rev(vars6)))
prof <- ggplot(ctr, aes(z, var, colour = cl)) +
geom_vline(xintercept = 0, colour = "grey70") +
geom_point(size = 3.2) +
scale_colour_manual(values = pal_states, guide = "none") +
labs(title = "Cluster means", x = "standard deviations from the mean of all states", y = NULL) +
theme_minimal(base_size = base) + theme(plot.title = element_text(face = "bold"))
map + prof + plot_layout(widths = c(1.45, 1))
}
# draw the figure
fig_states_clusters()
The names come from the means. One cluster has low incomes, much illiteracy, short lives, a high murder rate, few graduates and little frost, and 11 of its 12 states lie in the South. Another has long lives, few murders, many graduates and much frost: these 18 states stretch across the North, from New England through the Midwest and the Plains to the Mountain West. The remaining 20 states, among them California, New York, Illinois and Florida, have the highest incomes and are close to the average otherwise.
Here no species tell us whether the clusters are real. One check is whether other methods find them too. Ward’s method gives the same three clusters, but it minimises the same \(W\) as k-means, so it is not an independent check. Average linkage and the mixture, with the number of groups chosen by BIC, give different answers:
name_states <- function(cl) {
nm <- sapply(split(rownames(Z6), cl), function(s) {
if (all(c("AK", "NV") %in% s) && length(s) == 2) return("Alaska and Nevada")
km <- table(km_states$cluster[rownames(Z6) %in% s])
if (km["South"] == length(s)) "South" else if (km["North"] == length(s)) "North" else
if ("CA" %in% s && length(s) < 10) "West" else "Rest"
})
factor(nm[as.character(cl)], levels = names(pal_states))
}
fig_states_methods <- function(base = 13) {
res <- list("k-means: three clusters" = km_states$cluster,
"Average linkage: three clusters" = name_states(avg_states),
"Mixture (BIC): five groups" = name_states(mix_states$classification))
d <- purrr::map_dfr(names(res), function(m) tibble(x = st_pc$x[, 1], y = st_pc$x[, 2], abb = rownames(X6),
cl = res[[m]], method = factor(m, levels = names(res))))
ggplot(d, aes(x, y, colour = cl)) + axes0 +
geom_point(size = 2) +
geom_text_repel(data = filter(d, abb %in% c("AK", "NV", "CA", "FL", "HI")), aes(label = abb), size = 3.2,
seed = 2, show.legend = FALSE) +
facet_wrap(~method) +
scale_colour_manual(values = pal_states, name = NULL, drop = TRUE) +
coord_equal() +
labs(x = "PC1 score", y = "PC2 score") +
theme_minimal(base_size = base) +
theme(legend.position = "bottom", strip.text = element_text(face = "bold", size = base))
}
# draw the figure
fig_states_methods()
Average linkage finds the same 12 states of the South, but it sets Alaska and Nevada apart as a cluster of two and keeps all other states together. The mixture finds five round groups (EII): the South and the North as in k-means, Alaska with Nevada, six states in the West and Florida (AZ, CA, FL, HI, OR, WA), and the remaining 12.
So the South is a group that every method finds, and so, apart from average linkage, is the North. How the other states are grouped depends on the method. Groups that do not depend on the method deserve more trust than groups that do, and a clustering method returns \(k\) clusters whether or not the data have them. The three clusters of k-means are a useful summary of the states, like their two factors in Chapter 6 (Section 6.8), rather than a discovery. Everitt and Hothorn (Section 6.4.1) reach a similar conclusion with k-means on the crime rates of the states: their two clusters split the states along the first principal component, and the analysis may only divide a homogeneous set of states in two.
Check your understanding
- Ward’s method gives the same three clusters of states as k-means. This is a weak check, because
- Ward’s method uses another distance
- both minimise the same within-cluster sum of squares \(W\)
- Ward’s method always gives three clusters
- k-means starts from the clusters of Ward’s method
- The same 12 states of the South form a cluster with every method. This suggests that
- the other clusters are just as trustworthy
- the South is a group in the data, not a product of one method
- there are exactly three groups of states
- the South has the most states
- Run with \(k=3\) on data without any groups, k-means
- reports an error
- still returns three clusters
- returns one cluster
- returns the principal components
Answers
1 b. 2 b. 3 b.7.7 Clusters and factors
Factor analysis and model-based clustering are both models with a latent variable, and they share more than their form:
| Factor analysis | Model-based clustering | |
|---|---|---|
| Latent variable | continuous factors \(\mathbf f_t\) | a discrete group \(g_t\) |
| Model | \(\mathbf x_t=\Lambda\mathbf f_t+\mathbf u_t\) | \(\mathbf x_t=\mu_{g_t}+\mathbf u_t\) |
| What it groups | variables that load on the same factor | observations that lie in the same hill |
| Not identified | the turn of the factors | the numbers of the groups |
| Estimates for each observation | factor scores, never exact | membership probabilities, never certain |
| How many? | the likelihood ratio test | BIC |
| A change of units | rescales the loadings, not the factors | rescales the means and covariance matrices, not the groups, if the shape can adapt |
PCA and k-means are the model-free relatives: PCA looks for the directions of largest variance, k-means for compact clusters, and both depend on the units of the variables.
7.8 Summary
- A cluster model has a discrete latent variable: observation \(t\) belongs to group \(g_t\), and \(\mathbf x_t=\mu_{g_t}+\mathbf u_t\). The centre jumps among \(k\) points, which can lie anywhere, while the centre of a factor model slides along a line or a plane. Cluster analysis estimates the groups from the observations alone.
- Hierarchical clustering merges the two closest clusters, step by step. The dendrogram records the merges, and cutting it gives clusters. The linkage defines the distance between clusters: the closest pair (single, which can chain), the farthest pair (complete), the average of all pairs, or the rise in the within-cluster sum of squares \(W\) (Ward).
- k-means minimises \(W\) for a given \(k\): assign each observation to the nearest centre, move each centre to the mean of its cluster, and repeat. It favours round clusters of similar spread, depends on the units, and can end in a local minimum, so it is run from many starts.
- Model-based clustering fits a mixture of normal densities, \(f(x)=\sum_l\pi_lf_l(x)\), by maximum likelihood with the EM algorithm. Each observation gets membership probabilities, and each group an ellipse. BIC chooses the number of groups and their shape. k-means is the special case of round groups of equal size.
- Standardise the variables before k-means or hierarchical clustering when their units differ. A mixture whose covariance matrices can adapt to the units does not need it.
- For the penguins, the clusters match the species, and BIC even split the Gentoo by sex. For the states, only the South is found by every method. A clustering method always returns groups, so groups that several methods find deserve more trust than groups that depend on the method.
Cluster analysis finds groups of observations that lie together. A model for the groups adds membership probabilities, shapes for the clusters and a way to choose their number.
7.8.1 Further reading
- Everitt and Hothorn (2011), An Introduction to Applied Multivariate Analysis with R, Chapter 6: hierarchical clustering (with body measurements and jet fighters), k-means (with the crime rates of the US states and Romano-British pottery), model-based clustering with finite mixtures (with a survey of European doctors on what they tell cancer patients), and displays of the clusters (neighbourhood graphs and stripes plots).
- Everitt, Landau, Leese and Stahl (2011), Cluster Analysis, a book-length treatment.
- Kaufman and Rousseeuw (1990), Finding Groups in Data: An Introduction to Cluster Analysis.
- Hastie, Tibshirani and Friedman (2009), The Elements of Statistical Learning, Section 14.3, on k-means, hierarchical clustering and mixtures.
- Ward (1963) on Ward’s method, MacQueen (1967) and Lloyd (1982) on k-means, and Dempster, Laird and Rubin (1977) on the EM algorithm.
- Fraley and Raftery (2002), “Model-based clustering, discriminant analysis, and density estimation”, and Scrucca, Fop, Murphy and Raftery (2016), “mclust 5”, on model-based clustering in R.
- Gorman, Williams and Fraser (2014), “Ecological sexual dimorphism and environmental variability within a community of Antarctic penguins (genus Pygoscelis)”, the study behind the penguin data.