Clustering with k-means
Last updated
Sometimes there are no labels at all, only data, and the question is whether it falls into groups. Customers who shop alike, sensors that fail alike, penguins of different species before anyone named them. k-means finds k groups with two steps repeated until nothing moves. It's fast and simple, and it will always give you k groups, whether or not they're really there.
By the end of this lesson you can
- Run k-means by hand: assign to the nearest centre, then move each centre to its points’ mean
- Measure a clustering with inertia, and choose k with the elbow and the silhouette
- Explain why the start matters, and how k-means++ and restarts help
Groups without labels
Lesson 2.2 asked KMeans to split the penguins into three groups without telling it the species, and it mostly found them. That's clustering: unsupervised learning (lesson 2.2) that puts similar examples together. It's used to find kinds of customer, to group news stories, to compress images to a few colours, and to explore data before anyone has labelled it.
-means describes each of groups by its centroid, its centre, the mean of its points. Every point belongs to the group whose centroid is nearest.
Assign, then update
Lloyd's algorithm alternates two steps:
- Assign: put every point in the group of its nearest centroid.
- Update: move every centroid to the mean of the points in its group.
Repeat until no point changes group. Try it, a half-step at a time:
Four centres, placed on four random points. Press Assign: every point joins its nearest centre.
The centres start on four random points. After the first assignment, the groups are odd shapes; after the first update, each centre jumps towards the middle of its points; within a few rounds, they've each found a cloud and stopped. In NumPy, with broadcasting (lesson 0.5) to measure all 300 × 4 distances at once:
Inertia
The numbers printed are the inertia, the sum of each point's squared distance to its centroid:
where is point 's group and is centroid . It fell from 4,045 to 995 to 397 to 395, and then nothing moved. Each step can only lower it: assigning a point to a nearer centre shortens its distance, and the mean is the point with the smallest total squared distance to a group. So -means always stops. But it stops at the bottom of whatever valley it started in, which might not be the lowest one.
Wrong way: a bad start
Start all four centroids on the four points furthest to the left:
Inertia 723, against 395 from a good run. The group sizes show what went wrong: 34, 75, 41 and 150. One centroid holds two whole clouds, and two others share one cloud between them. Neither can escape: every step only makes small improvements. Press "Bad start" in the figure above and run it to see.
Two fixes, both on by default in scikit-learn:
- k-means++ (Arthur and Vassilvitskii, 2007) picks the starting centroids spread apart: the first at random, each next one chosen with a probability proportional to its squared distance from the nearest centroid already chosen.
- Restarts:
n_init=10runs the whole thing ten times from different starts and keeps the lowest inertia. That's what found 395, with groups of 74, 75, 75 and 76.
Choosing k: the elbow and the silhouette
-means needs in advance. Inertia can't choose it alone, because it always falls as grows (with as many groups as points, it's 0). Two common guides:
- The elbow: plot inertia against , and look for where adding a group stops helping much.
- The silhouette: for each point, is its mean distance to the others in its own group and its mean distance to the nearest other group. Its silhouette is : near 1 if it sits well inside its group, near 0 on a border, negative if it's probably in the wrong one. The mean over all points scores the clustering.
Inertia drops steeply to (3,336, 760, 395) and slowly after (352, 316): the elbow says 4, which is how the data was made. The silhouette is highest at , 0.718 against 0.669, because two of the four clouds sit close together and from far off look like one.
So the two guides disagree, and neither is wrong. "How many groups?" often has no single answer; it depends on how fine a split is useful. A shop might want 3 customer groups for its posters and 12 for its emails. Choose with the purpose in mind, then look at the groups and check they make sense.
When to use it
Good at
- Round, similar-sized groups
- Speed: big data, with MiniBatchKMeans
- Summarising data by a few typical points (its centroids)
Bad at
- Long, curved or nested clusters (lesson 4.9)
- Groups of very different sizes or spreads
- Outliers, which drag centroids
- Telling you whether there are any groups at all: it always returns k
Needs from you
- k, chosen with the elbow, the silhouette and the purpose
- Scaled features: it’s built on distances
- Several restarts (n_init)
In scikit-learn
- Classification: none: it clusters;
KMeans,MiniBatchKMeans - Regression: none
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Lloyd, Least squares quantization in PCM, IEEE Transactions on Information Theory 28(2), 1982: the assign-and-update algorithm, written in 1957 and published in 1982
- scikit-learn: kmeans_plusplus: k-means++ (Arthur and Vassilvitskii, 2007): spreading out the starting centres
- Rousseeuw, Silhouettes: a graphical aid to the interpretation and validation of cluster analysis, Journal of Computational and Applied Mathematics 20, 1987: the silhouette score
- scikit-learn: Clustering, k-means: KMeans, inertia, n_init and k-means++