The -means clustering algorithm attempts to solve the following optimization problem:
where is observation , is a cluster assignment function, and is a cluster mean. To solve this problem, -means uses an iterative approach that updates and the ’s alternately. Suppose we have a set of six observations.
The six observations are the original example generated in R with set.seed(3) and replicate(2, rnorm(6)). Both languages read the same observations and initial assignments.
We first randomly assign them into two clusters (initialize a random function). Based on this cluster assignment, we can calculate the corresponding cluster means .
Then we assign each observation to the closest cluster mean. In this example, only the navy point at the top moves to a new cluster. Then the cluster means can be recalculated.
When there is nothing to move anymore, the algorithm stops. Keep in mind that we started with a random cluster assignment, and this objective function is not convex. Hence we may obtain different results if we start with different values. The usual approach is to try different starting points and use the result with the smallest final within-cluster sum of squares. This is controlled by nstart in R’s kmeans() and n_init in Python’s KMeans.
The original comparison uses a matrix of standard normal observations and compares one start with 100 starts. We use the same data matrix and 100 sets of initial center rows in both languages. The first fit is included among the 100, so the best of 100 cannot have a larger objective. Here we specify Lloyd’s alternating updates in R to match Python’s algorithm.
mat <-as.matrix(read.csv("data/unsupervised/clustering-starts-data.csv"))starts <-as.matrix(read.csv("data/unsupervised/clustering-starts-indices.csv"))withinss <-numeric(100)for (s in1:100) { fit <-kmeans(mat, centers = mat[starts[s, ], ],nstart =1, algorithm ="Lloyd", iter.max =100) withinss[s] <- fit$tot.withinss}knitr::kable(data.frame(starts =c(1, 100), total_withinss =c(withinss[1], min(withinss))), digits =3)
starts
total_withinss
1
899.601
100
889.166
Show the reproducible code
mat = pd.read_csv("data/unsupervised/clustering-starts-data.csv").to_numpy()starts = pd.read_csv("data/unsupervised/clustering-starts-indices.csv").to_numpy() -1withinss = np.zeros(100)for s inrange(100): fit = KMeans(n_clusters=3, init=mat[starts[s]], n_init=1, algorithm="lloyd", max_iter=100, tol=0, random_state=1).fit(mat) withinss[s] = fit.inertia_pd.DataFrame({"starts": [1, 100],"total withinss": [withinss[0], withinss.min()]}).round(3)
starts total withinss
0 1 899.601
1 100 889.166
With ordinary random starts, the corresponding calls are kmeans(mat, centers = 3, nstart = 100) and KMeans(n_clusters=3, init="random", n_init=100, random_state=1).fit(mat). Equal seed numbers do not generate the same random starts across languages. Multiple starts improve the search but do not guarantee the global minimum.
Example 1: iris data
We use the classical iris data as an example. This dataset contains three different classes, but the goal here is to learn the clusters without knowing the class labels.
The iris observations, colored by species for comparison.
The last two variables in the iris data carry more information on separating the three classes. Hence we will only use Petal.Length and Petal.Width. The parallel coordinate plot below compares all four measurements after putting each variable on a common 0-to-1 plotting scale. This rescaling is for the plot; the clustering uses petal measurements in centimeters.
Parallel coordinates of the four iris measurements, colored by species.
Let’s perform the -means clustering with three clusters and 20 random starts. R retains its default Hartigan-Wong algorithm; Python uses Lloyd’s algorithm. Both minimize the same within-cluster sum of squares, although their search steps and random streams differ.
The fitted groups recover the isolated small-petal group, but some observations from the other two species are grouped together. Cluster numbers are arbitrary. For the plot only, we order colors by fitted petal length; the species labels do not enter the fit. The cross-tabulation compares clusters with the known classes afterward.
Example 2: Image Pixels
Let’s first load and plot an image of Leo and Lia (all rights reserved).
The original JPEG is supplied with a lossless PNG copy, decoded once using R’s jpeg package. We read that copy in both languages so that JPEG decoder differences do not change the observed RGB values.
The original photograph of Leo and Lia. All rights reserved.
In this color image, each pixel has three elements representing red, green, and blue intensities. The object img is stored as a three-dimensional array. The first two dimensions are the height and width of the image. We need to vectorize them and treat each pixel as an observation.
# Vectorize each red, green, and blue layer in column order.img_expand <-apply(img, 3, c)dim(img_expand)
[1] 200000 3
Show the reproducible code
print(img.shape)
(500, 400, 3)
Show the reproducible code
# Column order matches the vectorization of each color layer in R.img_expand = img.reshape(-1, 3, order="F")print(img_expand.shape)
(200000, 3)
Before performing the -means clustering, let’s have a quick peek at the data in a three-dimensional view. Since there are many observations, we randomly sample 1,000 pixels.
A sample of 1,000 pixels in red-green-blue color space.
The next step is to perform -means and obtain a cluster label for every pixel. For example, let’s try five clusters. We cluster color intensities only; the pixel’s location in the photograph is not used.
The photograph reconstructed using five cluster mean colors.
Show the reproducible code
kmeanfit = KMeans(n_clusters=5, init="random", n_init=1, max_iter=100, tol=0, algorithm="lloyd", random_state=1).fit(img_expand)# Replace each pixel with its cluster's mean color.new_img_expand = kmeanfit.cluster_centers_[kmeanfit.labels_]new_img = new_img_expand.reshape(img.shape, order="F")fig, ax = plt.subplots(figsize=(4, 5))ax.imshow(np.clip(new_img, 0, 1))ax.axis("off")plt.tight_layout(pad=0)plt.show()
The photograph reconstructed using five cluster mean colors.
With this technique, we can easily reproduce results with different values. As increases, we retain more color detail. recovers the original image fairly well. The number of spatial pixels is unchanged; this is a reduction in the number of colors.
Different initializations and fitting algorithms can produce slightly different palettes. Both routes use all pixels, RGB values on , the same numbers of clusters, and one random start for each reconstruction.