Skip to main content

Cluster analysis

Packages

library(ggplot2)   # Visualization
library(ggdendro)  # Dendrograms with ggplot
library(GGally)    # Scatter-plot matrices
library(tidyr)     # Reshape data
library(terra)     # Raster data
theme_set(theme_light())

Cluster analysis is an unsupervised method for finding groups (clusters) in data. The goal is for observations within a cluster to be as similar as possible and observations in different clusters to be as different as possible. Similarity is defined by a distance (dissimilarity) measure, so which measure we choose affects the result.

There are two main families of clustering algorithms:

  • Hierarchical algorithms build a nested sequence of clusters, either by repeatedly merging the closest observations or groups (agglomerative) or by repeatedly splitting them (divisive).
  • Partitional algorithms (e.g., k-means) split the data directly into a fixed number of \(k\) clusters, which you have to specify beforehand.

Hierarchical clustering

The result of a hierarchical clustering can be shown as a tree diagram called a dendrogram. It shows which observations or groups were merged at each step and at what distance (height) the merge happened. Cutting the tree at a given height gives a set of clusters.

We use the iris dataset as an example, dropping the Species column so that only the four numeric flower measurements are used for clustering:

data(iris)
iris_dat <- iris[,-5] # remove species column
head(iris_dat)
  Sepal.Length Sepal.Width Petal.Length Petal.Width
1          5.1         3.5          1.4         0.2
2          4.9         3.0          1.4         0.2
3          4.7         3.2          1.3         0.2
4          4.6         3.1          1.5         0.2
5          5.0         3.6          1.4         0.2
6          5.4         3.9          1.7         0.4

Dissimilarity measures

The first step is to compute the distance (dissimilarity) matrix. With dist() you can choose between euclidean, maximum, manhattan, canberra, binary or minkowski distance.

iris_dist <- dist(iris_dat, method = "euclidian")
class(iris_dist)
[1] "dist"
dim(as.matrix(iris_dist))
[1] 150 150
as.matrix(iris_dist)[1:5,1:8]
          1         2        3         4         5         6         7
1 0.0000000 0.5385165 0.509902 0.6480741 0.1414214 0.6164414 0.5196152
2 0.5385165 0.0000000 0.300000 0.3316625 0.6082763 1.0908712 0.5099020
3 0.5099020 0.3000000 0.000000 0.2449490 0.5099020 1.0862780 0.2645751
4 0.6480741 0.3316625 0.244949 0.0000000 0.6480741 1.1661904 0.3316625
5 0.1414214 0.6082763 0.509902 0.6480741 0.0000000 0.6164414 0.4582576
          8
1 0.1732051
2 0.4242641
3 0.4123106
4 0.5000000
5 0.2236068

Agglomeration methods

In the second step, we run an agglomeration cluster algorithm on the dissimilarity matrix. hclust() allows you to choose between several agglomeration methods: “ward.D”, “ward.D2”, “single”, “complete”, “average”, “mcquitty”, “median”, or “centroid”.

iris_ward <- hclust(iris_dist, method="ward.D")
iris_ward

Call:
hclust(d = iris_dist, method = "ward.D")

Cluster method   : ward.D 
Distance         : euclidean 
Number of objects: 150 

From R’s help: A number of different clustering methods are provided. Ward’s minimum variance method aims at finding compact, spherical clusters. The complete linkage method finds similar clusters. The single linkage method (which is closely related to the minimal spanning tree) adopts a ‘friends of friends’ clustering strategy. The other methods can be regarded as aiming for clusters with characteristics somewhere between the single and complete link methods.pl

Plot dendrogram

iris_dendr <- as.dendrogram(iris_ward)
plot(iris_dendr, horiz=F)

Visualize dendrogram with ggplot

dendro <- as.dendrogram(iris_ward)

dendro <- dendro_data(dendro, type = "rectangle")

ggplot(segment(dendro)) + 
  geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) + 
  geom_text(data = label(dendro), 
            aes(x = x, y = y - 2, label = label), size = 3)

Selection of clusters

cutree() cuts a tree, e.g., as resulting from hclust(), into several groups either by specifying the desired number(s) of groups (k) or the cut height(s) (h). Let’s split the tree into three groups.

iris_dat$cluster <- as.factor(cutree(iris_ward, k = 3))
head(iris_dat$cluster)
[1] 1 1 1 1 1 1
Levels: 1 2 3
table(iris_dat$cluster)

 1  2  3 
50 64 36 

Visualize clusters

Two visualize the four clusters, we create a scatter-plot matrix with pairs(), while using the vector of the cluster id’s to specify the symbol color.

pairs(iris_dat[,1:4], col=iris_dat$cluster, pch=19, cex=0.4)

Visualize clusters with ggpairs()

iris_dat$cluster <- as.factor(cutree(iris_ward, k = 3))
ggpairs(iris_dat, columns = 1:4, mapping = ggplot2::aes(color = cluster))

k-means cluster analysis

A k-means cluster analysis can be performed using the kmeans() function. Notice, that we also scale the data to unit variance and mean zero.

data(iris)

iris_kmeans <- kmeans(x = scale(iris[, c(1:4)]), centers = 3, algorithm="Lloyd", iter.max=20)
iris_kmeans
K-means clustering with 3 clusters of sizes 56, 44, 50

Cluster means:
  Sepal.Length Sepal.Width Petal.Length Petal.Width
1   -0.0113575  -0.8730834    0.3758167   0.3101145
2    1.1635361   0.1448178    0.9996766   1.0265628
3   -1.0111914   0.8504137   -1.3006301  -1.2507035

Clustering vector:
  [1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 [38] 3 3 3 3 3 3 3 3 3 3 3 3 3 2 2 2 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1 1 2 1 1 1
 [75] 1 2 2 2 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 2 2 2 2 1 2 1 2 2
[112] 1 2 1 1 2 2 2 2 1 2 1 2 1 2 2 1 1 2 2 2 2 2 1 1 2 2 2 1 2 2 2 1 2 2 2 1 2
[149] 2 1

Within cluster sum of squares by cluster:
[1] 48.40184 43.34674 47.35062
 (between_SS / total_SS =  76.7 %)

Available components:

[1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
[6] "betweenss"    "size"         "iter"         "ifault"      

We can plot the cluster solution using ggplot:

iris$cluster3 <- iris_kmeans$cluster

ggplot(iris, aes(Sepal.Length, y = Sepal.Width, col = factor(cluster3))) +
  geom_point()

And compare it to the actual species classification:

table(iris$cluster3, iris$Species)
   
    setosa versicolor virginica
  1      0         39        17
  2      0         11        33
  3     50          0         0

Previously, we selected \(k=3\), based on a-priori knowledge on the number of species. We found that species setosa was well separated from the other species but species versicolor and virginia showed strong overlapping characteristics. The question is, whether there are subgroups that might be better represented by additional clusters.

But how many clusters do we need?

iris$cluster2 <- kmeans(x = iris[, c(1:4)], centers = 2)$cluster
iris$cluster4 <- kmeans(x = iris[, c(1:4)], centers = 4)$cluster
iris$cluster5 <- kmeans(x = iris[, c(1:4)], centers = 5)$cluster
iris$cluster6 <- kmeans(x = iris[, c(1:4)], centers = 6)$cluster

iris |>
  pivot_longer(-(Sepal.Length:Species), names_to = "k", values_to = "cluster") |>
  ggplot(aes(Sepal.Length, y = Sepal.Width, col = factor(cluster))) +
  geom_point() +
  facet_wrap(~k, ncol = 6)

To answer the last question we run kmeans() for a range of \(k\) and calculate the within-group sum of squares for each \(k\) (here ranging from 1 to 10 clusters).

wss <- c()
var_explained <- c()

for(k in 1:10){
  set.seed(42)
  fit <- kmeans(scale(iris[, 1:4]), centers = k)
  wss <- c(wss, fit$tot.withinss)
  var_explained <- c(var_explained, fit$betweenss/fit$totss)
}

head(wss)
[1] 596.00000 220.87929 138.88836 113.64981 104.92773  95.48123
head(var_explained)
[1] 1.907497e-16 6.293972e-01 7.669658e-01 8.093124e-01 8.239468e-01
[6] 8.397966e-01

Now, when we plot \(k\) against the within-group sum of squares (\(SSE\)), you will see that the error decreases as \(k\) gets larger; this is because when the number of clusters increases, they should be smaller, so distortion is also smaller. The idea of the elbow method is to choose the k at which the \(SSE\) decreases abruptly. This produces an “elbow effect” in the graph.

ggplot(data.frame(k = 1:10, wss = wss), aes(x = k, y = wss)) +
  geom_line() +
  scale_x_continuous(breaks = 1:10)
ggplot(data.frame(k = 1:10, wss = wss), aes(x = k, y = wss)) +
  geom_line() +
  scale_x_continuous(breaks = 1:10)

set.seed(42)
fit3 <- kmeans(scale(iris[, 1:4]), centers = 3)
table(iris$Species, factor(fit3$cluster))
            
              1  2  3
  setosa     50  0  0
  versicolor  0 39 11
  virginica   0 14 36
set.seed(42)
fit4 <- kmeans(scale(iris[, 1:4]), centers = 4)
table(iris$Species, factor(fit4$cluster))
            
              1  2  3  4
  setosa     49  1  0  0
  versicolor  0 19 29  2
  virginica   0  2 21 27

k-means on raster data

The terra package provides the function k_means(), which runs k-means clustering directly on a SpatRaster. Each layer is treated as a variable and each cell as an observation. Cells with missing values (NA) are skipped and remain NA in the output, so we do not need to convert the raster to a data.frame and back.

Let’s load the bioclim data we used in another lab.

clim <- rast("data/chelsa_bio_1981-2010_V.2.1_europe.tif")
names(clim) <- c("Tmean", "Tdiurnal", "Isotherm", "Tseason", "Tmax_warmM",
                 "Tmin_coldM", "Trange", "Tmean_wetQ", "Tmean_dryQ",
                 "Tmean_warmQ", "Tmean_coldQ", "Pann", "P_wetM", "P_dryM",
                 "Pseason", "P_wetQ", "P_dryQ", "P_warmQ", "P_coldQ")

As with the iris data, the variables have very different units and ranges, so we first standardize each layer using scale(), which also works on SpatRasters.

clim_scaled <- scale(clim)

Now we run k-means with five clusters. Because the initial cluster centers are chosen randomly, we set the random seed to get reproducible results. The argument nstart is passed on to kmeans() and repeats the clustering with several random starts, keeping the best solution, i.e. the one with the lowest total within-cluster sum of squares (the most compact clusters).

set.seed(42)
kmean_raster <- k_means(clim_scaled, centers = 5, nstart = 5)
names(kmean_raster) <- "cluster"
kmean_raster
class       : SpatRaster
size        : 306, 347, 1  (nrow, ncol, nlyr)
resolution  : 15000, 15000  (x, y)
extent      : 2325000, 7530000, 1170000, 5760000  (xmin, xmax, ymin, ymax)
coord. ref. : ETRS89-extended / LAEA Europe (EPSG:3035)
source(s)   : memory
name        : cluster
min value   :       1
max value   :       5
plot(kmean_raster)

Note, for large rasters (more than maxcell cells, by default one million), k_means() estimates the cluster centers from a regular sample of cells and then assigns every cell to its nearest center.

NoteChoosing the number of clusters

k_means() only returns the cluster raster, not the within-group sum of squares. To apply the elbow method, draw a random sample of cells, e.g. with spatSample(clim_scaled, size = 10000, na.rm = TRUE), and run kmeans() on the sample for a range of \(k\), as in the previous section.