MoonSay /Tutorials/Machine Learning Interview #3
Contents
  1. 01Introduction
  2. 02What clustering is
  3. 03K-means
  4. 04Choosing K, and where K-means fails
  5. 05Gaussian mixture models and the EM algorithm
  6. 06Dirichlet process mixtures
  7. 07DBSCAN
  8. 08Hierarchical clustering
  9. 09Spectral clustering
  10. 10Putting it all together
  11. 11Interview questions and model answers
  12. 12Summary
  13. References
Clustering Algorithms/Chapter 03 of 12

03K-means: a cluster is a set of points close to a centre

3.1The objective and Lloyd’s algorithm

K-means looks for K centres and an assignment that minimize the within-cluster sum of squares (1). The objective has two kinds of unknowns, the discrete labels c and the continuous centres \mu, and is easy to minimize over either one when the other is fixed. Lloyd’s algorithm alternates the two:

  1. Assignment step. With the centres fixed, J is a sum of separate terms, one per point, so each point should take its nearest centre: c_i=\operatorname*{arg\,min}_k\|x_i-\mu_k\|^2.
  2. Update step. With the labels fixed, J is a sum of separate quadratic functions, one per cluster. Setting the gradient of \sum_{i:c_i=k}\|x_i-\mu_k\|^2 to zero gives -2\sum_{i:c_i=k}(x_i-\mu_k)=0, so \mu_k=\bar x_k, the mean of the cluster.

Lloyd thought of it physically: for a fixed partition, the total moment of inertia is smallest when each centre sits at the centre of mass of its cell (Lloyd, 1982). The following identity, which is behind every proof about K-means, makes this exact.

Lemma 1 (Arthur and Vassilvitskii, 2007, Lemma 2.1). For a set S of points with mean \bar x_S and any point z,

\sum_{x\in S}\|x-z\|^2=\sum_{x\in S}\|x-\bar x_S\|^2+|S|\,\|\bar x_S-z\|^2 . \tag{3}

Write x-z=(x-\bar x_S)+(\bar x_S-z) and expand the square: \|x-z\|^2=\|x-\bar x_S\|^2+2(x-\bar x_S)^\top(\bar x_S-z)+\|\bar x_S-z\|^2. Summing over x\in S, the middle term vanishes because \sum_{x\in S}(x-\bar x_S)=0.

The lemma says that moving a centre away from the mean by a distance \delta costs exactly |S|\delta^2; it is the same algebra as the bias–variance decomposition. Applying (3) with z equal to each point of S in turn and averaging gives another useful form: the scatter of a cluster about its mean is \frac{1}{2|S|}\sum_{x\in S}\sum_{x'\in S}\|x-x'\|^2, so J can be written with the distances between points of the same cluster alone, without any centres; Hastie et al. (2009, eq. 14.31) write the K-means criterion in this pairwise form, with each cluster weighted by its size.

Worked example 2. Take the three points (0,0), (2,0) and (1,3), with mean (1,1). Their squared distances to the mean are 2, 2 and 4, a total of 8. The six ordered pairs have squared distances 4,4,10,10,10,10, a total of 48, and 48/(2\cdot3)=8, as promised. About the origin instead, the total is 0+4+10=14, and the difference 14-8=6 is |S|\,\|\bar x_S\|^2=3\cdot2, as Lemma 1 says.

Theorem 1 (Convergence of Lloyd’s algorithm). Neither step increases J, and the algorithm stops after finitely many iterations at a partition that no single step can improve.

The assignment step minimizes J exactly over the labels with the centres fixed, and by Lemma 1 the update step minimizes it exactly over the centres with the labels fixed, so neither can increase J. If an iteration changes the labels, J strictly decreases (with ties broken consistently), so no partition can repeat; there are at most K^n partitions, so the algorithm stops. The Episode 1 tutorial gives this proof with a small example.

Two caveats matter in practice. First, the stopping point is a local minimum: a fixed point of the two steps, not necessarily the best partition. Hartigan and Wong (1979) refine it by also checking whether moving any single point to another cluster lowers J. Second, it usually needs only a few iterations (five in the example below), and each iteration costs O(nKd) operations.

Voronoi cells. The assignment step splits space into the cells of points nearest to each centre. The boundary between centres \mu_j and \mu_k is where \|x-\mu_j\|^2=\|x-\mu_k\|^2, that is 2(\mu_k-\mu_j)^\top x=\|\mu_k\|^2-\|\mu_j\|^2: a straight line (a hyperplane in d dimensions) perpendicular to the segment between the centres, through its midpoint. Every cell is therefore convex, and every K-means cluster lies in a convex region. This single fact explains most of K-means’ failures (Section 4.2).

The video’s animation. Figure 1 replays the K-means scene of the video: 144 points from three groups of 48 and three centres started in a deliberately bad position, two of them close together at the top left. In the first assignment the leftmost centre gets no points at all, an empty cluster, so it stays where it is (J=1550.6); the update moves the other two centres into the data (J=487.7). The empty centre then picks up 8 points, then 44, and after five updates the sixth assignment changes nothing: the clusters are exactly the three groups that generated the data, with J=100.59. The objective after each half-step is 1550.6, 487.7, 468.8, 424.7, 258.3, 114.5, 102.1, 101.1, 100.7, 100.6, never increasing. Even this fixed point is not quite optimal: scikit-learn with ten starts finds J=100.50, a partition that differs from it in a single point near a boundary.

Lloyd’s algorithm on 144 points with three centres (crosses) started badly. Shaded regions are the Voronoi cells of the current centres. (a) First assignment: the top-left centre gets no points. (b) First update: the other centres move to the means of their points (arrows). (c) Third assignment. (d) Converged after five updates. Data: computed for this tutorial, with the same data and starting centres as the companion video.
Figure 1. Lloyd’s algorithm on 144 points with three centres (crosses) started badly. Shaded regions are the Voronoi cells of the current centres. (a) First assignment: the top-left centre gets no points. (b) First update: the other centres move to the means of their points (arrows). (c) Third assignment. (d) Converged after five updates. Data: computed for this tutorial, with the same data and starting centres as the companion video.
Try itRun Lloyd's algorithm yourself

The 400 points in four groups of Figure 2. Pick K, start from random data points or with k-means++ seeding, then step through the assignment and update steps. The right panel tracks the objective J after every half-step; the dashed line is the best value scikit-learn found in ten k-means++ restarts.

3.2Seeding: k-means++

Because Lloyd’s algorithm only finds a local minimum, the start matters. Picking K random data points can put two centres in one true cluster and none in another, and Lloyd’s steps cannot repair that: a centre never jumps across another cluster. The standard remedies are many random restarts, keeping the lowest J, and k-means++ seeding (Arthur and Vassilvitskii, 2007): choose the first centre uniformly at random from the data; then repeatedly choose a data point x as the next centre with probability

P(x)=\frac{D(x)^2}{\sum_{x'}D(x')^2}, \tag{4}

where D(x) is the distance from x to the nearest centre chosen so far. Points far from all current centres are likely to be picked, so the centres spread out. Remarkably, this seeding alone, before any Lloyd step, comes with a guarantee.

Theorem 2 (Arthur and Vassilvitskii, 2007, Theorem 3.1). If the K centres are chosen by (4), the expected objective satisfies \E[J]\le8(\ln K+2)\,J_{\mathrm{opt}}, where J_{\mathrm{opt}} is the optimal value of (1).

The Lloyd steps that follow can only lower J, so k-means++ is O(\log K)-competitive with the optimum. In their experiments the gains were large: on an intrusion-detection data set of 494{,}019 points in 35 dimensions with K=50, the average objective was 3.08\times10^{8} with random seeding and 4.67\times10^{5} with k-means++, and the algorithm also finished faster (Arthur and Vassilvitskii, 2007, Table 4). k-means++ is the default in scikit-learn.

Worked example 3. Seven points on a line, 0,1,2,10,11,12 and an isolated point at 30, with K=3. Suppose the first centre is 1. The squared distances to it are 1,0,1,81,100,121,841, a total of 1145, so the second centre is the far point 30 with probability 841/1145=0.734, one of \{10,11,12\} with probability 0.264, and one of \{0,1,2\} with probability only 0.002; uniform sampling would pick 30 with probability 1/7=0.143. If the second centre is 11 instead, the squared distances to the nearest centre become 1,0,1,1,0,1,361 and the third centre is 30 with probability 361/365=0.989. The seeding reliably finds the three groups, but it is also drawn to outliers: an isolated point is the most likely next centre. This is why implementations try several candidates at each step and keep the best one, and why outliers should be handled before K-means.

3.3K-means as compression

Replacing every point by its centre is lossy compression, called vector quantization: store the K centres (the code book) and, for each point, only the index of its centre. Bishop (2006, Section 9.1.1) cluster the 240\times180=43{,}200 pixels of a colour image in RGB space. Sending the image directly costs 24 bits per pixel, 1{,}036{,}800 bits in all; with K colours it costs 24K+43{,}200\log_2K bits, which is 4.2\%, 8.3\% and 16.7\% of the original for K=2, 3 and 10. This is exactly the problem Lloyd solved for one-dimensional signals, and K-means is still the first step of many image and speech coders.

Pause and think. In Figure 1(a) one centre received no points. What does Lloyd’s update do with an empty cluster, and what do libraries do?

Show the answer

The mean of an empty set is undefined. The video’s code simply leaves the centre where it is; it can capture points later, as happened here. Libraries usually move an empty centre to a point far from its current centre (for example the point with the largest distance), which immediately lowers J.