Skip to main content

Problem Set 8 Key: Clustering

PLS 206 — Applied Multivariate Modeling

Author

Grey Monroe

Published

January 1, 2026

Tip

Try the problems yourself before consulting this key. Every number below is computed by the code on this page from data/winedata.csv (178 wines, 13 chemicals). Cluster numbers are arbitrary: if your cluster 1 is our cluster 3, the answer is the same. With nstart = 25 the k-means answers here do not depend on the seed; with nstart = 1 the unscaled fit in Q1 sometimes lands in a worse solution (see the note under Q1).

library(ggplot2)
library(cluster)
wine <- read.csv("https://greymonroe.github.io/PLS_206/data/winedata.csv")
chem <- wine[, -1]
X    <- scale(chem)

agreement <- function(a, b) {
  tab <- table(a, b)
  perms <- list(c(1, 2, 3), c(1, 3, 2), c(2, 1, 3),
                c(2, 3, 1), c(3, 1, 2), c(3, 2, 1))
  max(sapply(perms, function(p) sum(diag(tab[, p])))) / length(a)
}

# key-only helper: rename each cluster after the cultivar it is matched to,
# so tables read the same whatever numbers the algorithm happened to use
relabel <- function(cl, truth) {
  tab <- table(cl, truth)
  perms <- list(c(1, 2, 3), c(1, 3, 2), c(2, 1, 3),
                c(2, 3, 1), c(3, 1, 2), c(3, 2, 1))
  best <- perms[[which.max(sapply(perms, function(p) sum(diag(tab[, p]))))]]
  lab <- setNames(colnames(tab)[best], rownames(tab))
  factor(lab[as.character(cl)], levels = colnames(tab))
}
pct <- function(x) paste0(round(100 * x, 1), "%")

Part 1: k-means

set.seed(206)
km_raw <- kmeans(chem, centers = 3, nstart = 25)
set.seed(206)
km <- kmeans(X, centers = 3, nstart = 25)
a_raw <- agreement(km_raw$cluster, wine$Cultivar)
a_km  <- agreement(km$cluster, wine$Cultivar)
v <- sapply(chem, var)

Q1. Unscaled, k-means matches the cultivars for 70.2% of wines (125 of 178); scaled, 96.6% (172 of 178). k-means assigns each wine to the nearest centre by Euclidean distance, so a variable measured in big numbers dominates the distance. Proline has variance 99,167, against 204 for Mg and under 12 for everything else, so the unscaled clusters are essentially bins of proline. Scaling gives every chemical the same weight.

Rows are clusters (named after the cultivar each is matched to), columns are the true cultivars:

table(cluster = relabel(km_raw$cluster, wine$Cultivar), cultivar = wine$Cultivar)
             cultivar
cluster       barbera barolo gringnolino
  barbera          29     13          20
  barolo            0     46           1
  gringnolino      19      0          50
table(cluster = relabel(km$cluster, wine$Cultivar), cultivar = wine$Cultivar)
             cultivar
cluster       barbera barolo gringnolino
  barbera          48      0           3
  barolo            0     59           3
  gringnolino       0      0          65

Seed note. With a single random start the unscaled fit does not always find the same answer: across 20 seeds it lands in two different solutions. With nstart = 25 the best of 25 starts is kept and the answer is stable. The scaled fit finds the same solution from every start.

tw_raw <- sapply(1:20, function(s) { set.seed(s); kmeans(chem, 3, nstart = 1)$tot.withinss })
tw_sc  <- sapply(1:20, function(s) { set.seed(s); kmeans(X, 3, nstart = 1)$tot.withinss })
table(round(tw_raw))   # unscaled: two different local optima

2370690 2629315 
     13       7 
table(round(tw_sc, 1)) # scaled: one solution

1270.7 
    20 

Q2.

wss <- sapply(1:10, function(k) {
  set.seed(206)
  kmeans(X, centers = k, nstart = 25)$tot.withinss
})
d <- dist(X)
sil <- sapply(2:10, function(k) {
  set.seed(206)
  cl <- kmeans(X, centers = k, nstart = 25)$cluster
  mean(silhouette(cl, d)[, "sil_width"])
})
k_sil <- (2:10)[which.max(sil)]
round(wss)
 [1] 2301 1649 1271 1169 1095 1033  973  920  875  837
round(setNames(sil, 2:10), 3)
    2     3     4     5     6     7     8     9    10 
0.259 0.285 0.258 0.233 0.199 0.203 0.199 0.203 0.144 
par(mfrow = c(1, 2))
plot(1:10, wss, type = "b", pch = 19, xlab = "k", ylab = "Total within-cluster SS",
     main = "Elbow")
abline(v = 3, lty = 2, col = "grey50")
plot(2:10, sil, type = "b", pch = 19, xlab = "k", ylab = "Average silhouette width",
     main = "Silhouette")
abline(v = k_sil, lty = 2, col = "grey50")

Both point to k = 3. The sum of squares drops by 652 from k = 1 to 2 and by 379 from 2 to 3, then by only 102 from 3 to 4: the elbow is at 3. The average silhouette peaks at k = 3 (0.285). Both methods recover the true number of cultivars without being told. (An answer of “elbow at 3, though it is not sharp” is fine; the silhouette is the cleaner signal here.)

Q3.

pca <- prcomp(chem, scale. = TRUE)
scores <- data.frame(pca$x[, 1:2],
                     Cluster  = relabel(km$cluster, wine$Cultivar),
                     Cultivar = wine$Cultivar)
scores$Mismatch <- scores$Cluster != scores$Cultivar
pv <- round(100 * pca$sdev^2 / sum(pca$sdev^2))
ggplot(scores, aes(PC1, PC2, colour = Cluster, shape = Cultivar)) +
  geom_point(size = 2) +
  geom_point(data = subset(scores, Mismatch), shape = 1, size = 5,
             colour = "black") +
  coord_fixed() +
  labs(x = paste0("PC1 (", pv[1], "%)"), y = paste0("PC2 (", pv[2], "%)"),
       colour = "k-means cluster\n(matched cultivar)", shape = "True cultivar",
       title = "k-means (k = 3, scaled) on the PCA of the wines",
       subtitle = "Black rings: wines placed with the wrong cultivar") +
  theme_classic()

tab_km <- table(cluster = scores$Cluster, cultivar = scores$Cultivar)
tab_km
             cultivar
cluster       barbera barolo gringnolino
  barbera          48      0           3
  barolo            0     59           3
  gringnolino       0      0          65
n_wrong <- sum(scores$Mismatch)
wrong_from <- table(scores$Cultivar[scores$Mismatch])

k-means agrees with cultivar for 96.6% of wines: only 6 of 178 are placed with the wrong cultivar. All 6 are gringnolino wines: 3 went into the barolo cluster and 3 into the barbera cluster. Every barolo and every barbera wine was clustered correctly. On the PC plot none of the mismatches sits in the middle of the gringnolino cloud: three sit in the upper edge of the barolo cloud and three in the gap between gringnolino and barbera. Their chemistry looks more like the neighbouring cultivar’s than like their own, so any method that groups wines by chemical similarity will struggle with them. Matching works by reading the table row by row: each cluster has one big count, and that cultivar is its label; the cluster numbers k-means printed carry no meaning.

Q4.

ctr <- km$centers
lab <- relabel(km$cluster, wine$Cultivar)     # name each row after its matched cultivar
rownames(ctr) <- sapply(1:3, function(i) as.character(lab[km$cluster == i][1]))
round(ctr, 2)
            Alcohol AlcAsh   Ash Color  Flav   Hue MalicAcid    Mg
barolo         0.83  -0.61  0.36  0.17  0.98  0.47     -0.30  0.58
gringnolino   -0.92   0.17 -0.49 -0.90  0.02  0.46     -0.39 -0.49
barbera        0.16   0.52  0.19  0.94 -1.21 -1.16      0.87 -0.08
            NonFlavPhenols    OD Phenols  Proa Proline
barolo               -0.56  0.78    0.88  0.58    1.12
gringnolino          -0.03  0.27   -0.08  0.06   -0.75
barbera               0.72 -1.29   -0.98 -0.78   -0.41
top3 <- function(cv) {
  x <- round(ctr[cv, ], 2)
  x <- x[order(-abs(x))][1:3]
  paste0(names(x), " (", sprintf("%+.2f", x), ")", collapse = ", ")
}

The centres are in SD units relative to the average wine.

  • Barolo cluster: Proline (+1.12), Flav (+0.98), Phenols (+0.88), with Alcohol also high. High-proline, flavonoid- and phenol-rich, strong wines.
  • Barbera cluster: OD (-1.29), Flav (-1.21), Hue (-1.16), with Color and MalicAcid high. Deeply coloured wines that are low in flavonoids, with a low hue ratio and more malic acid.
  • Gringnolino cluster: Alcohol (-0.92), Color (-0.90), Proline (-0.75). Pale, lower-alcohol, low-proline wines.

These are the same chemicals that built PC1 (flavonoids and phenols against malic acid and non-flavonoid phenols: barolo against barbera) and PC2 (colour, alcohol and proline: gringnolino against the other two) in PS7.


Part 2: Hierarchical Clustering

Q5.

d <- dist(X)
h_complete <- hclust(d, method = "complete")
h_ward     <- hclust(d, method = "ward.D2")
h_single   <- hclust(d, method = "single")
cl <- list(complete = cutree(h_complete, k = 3),
           ward.D2  = cutree(h_ward, k = 3),
           single   = cutree(h_single, k = 3))
res <- data.frame(linkage   = names(cl),
                  sizes     = sapply(cl, function(x) paste(sort(table(x), decreasing = TRUE), collapse = ", ")),
                  agreement = sapply(cl, function(x) pct(agreement(x, wine$Cultivar))),
                  row.names = NULL)
res
   linkage      sizes agreement
1 complete 69, 58, 51     83.7%
2  ward.D2 64, 58, 56     92.7%
3   single  174, 3, 1     37.6%
Linkage Cluster sizes Agreement with cultivar
complete 69, 58, 51 83.7%
ward.D2 64, 58, 56 92.7%
single 174, 3, 1 37.6%

Single linkage fails. It merges two clusters when their closest pair of wines is close, so a single chain of intermediate wines is enough to glue whole cultivars together. Here the three cultivars touch at their edges (Q3), so single linkage chains 174 wines into one cluster and the other two “clusters” are a handful of outlying wines. Complete linkage (farthest pair) avoids chaining but mixes barolo and gringnolino; Ward’s method, which merges the pair of clusters that adds the least within-cluster sum of squares (the k-means criterion), does best.

table(cluster = relabel(cl$complete, wine$Cultivar), cultivar = wine$Cultivar)
             cultivar
cluster       barbera barolo gringnolino
  barbera          48      0           3
  barolo            0     51          18
  gringnolino       0      8          50
table(cluster = relabel(cl$ward.D2, wine$Cultivar), cultivar = wine$Cultivar)
             cultivar
cluster       barbera barolo gringnolino
  barbera          48      0           8
  barolo            0     59           5
  gringnolino       0      0          58

Q6.

plot(h_ward, labels = substr(wine$Cultivar, 1, 4), cex = 0.35,
     main = "Ward linkage, scaled wine chemistry", xlab = "", sub = "")
rect.hclust(h_ward, k = 3, border = c("tomato", "steelblue", "darkgreen"))

hts <- rev(h_ward$height)[1:5]
round(hts, 1)
[1] 35.3 27.6 12.5 12.2 11.7

Yes. The last two merges happen at heights 35.3 and 27.6, and the next ones drop to 12.5, 12.2, 11.7: three long branches, then a dense comb of short merges. A cut anywhere between about 13 and 27 (say 20) gives 3 clusters. Two clusters is also defensible from the tree (the top two merges are both tall), but four is not: the 4th and 5th groups would split at almost the same height as dozens of others. The leaf labels show each box is dominated by one cultivar (barb, baro, grin), and the misplaced wines are gringnolino leaves (“grin”) sitting in the barbera and barolo boxes.

Q7.

cl_ward <- cl$ward.D2
table(kmeans = relabel(km$cluster, wine$Cultivar),
      ward   = relabel(cl_ward, wine$Cultivar))
             ward
kmeans        barbera barolo gringnolino
  barbera          51      0           0
  barolo            0     61           1
  gringnolino       5      3          57
a_kw   <- agreement(km$cluster, cl_ward)
a_ward <- agreement(cl_ward, wine$Cultivar)

k-means and Ward agree on 94.9% of wines (169 of 178). k-means matches the cultivars better (96.6% against 92.7% for Ward). They disagree because hierarchical clustering is greedy: once two wines or groups are merged, that merge is never undone, so an early merge of a borderline gringnolino wine with barbera wines carries all the way to the top. k-means keeps reassigning every wine to its nearest centre until nothing moves. (Also acceptable: they optimise slightly different things; Ward minimises the increase in sum of squares one merge at a time, k-means minimises the total directly.)


Part 3: Clusters Without Answers

Q8.

set.seed(206)
noise <- matrix(rnorm(178 * 13), ncol = 13)
km_noise <- kmeans(noise, centers = 3, nstart = 25)
km_noise$size
[1] 62 47 69
sil_noise <- mean(silhouette(km_noise$cluster, dist(noise))[, "sil_width"])
sil_wine  <- sil[2:10 == 3]

k-means splits pure noise into three clusters of sizes 62, 47, 69: it always returns k groups, structure or not. The average silhouette is 0.07 for noise against 0.285 for the real wines at k = 3. The wine clusters are real but not dramatically separated (their clouds touch); the noise clusters are arbitrary cuts through one cloud. Lesson: the existence of clusters says nothing by itself. Check a quality measure against a structureless baseline before naming groups.

Q9. Any well-reasoned answer earns full credit. A strong answer uses at least two of these:

  • Scale the traits (Q1), and think about which traits to include, since every included trait gets an equal vote in the distance.
  • Choose k with more than one method (elbow and silhouette, Q2) and report whether they agree; if they do not, say so.
  • Run more than one method (k-means and Ward, Q5 and Q7) and check that they find the same groups; avoid single linkage, which chains.
  • Compare the silhouette with that of structureless data of the same size (Q8), or check that clusters are stable when you resample landraces or change the seed.
  • Interpret the cluster centres (Q4): clusters worth naming should differ in a few traits in a way that makes biological sense, and ideally line up with something not used to build them (geography, pedigree, farmer-assigned variety names).