Visualized ML
Topics

C · Classic ML

k-Means Clustering

Find k groups in unlabelled data by alternating two steps: assign each point to its nearest centre, then move each centre to the mean of its points.

Try it: C2 · k-Means

Intuition

Sometimes there are no labels at all, only data, and the question is what groups it falls into: customer types, colours in an image, kinds of documents. That is clustering, the classic example of unsupervised learning. k-means is its best-known method.

You choose the number of groups \(k\). Each group is represented by a centre point. Then two simple steps repeat. Assign: every point joins the group of its nearest centre. Update: every centre moves to the mean of the points in its group. Repeat until nothing changes. Each step can only make the groups tighter, so the process always settles, usually within a few rounds.

Three centres (crosses) start in poor places. Each round, every point takes the colour of its nearest centre, then each centre slides to the mean of its points, leaving a dashed trail. The bars on the right show the sum of squared distances after each round: it never goes up.

The math

k-means looks for centres \(\boldsymbol\mu_1, \dots, \boldsymbol\mu_k\) and an assignment \(c(i)\) of each point to a centre that minimize the within-cluster sum of squares (also called inertia):

\[ J = \sum_{i=1}^{n} \lVert \mathbf{x}_i - \boldsymbol\mu_{c(i)} \rVert^2 \]

Lloyd's algorithm minimizes \(J\) one half at a time:

  1. Assign, with the centres fixed: \(c(i) = \arg\min_j \lVert \mathbf{x}_i - \boldsymbol\mu_j \rVert^2\). Each point's term in \(J\) is as small as it can be.
  2. Update, with the assignment fixed: \(\boldsymbol\mu_j = \frac{1}{|C_j|}\sum_{i \in C_j}\mathbf{x}_i\). The mean is the point with the smallest total squared distance to a group (set the gradient \(\sum_{i \in C_j} 2(\boldsymbol\mu_j - \mathbf{x}_i)\) to zero), so each cluster's part of \(J\) is as small as it can be.

Neither step can increase \(J\), and there are only finitely many assignments, so the algorithm stops. But it stops at a local minimum, which depends on where the centres started.

Worked example. One-dimensional points \(1, 2, 4, 7, 8\), \(k = 2\), centres starting at 1 and 2.

Round 1. Assign: \(\{1\}\) and \(\{2, 4, 7, 8\}\). Update: centres 1 and 5.25. \(J = 22.75\).

Round 2. Assign: 2 is now closer to 1, giving \(\{1, 2\}\) and \(\{4, 7, 8\}\). Update: centres 1.5 and 6.33. \(J = 9.17\).

Round 3. Nothing changes: done. Yet \(\{1, 2, 4\}\) and \(\{7, 8\}\) would give \(J = 5.17\). The poor start led to a local minimum, which is why k-means is run several times from different starts.

Practical points

  • k-means++ initialization. Choose the first centre at random from the data, then each next one from the data with probability proportional to its squared distance to the nearest centre already chosen. Centres start spread out; the result is provably within a factor \(O(\log k)\) of optimal in expectation, and usually much closer. It is the default in most libraries.
  • Several restarts. Run it a few times and keep the result with the lowest \(J\).
  • Choosing k. \(J\) always falls as \(k\) grows (at \(k = n\) it is 0), so it cannot choose \(k\) on its own. Look for an "elbow" where adding a cluster stops helping much, use the silhouette score, or let the application decide (a palette of 16 colours).
  • Mini-batch k-means updates the centres from small random samples, scaling to millions of points.

Relatives

  • Gaussian mixture models give soft assignments (each point belongs to each cluster with some probability) and clusters with their own shapes; k-means is their limit when every cluster is a small round Gaussian.
  • k-medoids uses actual data points as centres, which works with any distance.
  • DBSCAN grows clusters from dense regions, finds their number by itself, handles any shape and labels outliers as noise.
  • Hierarchical clustering builds a tree of merges, from single points up to one cluster, so you can cut it at any level.
  • Vector quantization. The centres themselves are useful: replacing each point with its centre compresses data, from image colour palettes to codebooks in speech coding and in some generative models.

Pitfalls

  • Round clusters only. Assigning to the nearest centre cuts space into straight-edged cells, so k-means cannot find long, curved or nested clusters, and it splits big clusters to balance small ones.
  • Scaling. As with any distance method, standardize features first.
  • Outliers. The mean is pulled by extreme points; one far-off point can drag a centre away from its cluster.
  • Empty clusters. A centre can end up with no points. Implementations re-seed it, for example at the point furthest from its centre.
  • Clusters are not truth. k-means always returns \(k\) groups, even from data with no structure.

History

Stuart Lloyd devised the algorithm at Bell Labs in 1957 for quantizing signals in pulse-code modulation; it was published only in 1982. Hugo Steinhaus had described the idea in 1956, and James MacQueen named it "k-means" in 1967. David Arthur and Sergei Vassilvitskii introduced k-means++ in 2007.

Connections

Builds on

Further reading