Traditional models · lesson 8 of 16
Parts in this lesson
Ad.argmin(axis=1)0.4: each point’s nearest centre
BX[group == k].mean(axis=0)each centre moves to its points’ mean
CKMeans(4, n_init=10)k-means, started ten times, best kept
Dsilhouette_score(X, labels)how well each point fits its group

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.

k-means describes each of k 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:

  1. Assign: put every point in the group of its nearest centroid.
  2. 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:

Centroid dancek-means with k = 4

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:

kmeans.ipynb

Inertia

The numbers printed are the inertia, the sum of each point's squared distance to its centroid:

inertia=∑i‖xi−μg(i)‖2

where g(i) is point i's group and μk is centroid k. 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 k-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:

kmeans.ipynb

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=10 runs 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

k-means needs k in advance. Inertia can't choose it alone, because it always falls as k grows (with as many groups as points, it's 0). Two common guides:

  • The elbow: plot inertia against k, and look for where adding a group stops helping much.
  • The silhouette: for each point, a is its mean distance to the others in its own group and b its mean distance to the nearest other group. Its silhouette is s=b−amax⁡(a,b): 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.
kmeans.ipynb

Inertia drops steeply to k=4 (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 k=3, 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

When to use k-means

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

In k-means’ update step, where does each centroid move?
Two runs of k-means on the same data, with different random starts, give inertias of 410 and 395. What should you conclude?
Why can’t you choose k by picking the k with the lowest inertia?

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.

All sources for Simple Machine Learning