TL;DR
K-means groups unlabelled data into clusters. It keeps one centre per cluster and repeats two steps: give each point to its nearest centre, then move each centre to the average of the points assigned to it. Each step cannot increase the total squared distance from points to their centres, so the procedure settles, though possibly at a local optimum.
Where you'll see it: customer or document segmentation, compressing colours in an image to a small palette, and building the codebook in Vector Quantization.
Intuition
Suppose you have a pile of points on a table and want to split them into three groups without being told what the groups are. Drop three markers at random on the table. Each point goes to the marker it is closest to. Then move each marker to the middle of the points that chose it. Some points now have a different nearest marker, so repeat. After a few rounds the assignments stop changing and the markers sit in the middle of their groups.
The idea behind the mean is that a centre should be as close as possible, on average, to the points it represents. The average is the point that minimises the sum of squared distances to a set of points, which is why the update step uses it. The assignment step does the other half of the job: for fixed centres, the nearest centre is the best choice for each point.
The algorithm works best when the groups are roughly round and of similar size. Squared distance treats every direction the same, so long, thin or very uneven groups get cut in the wrong place.
flowchart TD
A[Pick k starting centres] --> B[Assign each point to its nearest centre]
B --> C[Move each centre to the mean of its points]
C --> D{Any assignment changed?}
D -- yes --> B
D -- no --> E[Stop: clusters are the current groups]
The math
Let the data be points . We want centres and an assignment for each point, the index of the centre that point belongs to.
Minimise the within-cluster sum of squares
where is the Euclidean norm and is the centre assigned to point . Minimising over both the assignments and the centres is the k-means problem.
Finding the global minimum is NP-hard in general, so the practical method is the alternating procedure, usually called Lloyd's algorithm:
- Assignment step. With the centres fixed, set each to the index of the nearest centre: .
- Update step. With the assignments fixed, set each centre to the mean of its cluster :
Why the update is the mean
Take one cluster and fix its points. The function is a sum of squares, so it is smooth and has one minimum. Setting its gradient to zero gives
So the mean is the best single centre for its cluster.
Why the procedure converges
Each step can only lower , or leave it the same. The assignment step picks, for each point, the nearest centre, which is the smallest term in its sum, so does not rise. The update step moves each centre to its cluster's mean, which the calculation above shows is the minimum for that cluster, so does not rise either. There are only finitely many ways to partition points into clusters, and never increases, so the procedure must stop. It stops at a point where neither step changes anything: a local minimum of , which may not be the global one.
Worked examples
Take the one-dimensional points and . Start with centres and .
- Assign. Point 0 is nearest to . Point 4 is at distance 4 from and 6 from , so it goes to cluster 1. Point 6 is at distance 6 from and 4 from , so it goes to cluster 2. Point 10 goes to cluster 2. Clusters: and .
- Update. and .
- Assign again. Point 0 is at distance 2 from and 8 from , so cluster 1. Point 4 is at distance 2 and 4, so cluster 1. Point 6 is at distance 4 and 2, so cluster 2. Point 10 is cluster 2. Nothing changed.
- Stop. The objective is .
Interpretation: two rounds were enough. Each centre ended up at the middle of its pair, and the squared distances from points to centres add up to 16.
Use the points and compare , and . The best solution for each gives its smallest .
- . One centre at the mean . The squared distances are .
- . The clusters and have means and . Each point is at distance from its mean, so .
- . The clusters , and have means , and . .
Interpretation: going from to removes almost all the error, from 65 to 1. Going from to removes only half of what remains. The curve of against bends at , which is the usual "elbow" used to pick . The rule is a heuristic: it shows where extra clusters stop helping much, not what the true number of groups is.
Tradeoffs and failure modes
K-means is fast, simple and scales to large datasets, because each iteration costs about operations. It also has known weaknesses.
| Situation | Problem | Better choice |
|---|---|---|
| Starting centres are random | Different starts give different local optima | Run several times and keep the lowest , or use k-means++ seeding |
| Clusters are long, thin or curved | Squared distance cuts them along the wrong lines | [[mixture-model |
| Features have very different units | The feature with the largest numbers dominates the distances | Standardise the features first |
| Outliers are present | A single far point pulls its centre toward it | Remove or clip outliers, or use a robust variant |
| You need soft membership or a probability per cluster | Each point gets one hard label | A mixture model fitted by expectation-maximisation |
| You do not know | The objective always falls as grows | Use the elbow heuristic, or compare models with a criterion that penalises complexity |
The most common mistake is to skip feature scaling. Income in dollars and age in years differ by orders of magnitude, so the clusters end up reflecting income alone.
History
Hugo Steinhaus proposed the basic idea of splitting data around representative points in 1956. Stuart Lloyd described the alternating procedure in a Bell Labs report in the late 1950s, which was published in 1982. James MacQueen gave the method the name "k-means" in 1967. Arthur and Vassilvitskii introduced k-means++ in 2007, a seeding rule that picks spread-out starting centres and gives a guarantee on the objective, which made the method much more reliable in practice.
Check yourself
QuestionWhat does the assignment step of k-means do, and why can it never increase the objective?Show answer
It gives each point to its nearest centre. Each point's term in is its squared distance to its assigned centre, so choosing the nearest centre makes each term as small as it can be with the centres fixed. The sum therefore does not rise.
QuestionPoints are . Start with centres and and run one full iteration. What are the clusters, the new centres and the objective?Show answer
Assignment: goes to cluster 1 and to cluster 2, since 4 is closer to 0 than to 10 and 6 is closer to 10 than to 0. Update: and . Objective: . In a second iteration the assignments do not change, so the algorithm stops.
QuestionWhy is the mean of a cluster the best centre for that cluster under squared distance?Show answer
The sum of squared distances from a fixed set of points to a single centre is a smooth function of with one minimum. Its gradient is , which is zero exactly when equals the average of the points. So the mean minimises the squared error for that cluster.
QuestionApplied: you cluster customers using annual income in dollars (0 to 200,000) and age in years (18 to 90). The clusters look like income bands and ignore age completely. What is going on, and what would you change?Show answer
Squared distance is dominated by the feature with the largest numbers. A difference of 10,000 dollars adds to the squared distance, while a difference of 10 years adds only 100, so income decides every assignment. The fix is to standardise each feature, for example by subtracting its mean and dividing by its standard deviation, before running k-means. Then both features contribute on a comparable scale. Whether that is the right weighting for the business question is a separate decision.
Sources
- K-means clustering (Wikipedia)
- Bishop, Pattern Recognition and Machine Learning, §9.1. https://www.microsoft.com/en-us/research/publication/pattern-recognition-machine-learning/