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. Choose k and place k centres (randomly, or spread out using k-means++).
- 2. Assign each point to its closest centre.
- 3. Move each centre to the mean of its assigned points.
- 4. Repeat steps 2–3 until no point changes team.
The key formula
- the points in cluster j
- the centre (average) of cluster j
- 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
- Make two long, thin, parallel clusters. Does k-means split them the way you would? Why not?
- Start badly on purpose: put all centres in one corner. Does it still find good groups?
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.