Kolton Ndoj

k-means clustering: letting data sort itself into groups

A classic way to shrink a photo to 16 or 256 colours (like a GIF), and to group similar songs, shoppers or stars

What problem does it solve?

How do you split a cloud of points into k natural groups when nobody tells you what the groups are?

The big idea

Drop k 'centres' anywhere. Every point joins its nearest centre, then every centre moves to the average of its members. Repeat: points switch teams, centres drift, and very quickly nothing moves any more. Each round can never raise the total squared distance from points to their centres, so it must eventually settle, though possibly in a merely 'okay' arrangement rather than the best one.

How it works, step by step

  1. 1. Choose k and place k centres (randomly, or spread out using k-means++).
  2. 2. Assign each point to its closest centre.
  3. 3. Move each centre to the mean of its assigned points.
  4. 4. Repeat steps 2–3 until no point changes team.

The key formula

min⁡∑j=1k∑x∈Cj∥x−μj∥2\min \sum_{j=1}^{k}\sum_{x\in C_j}\lVert x-\mu_j\rVert^2
CjC_j
the points in cluster j
μj\mu_j
the centre (average) of cluster j
∥x−μj∥2\lVert x-\mu_j\rVert^2
squared distance from a point to its centre; the total is what k-means shrinks

How fast is it?

Each round costs about n·k distance checks, and usually only a few dozen rounds are needed. Finding the truly best clustering is NP-hard, so in practice you run it several times from different starts and keep the best.

Try it yourself

Fun fact

Stuart Lloyd devised the method at Bell Labs in 1957 to turn sound signals into digital levels, but it wasn't formally published until 1982. Its smarter starting rule, k-means++, came in 2007.

Related

Open it in the Math Lab →

AI · Intermediate