cat /en/k-means-clustering/
MDN-119:35

Clustering with the K-means Algorithm

· Artificial Intelligence · 6 min read
Immagine che contiene grafico Descrizione generata automaticamente

An excerpt from the book Data Science e Machine Learning: dai dati alla conoscenza

K-means is a partitional clustering algorithm in which each cluster is associated with a centroid and each point is assigned to the cluster with the nearest centroid. To run this algorithm we have to specify the parameter k, which indicates the number of clusters to be formed. The algorithm works through the following steps:

  • k random points are selected as the initial centroids.
  • We form the k clusters by assigning every point to its nearest centroid.
  • We recompute the centroid of each cluster.
    • If the centroid has changed, we repeat the assignment of all the points to the nearest centroid.
    • If the centroid has not changed, we have found the cluster.

Distances can be computed with any of the measures we have already seen in the previous chapters. The algorithm typically converges within the first few iterations, but stopping criteria can be specified based on the number of iterations, on a minimum value of the total error, or until the members of each cluster stabilise (that is, they no longer move from one cluster to another).

The algorithm is sensitive to local minima, since the choice of random starting points may lead to different results across different runs. One solution is to run the algorithm several times with different starting points until we obtain a solution that minimises the error; alternatively, other algorithms (such as hierarchical clustering) can be used to determine the starting points. K-means is also strongly affected by outliers, which tend to “pull” the cluster centroid and increase the total error. The solution in this case is to identify and remove outliers during data preparation.

Table 1 – K-Means

Advantages Disadvantages
  • Simple to interpret and explain
  • Flexible and easy to tune
  • Efficient, and produces good clustering
  • Not as sophisticated as more recent clustering algorithms
  • Not guaranteed to find the optimal number of clusters
  • Requires an assumption about the number of clusters

To give an example of K-means clustering in R we will use the USArrests dataset, which contains 50 observations with the number of arrests per 100,000 residents for assault, murder and rape in each of the 50 US states in 1973.

> library(tidyverse)
> library(cluster) # algoritmi di clustering
> library(factoextra) # algoritmi di clustering & visualization

> mydata <- USArrests
> head(mydata)

           Murder  Assault UrbanPop Rape
Alabama      13.2      236       58 21.2
Alaska       10.0      263       48 44.5
Arizona       8.1      294       80 31.0
Arkansas      8.8      190       50 19.5
California    9.0      276       91 40.6
Colorado      7.9      204       78 38.7

We remove the rows with missing values and scale the variables:

> mydata <- na.omit(mydata)
> mydata <- scale(mydata)
> head(mydata)

                Murder   Assault   UrbanPop         Rape
Alabama     1.24256408 0.7828393 -0.5209066 -0.003416473
Alaska      0.50786248 1.1068225 -1.2117642  2.484202941
Arizona     0.07163341 1.4788032  0.9989801  1.042878388
Arkansas    0.23234938 0.2308680 -1.0735927 -0.184916602
California  0.27826823 1.2628144  1.7589234  2.067820292
Colorado    0.02571456 0.3988593  0.8608085  1.864967207

Now we use the get_dist() function to compute a distance matrix (the default distance is Euclidean, but many others can be used) and the fviz_dist() function to visualise it:

> # get_dist: calcola la matrice delle distanze
> # fviz_dist: visualizza la matrice

> distance <- get_dist(mydata)
> fviz_dist(distance, gradient = list(low = "#00AFBB", 
  mid = "white", high = "#FC4E07"))

Image containing a chart. Automatically generated description

Figure 1 – The distance matrix

In R the K-means algorithm is implemented by the function kmeans(). We will pass the function the number of centres (two) and a parameter that tries several initial configurations and selects the best one (25 configurations is a common choice):

> k2 <- kmeans(mydata, centers = 2, nstart = 25)
> str(k2)

List of 9
$ cluster : Named int [1:50] 1 1 1 2 1 1 2 2 1 1 ...
..- attr(*, "names")= chr [1:50] "Alabama" "Alaska" "Arizona" "Arkansas" ...
$ centers : num [1:2, 1:4] 1.005 -0.67 1.014 -0.676 0.198 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:2] "1" "2"
.. ..$ : chr [1:4] "Murder" "Assault" "UrbanPop" "Rape"
$ totss       : num 196
$ withinss    : num [1:2] 46.7 56.1
$ tot.withinss: num 103
$ betweenss   : num 93.1
$ size        : int [1:2] 20 30
$ iter        : int 1
$ ifault      : int 0
- attr(*, "class")= chr "kmeans"

Let us look at the model:

> # visualizzo i dettagli
> k2
K-means clustering with 2 clusters of sizes 20, 30

Cluster means:
Murder Assault UrbanPop Rape
1 1.004934 1.0138274 0.1975853 0.8469650
2 -0.669956 -0.6758849 -0.1317235 -0.5646433

Clustering vector:
     Alabama    Alaska     Arizona       Arkansas
           1         1           1              2
  California  Colorado Connecticut       Delaware
           1         1           2              2
     Florida   Georgia      Hawaii          Idaho
           1         1           2              2
…
South Dakota Tennessee       Texas           Utah
           2         1           1              2
     Vermont  Virginia  Washington  West Virginia
           2         2           2              2
   Wisconsin   Wyoming
           2         2

Within cluster sum of squares by cluster:

[1] 46.74796 56.11445
(between_SS / total_SS = 47.5 %)

Available components:

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

Cluster is a vector of integers (from 1 to k) indicating the cluster to which each point is allocated. Centers is a matrix of cluster centres, totss is the total sum of squared errors, while withinss is the vector of within-cluster sums of squares, one component per cluster. Tot.withinss is the total within-cluster sum of squares, while betweenss is the between-cluster sum of squares, i.e. totss – tot.withinss. Size is the number of points in each cluster. Now we use the very handy fviz_cluster() function, which performs a PCA on the variables and plots the clusters against the first two principal components:

> # grafico rispetto alle componenti principali
> fviz_cluster(k2, data = mydata)

Image containing a map. Automatically generated description

Figure 2 – Plot with k = 2

We now have to decide the optimal value of k, i.e. the ideal number of clusters. Let us first try to do it manually, using different values of k:

> # diversi valori di K
> k3 <- kmeans(mydata, centers = 3, nstart = 25)
> k4 <- kmeans(mydata, centers = 4, nstart = 25)
> k5 <- kmeans(mydata, centers = 5, nstart = 25)

> # creo diversi grafici per valori di k
> p1 <- fviz_cluster(k2, geom = "point", data = mydata) + ggtitle("k = 2")
> p2 <- fviz_cluster(k3, geom = "point", data = mydata) + ggtitle("k = 3")
> p3 <- fviz_cluster(k4, geom = "point", data = mydata) + ggtitle("k = 4")
> p4 <- fviz_cluster(k5, geom = "point", data = mydata) + ggtitle("k = 5")

> install.packages("gridExtra")
> library(gridExtra)
> grid.arrange(p1, p2, p3, p4, nrow = 2)

Figure 3 – K-means for different values of k

Let us now determine the optimal number of clusters using the various methods at our disposal. First of all, we try the Elbow method:

> # metodo Elbow
> set.seed(123)
> fviz_nbclust(mydata, kmeans, method = "wss")

Image containing a chart. Automatically generated description

Figure 4 – Optimal number of clusters with the Elbow method

Now let us try the silhouette method:

> # metodo silouhette
> fviz_nbclust(mydata, kmeans, method = "silhouette")

Image containing a chart. Automatically generated description

Figure 5 – Optimal number of clusters with the silhouette method

And finally with the gap statistic:

> # metodo gap statistics
> gap_stat <- clusGap(mydata, FUN = kmeans, nstart = 25, K.max = 10, B = 50)

Clustering k = 1,2,..., K.max (= 10): .. done
Bootstrapping, b = 1,2,..., B (= 50) [one "." per sample]:

.................................................. 50

> print(gap_stat, method = "firstmax")

Clustering Gap statistic ["clusGap"] from call:
clusGap(x = mydata, FUNcluster = kmeans, K.max = 10, B = 50, nstart = 25)
B=50 simulated reference sets, k = 1..10; spaceH0="scaledPCA"

--> Number of clusters (method 'firstmax'): 4
logW E.logW gap SE.sim
[1,] 3.458369 3.640156 0.1817869 0.04422756
[2,] 3.135112 3.372380 0.2372687 0.03558739
[3,] 2.977727 3.233913 0.2561861 0.03747805
[4,] 2.826221 3.118924 0.2927035 0.04061157
[5,] 2.738868 3.019640 0.2807720 0.04173697
[6,] 2.666967 2.929928 0.2629603 0.04102800
[7,] 2.609895 2.851923 0.2420281 0.04183308
[8,] 2.537521 2.778291 0.2407703 0.04289286
[9,] 2.468162 2.711324 0.2431612 0.04340014
[10,] 2.400620 2.647381 0.2467610 0.04546883

> fviz_gap_stat(gap_stat)

Image containing a chart. Automatically generated description

Figure 6 – Optimal number of clusters with the gap statistic method

We decide to use k = 4 as the optimal number of clusters and fit the final model:

> # k-means clustering con k = 4
> set.seed(123)
> final_model <- kmeans(mydata, 4, nstart = 25)
> print(final_model)

K-means clustering with 4 clusters of sizes 8, 13, 16, 13

Cluster means:
      Murder    Assault   UrbanPop        Rape
1  1.4118898  0.8743346 -0.8145211  0.01927104
2 -0.9615407 -1.1066010 -0.9301069 -0.96676331
3 -0.4894375 -0.3826001  0.5758298 -0.26165379
4  0.6950701  1.0394414  0.7226370  1.27693964

Clustering vector:
       Alabama Alaska Arizona Arkansas
             1      4       4        1
             …

Within cluster sum of squares by cluster:
[1] 8.316061 11.952463 16.212213 19.922437
(between_SS / total_SS = 71.2 %)

Available components:
[1] "cluster" "centers" "totss" "withinss"
    "tot.withinss" "betweenss" "size" "iter"
[9] "ifault"

Let us visualise the clusters:

> fviz_cluster(final_model, data = mydata)

Figure 7 – Clustering with k = 4

A variant of K-means is Partitioning Around Medoids (PAM or K-medoids), which, instead of using the mean to determine the cluster centroid, uses the most central point (the medoid). The PAM algorithm is less sensitive to outliers than K-means, but computing the central point is computationally expensive. PAM is available in R through the pam() function:

> #k-mediods
> model_medoids <- pam(mydata, 4)
> print(model_medoids)

Medoids:
              ID     Murder    Assault   UrbanPop         Rape
Alabama        1  1.2425641  0.7828393 -0.5209066 -0.003416473
Michigan      22  0.9900104  1.0108275  0.5844655  1.480613993
Oklahoma      36 -0.2727580 -0.2371077  0.1699510 -0.131534211
New Hampshire 29 -1.3059321 -1.3650491 -0.6590781 -1.252564419

Clustering vector:
      Alabama Alaska Arizona Arkansas
            1      2       2        1      …

Objective function:
build swap
1.035116 1.027102

Available components:
[1] "medoids" "id.med" "clustering" "objective" "isolation"
    "clusinfo" "silinfo" "diss" "call"
[10] "data"

Let us look at the results, which differ slightly from those of the k-means method:

> fviz_cluster(model_medoids, data = mydata)

Image containing a chart. Automatically generated description

Figure 8 – Clustering with PAM

 

Want to learn more? Buy the book Data Science e Machine Learning: dai dati alla conoscenza on Amazon:

Try it yourself

An interactive demo of the ideas in this article: you can use it right here on the page.

DEMO K-means step by step · about this demo · full screen ↗