K-means clustering explained

Give a computer a cloud of points and ask it to find groups, without telling it what the groups are: that is clustering, the classic task of unsupervised learning. K-means is the oldest and still the most used way to do it. It is simple enough to run by hand, fast enough for millions of points, and it shows clearly both what machine learning can do and where its assumptions break. This page explains what k-means optimises, how it gets there and how to use it well.

Points in six coloured clusters with the regions of their centroids, the centroids marked with crosses and the dashed trails of how they moved, beside a chart of the inertia falling with each iteration

What k-means is looking for

Given n points and a number k, k-means looks for k centres μ₁ … μₖ and a split of the points into k clusters that make the inertia as small as possible: the sum, over all points, of the squared distance from each point to the centre of its cluster. This within-cluster sum of squares measures how tight the clusters are. For a fixed split the best centre of each cluster is its mean, its centroid, and for fixed centres the best split gives each point to its nearest centre. Finding the very best solution is NP-hard even in the plane, so in practice k-means means a fast heuristic that finds a good one.

Lloyd's algorithm: assign, update, repeat

Stuart Lloyd described the standard algorithm at Bell Labs in 1957 for quantising signals; it was published in 1982, and Hugo Steinhaus and James MacQueen, who coined the name k-means in 1967, had similar ideas. Start from k centroids. In the assignment step, give every point to the nearest centroid. In the update step, move every centroid to the mean of the points now in its cluster. Repeat. The assignment step can only lower the inertia, because each point moves to a closer centre, and so can the update step, because the mean is the point with the smallest sum of squared distances. Since there are finitely many ways to split n points, the inertia cannot fall for ever: when an assignment changes no point, the algorithm has converged. Each iteration costs about n·k distance calculations, and most runs converge in tens of iterations.

The regions are Voronoi cells

The assignment step divides the plane into the Voronoi cells of the centroids: every location belongs to its nearest centroid, and the boundary between two clusters is the perpendicular bisector of their centroids. That is why k-means always produces convex clusters separated by straight lines. A converged k-means solution is a centroidal Voronoi tessellation of the data: every centroid sits at the mean of its own cell. Lloyd's relaxation of points in a region, used for stippling and meshes, is the same algorithm with a continuous density instead of data points.

Starting well: random starts and k-means++

Lloyd's algorithm only goes downhill, so the result depends on where it starts. Classic starts are random points in the data's bounding box, Forgy's method (k data points chosen at random as centroids) and random partition (every point put in a random cluster, which places all the first centroids near the middle). All of them can leave two centroids in one real cluster and one centroid stretched across two. K-means++, published by David Arthur and Sergei Vassilvitskii in 2007, picks the first centre uniformly from the data and every next one from the data with a probability proportional to D(x)², the squared distance from x to the nearest centre already chosen. Far points are likely picks, so the centres spread out, and the expected inertia of the seeding alone is within a factor 8(ln k + 2) of the optimum. It is the default in scikit-learn and most libraries.

Local minima and restarts

A converged run is a local minimum: no single assignment or update can improve it, yet a different split may have a much lower inertia. In the app, two centroids that share one blob while a neighbouring pair of blobs shares one centroid is the typical trap, and no amount of iterating gets out of it. The simple remedy is to run k-means several times from different random starts and keep the run with the lowest inertia, which libraries call n_init. With k-means++ a handful of restarts is usually enough; with purely random starts many more may be needed.

Choosing k: the elbow and the silhouette

K-means cannot tell you how many clusters there are, and the inertia is no guide on its own: it always falls as k grows and reaches zero when every point is its own cluster. The elbow method plots the best inertia against k; it drops steeply while k is below the natural number of groups and slowly afterwards, and the bend, the elbow, suggests k. The silhouette, introduced by Peter Rousseeuw in 1987, scores each point by s = (b − a) / max(a, b), where a is its mean distance to the other points of its cluster and b its mean distance to the points of the nearest other cluster. Values near 1 mean the point sits well inside its cluster, near 0 on a border, below 0 probably in the wrong cluster. The mean silhouette over all points is highest for a good k: above about 0.7 the structure is strong, 0.5 to 0.7 reasonable, 0.25 to 0.5 weak. The gap statistic and information criteria are other options.

Where k-means fails, and what to use instead

K-means assumes clusters that are round, similar in size and similar in spread, because it measures plain distances to a single centre. Two interleaved half-moons, a ring round a blob, long sheared clusters and a large diffuse cluster beside small tight ones all break that assumption, and k-means cuts them with straight lines however long it runs. DBSCAN finds clusters of any shape as regions of high density and marks outliers as noise; spectral clustering groups points through a graph of their neighbours, which separates moons and rings; Gaussian mixture models, fitted by expectation maximisation, allow elliptical clusters of different sizes and give soft memberships; k-medians and k-medoids use medians or actual data points as centres and are less sensitive to outliers. Units matter as well: if one feature varies over thousands and another over ones, the first decides every distance, so features are usually standardised to unit variance first, as the app's Scale features does.

Colour quantisation and other uses

Treat every pixel of a picture as a point in RGB space, run k-means with k = 8 or 16, and replace each pixel by its centroid: the picture is redrawn with a palette of k colours chosen to fit it, the classic way to make a GIF or a poster effect. The same idea, vector quantisation, compresses sound and images, and k-means is used to segment customers, group documents and genes, place warehouses or cell towers, build bag-of-visual-words features for image search and initialise more complex models. Mini-batch k-means and k-means|| make it practical for billions of points.

Поширені запитання

Is k-means supervised or unsupervised learning?

Unsupervised. It is given only the points, with no labels, and invents the groups itself. The clusters it finds are not guaranteed to match any categories you have in mind; checking them against known labels or against what they are used for is part of the job.

Why does k-means always converge?

Both steps lower the inertia or leave it unchanged, and the inertia depends only on how the points are split, of which there are finitely many. So the algorithm cannot cycle and must reach a split that no step changes. It converges to a local minimum, not necessarily the global one, and with ties it may stop on a split where some point is equally close to two centroids.

What happens to an empty cluster?

If no point is nearest to a centroid, the update step has no mean to move it to. Implementations either keep it where it is, remove it or move it somewhere useful; the app, like scikit-learn, moves it to the point that is farthest from its own centroid, which splits the worst-fitting cluster.

How is k-means related to the Gaussian mixture model?

K-means is the limit of a Gaussian mixture with equal, round covariances shrinking to zero: the soft memberships of expectation maximisation become hard assignments and the M-step becomes the mean. A Gaussian mixture keeps soft memberships and lets each cluster have its own shape and size, at the cost of more parameters and a slower fit.

Готові спробувати?

Відкрийте PictorX у браузері — без встановлення і без кредитної картки.

Open the k-means clustering app