Clusters, one step at a time
Give k-means a cloud of points and a number k, and it finds k groups by repeating two simple steps: give every point to its nearest centroid, then move every centroid to the mean of its points. Watch both steps animate, the coloured regions of the centroids, their trails and the inertia falling on a chart. See how the start decides the result, choose k with the elbow and the silhouette, discover the shapes k-means cannot find and turn a picture into a palette of k colours. K-means clustering splits points into k groups by repeating two steps. Assignment: every point joins its nearest centroid, so the coloured regions, the Voronoi cells of the centroids, show where each point goes. Update: every centroid moves to the mean of its points, leaving a dashed trail. Each step lowers the inertia, the sum of squared distances from the points to their centroids (the chart), and when an assignment changes no point the run has converged. Press Play, or Step through it half a step at a time. The start matters: k-means++ picks each new centre with a chance proportional to D², the squared distance to the nearest centre so far (shown as point sizes); random points, Forgy and random partition are simpler and more often end in a poor local minimum, which Restarts fixes by keeping the best of several runs. Choose k with the elbow of the inertia chart or the highest silhouette. Moons and rings show where k-means fails: it can only cut the plane with straight lines. Stretched data need Scale features. The picture preset clusters the colours of a picture into a palette. Click to add points, drag them, double-click one to delete it. Save image, record a video with a soft chord per iteration, or open the picture in the photo editor with the pencil, where the regions, each cluster's points, the centroids, the trails and the chart are layers of their own.
How it works
- Press Play: the centroids appear, every point takes the colour of its nearest centroid, then every centroid glides to the mean of its points. Step goes half a step at a time, Back goes back.
- Change Initialisation: k-means++ shows its chances as point sizes while it picks each centre; random points, Forgy and random partition start blind. Raise Restarts to keep the best of several runs.
- Switch the chart to the elbow or the silhouette to see which k fits the data, or to the silhouette of each point to see which points sit badly.
- Pick moons, rings or stretched data to see k-means fail, turn on Scale features, or choose Colour quantisation to cluster the colours of a picture; click to add points and drag them.
Two steps, repeated
K-means looks for k centres, the centroids, that make the points as close as possible to their nearest centre. Lloyd's algorithm alternates two steps. In the assignment step every point joins the cluster of its nearest centroid, so the plane is cut into the Voronoi cells of the centroids, the coloured regions. In the update step every centroid moves to the mean of the points in its cluster, the point that minimises their squared distances. Neither step can raise the inertia, the sum of squared distances from the points to their centroids, and there are only finitely many ways to split the points, so the algorithm always stops: when an assignment changes no point, it has converged.
Where you start decides where you end
Lloyd's algorithm only goes downhill, so it stops in a local minimum that depends on the starting centroids: two centroids can share one cluster while another pair of clusters shares one centroid. Random points and Forgy (k data points at random) often start badly; random partition puts every centroid near the middle. K-means++, by David Arthur and Sergei Vassilvitskii (2007), picks the first centre at random and every next one with a chance proportional to D², the squared distance to the nearest centre already chosen, which spreads the centres out and is provably within a factor O(log k) of the best inertia on average. Running several times and keeping the lowest inertia, the n_init of libraries, helps as well.
How many clusters?
K-means needs k in advance, and the inertia always falls as k grows, reaching zero when every point is its own cluster. The elbow method plots the inertia against k and looks for the bend where adding a cluster stops paying off. The silhouette, by Peter Rousseeuw (1987), compares for every point the mean distance a to its own cluster with the mean distance b to the nearest other cluster: s = (b − a) / max(a, b) runs from −1 (in the wrong cluster) to 1 (well inside its own). The k with the highest mean silhouette is a good choice; above 0.7 the structure is strong, below 0.25 there is hardly any.
What k-means cannot see
Because every point goes to its nearest centroid, k-means always cuts the plane with straight lines into convex regions, and it prefers round clusters of similar size and spread. Two interleaved moons, a ring round a blob, long sheared clusters or one big cluster beside small ones defeat it, however long it runs. Density-based clustering such as DBSCAN, spectral clustering and Gaussian mixture models handle those shapes. Distances also depend on units: when one feature spreads far wider than another, it decides everything, so features are usually standardised first. The same algorithm in colour space reduces a picture to a palette of k colours.
Frequently asked questions
What is k-means clustering?
An unsupervised machine learning method that splits a set of points into k groups. Each group is represented by its centroid, the mean of its points, and every point belongs to the nearest centroid. The algorithm looks for the centroids that make the total squared distance from the points to their centroids, the inertia or within-cluster sum of squares, as small as possible.
How does Lloyd's algorithm work?
Start with k centroids. Assign every point to its nearest centroid, then move every centroid to the mean of its points, and repeat. Each step lowers the inertia or leaves it unchanged, so the process ends, usually within a few dozen iterations, when no point changes cluster. The app shows the two steps separately: the points recolour, then the centroids glide.
Why does k-means give different results each time?
It only ever moves downhill from where it starts, so it ends in a local minimum that depends on the initial centroids. With an unlucky start two centroids can split one real cluster while another centroid covers two. K-means++ seeding makes bad starts rare, and running several times with different seeds and keeping the lowest inertia, which the app calls Restarts, makes them rarer still.
How do I choose k?
Look at the elbow chart: the inertia for k = 1 to 10 falls steeply while k is below the true number of groups and slowly after it, so the bend suggests k. Or look at the mean silhouette, which is highest for the k whose clusters are tight and well apart. Both are heuristics; what the clusters are for matters too.
When does k-means fail?
When the clusters are not round blobs of similar size: interleaved moons, rings, long sheared shapes, very unequal sizes or densities. K-means draws straight boundaries halfway between centroids, so it cuts such shapes apart. DBSCAN, spectral clustering or a Gaussian mixture model fit them better. Unscaled features with very different spreads also mislead it.
Can I use the picture?
Yes. Save gives a PNG at the size you choose, Save JSON writes the centroids, the cluster sizes, the inertia, the silhouette and every run, Record films the algorithm with a soft chord per iteration, and the pencil opens the picture in the PictorX photo editor with the background, the regions, each cluster's points, the centroids, the trails, the labels and the chart on layers of their own. In the editor itself it is under Apps ▸ Science ▸ Computing ▸ K-Means Clustering. Everything runs in your browser.
K-Means Clustering: how do I record a video?
Press the red Record button in the playback bar: it films what the stage shows. Press it again to stop, and the video is saved to your device. Recording is free; you only need to sign in. Without a subscription the video carries a small PictorX logo in a corner. The button beside Record opens the video options: the shape (as shown, square, story 9:16 or wide 16:9), the length (until you stop, or 5, 10, 15 or 30 seconds for social media) and the file: MP4, WebM or an animated GIF. For the sound, choose the app's own sounds or one of three music tracks: calm, bright or beat.
Ready to try it?
Open PictorX in your browser — no install, no credit card required to start.
Go to Editor