Skip to content

k-means clustering

With no labels at all, find k groups by giving each point to its nearest centre, moving each centre to the mean of its points, and repeating until nothing changes.

Helps to know firstNearest neighbours

Helps to know first
This topic

First, the picture

No labels this time, only dots. Can the groups be found? Below, three centres go looking. Before it plays: can the number under the picture ever go up?

Finding groups in data

90 unlabelled dots; three centres, each dot joining the nearest and each centre moving to the mean of its dots.

90 dots with no labels at all. Three centres start bunched together below them.

total squared distance
–
dots that changed colour
–
steps taken
–
0.00 / 20.80 s
Describe this picture

One plane, feature 1 across from −4 to 4 and feature 2 up from −3.5 to 4.5, with 90 grey dots in three clouds, lower left, lower right and top, and no labels at all. Three centres, marked with crosses, start bunched together below the dots. In the clip two steps take turns. Assign: every dot takes the colour of its nearest centre; the first time, the middle centre is nearest to only a few. Move: every centre glides to the mean of its dots. After each step the total squared distance from the dots to their centres is listed beside the plane: 1216.7 after the first colouring, then 211.9, 115.1, 63.8, 59.3 and 59.1, never rising. By then each centre sits in one cloud with its 30 dots. A last assignment changes no dot’s colour, and the run stops. Readouts give the total squared distance, the dots that changed colour in the last assignment, 90, then 22, 1 and finally 0, and the steps taken. There is a play button and no other control.

The two steps

There are mm points x1,…,xm\mathbf{x}_1,\dots,\mathbf{x}_m and no labels: nobody has said which point belongs where. Choose a number of groups, or clusters, kk, and a starting place for each centre, c1,…,ck\mathbf{c}_1,\dots,\mathbf{c}_k, numbered by rr. Then repeat two steps.

Assign. Give each point to its nearest centre:

r(i)=the r with the smallest ∥xi−cr∥,r(i)=\text{the }r\text{ with the smallest }\lVert\mathbf{x}_i-\mathbf{c}_r\rVert,

so r(i)r(i) is the cluster of point ii. If two centres are equally near, the point goes to the lower rr. This is Nearest neighbours with k=1k=1, asked of the centres instead of the training examples.

Update. Move each centre to the mean of its points: the average of their first coordinates and the average of their second. A centre with no points keeps its place.

Stop when an assignment changes nothing. That is k-means.

Why it settles

Measure how well the centres fit by the total squared distance from each point to its own centre,

cost=∑i=1m∥xi−cr(i)∥2.\text{cost}=\sum_{i=1}^{m}\lVert\mathbf{x}_i-\mathbf{c}_{r(i)}\rVert^2.

Now the answer to the question. The cost can never go up, and each step is the reason.

  • The assign step gives each point the nearest centre. Its squared distance can only shrink or stay.
  • The update step moves each centre to the mean of its points. The mean is the one point with the smallest total squared distance to a set of points, the best constant of Models and loss worked in each coordinate. So no centre position does better for those points.

A cost that never rises, with only finitely many ways to split mm points into kk groups, has to stop changing. In the clip it falls from 1216.7 to 59.1 in six steps.

In probability and statistics · the mean as the best centre

Describing data in the statistics course compares the mean with the median. Under squared distance the mean is the best single summary, so it is the centre k-means uses.

Starts and the choice of k

The cost settles, but not always at the lowest cost there is. It stops at the first split that no single step can improve, and where that is depends on the start.

Two runs on the same 90 dots from different starting centres. The first finds the three clouds (total squared distance 59.1); the second splits one cloud in two and joins the other two (total 231.6). Both have stopped: each centre is the mean of its dots, and no dot is nearer another centre. Where k-means ends depends on where it starts.
Describe this picture

Two plots of the same 90 dots, coloured by group, with a cross at each centre. On the left, “the start below the dots”, the clip’s run: one group for each cloud, total 59.1. On the right, “another start”, from centres at (2,−1)(2,-1), (2.5,−1)(2.5,-1) and (−1,1)(-1,1): two groups of 15 share one cloud and one group of 60 covers the other two clouds, total 231.6. Both runs have stopped: each centre is the mean of its dots, and no dot is nearer another centre. There is no control.

So different starts can end on different groups: here at nearly four times the cost. Practical programs run k-means from several starts and keep the run with the lowest cost. A good way to start, called k-means++, picks the first centre at a random data point and each next one at a data point chosen at random, with points far from every centre so far more likely to be picked.

The number kk is a choice too, and the cost cannot make it:

The total squared distance of the same 90 dots for 1 to 90 groups (a logarithmic axis). It falls steeply up to 3 groups, 59.1 there, and slowly after, but it never stops falling: more groups always lower the cost, and at one group per dot it is zero. The lowest cost cannot choose k; real data rarely bend as clearly as these three clouds.
Describe this picture

A curve of the total squared distance of the clip’s 90 dots against the number of groups kk, from 1 to 90 on a logarithmic axis, each point the best of ten runs. It starts at 487.6 for one group, falls to 241.4 at k=2k=2 and steeply to 59.1 at k=3k=3, where the bend is marked, then slowly, to 49.3 at k=4k=4 and all the way down to 0 at k=90k=90, one group per dot. The caption says that more groups always lower the cost, that the lowest cost cannot choose kk, and that real data rarely bend as clearly as these three clouds. There is no control.

More centres never cost more: give one more centre a place on any point and the cost can only fall. With one centre per point, every point is its own centre and the cost is 0. So the lowest cost always picks the largest kk, and it means nothing. Here the bend at k=3k=3 stands out, because the data were made from three clouds. Real data rarely bend so clearly, and choosing kk often needs knowledge of what the groups are for.

Watch out

k-means does not find the number of groups. Its cost falls whenever kk rises, so a lower cost is no reason to choose a larger kk.

What it cannot find

Every point goes to its nearest centre, so the boundary between two clusters is the line of points equally far from both centres: a straight line at right angles to the segment between them, through its middle. k-means can only cut the plane with such straight lines, and it favours round groups of similar size.

k-means finds round groups, not curved ones. Colour shows the group k-means gives each dot, and the mark (round or square) the shape it was drawn from. With two groups the plane is always split by a straight line halfway between the two centres (dashed), so it cuts across the crescents, across two long bands, and through the edge of a big cloud beside a small one.
Describe this picture

Three plots, each run with two groups and split by a dashed straight line halfway between the two centres into two shaded halves, with the dots coloured by the group k-means gives them and a cross at each centre. On the left, “two crescents”, the 100 dots of Nearest neighbours with their labels hidden: the line cuts across both crescents, so each group holds dots of both: 16 of class A and 41 of class B in one group, 34 and 9 in the other. In the middle, “two long bands”, one above the other: an upright line cuts them into a left half and a right half. On the right, “a big cloud and a small one”: the small cloud’s group also takes the near edge of the big cloud. The caption begins “k-means finds round groups, not curved ones”. There is no control.

The same goes for long groups, which k-means cuts across rather than along, and for a small, tight group next to a large, spread-out one: the boundary runs midway between the two centres, so the small group’s centre takes the large group’s edge points. Gaussian mixtures allow stretched groups and groups of different sizes.

Worked example

Six points, (1,1)(1,1), (1,2)(1,2), (2,1)(2,1), (6,5)(6,5), (7,5)(7,5) and (6,6)(6,6), and k=2k=2, starting from a poor place: c1=(1,1)\mathbf{c}_1=(1,1) and c2=(2,1)\mathbf{c}_2=(2,1), both in the lower group.

Assign. (1,1)(1,1) and (1,2)(1,2) are nearest c1\mathbf{c}_1; (2,1)(2,1) sits on c2\mathbf{c}_2, and the three upper points are nearer c2\mathbf{c}_2 too. The squared distances to the chosen centres are 00, 11, 00, 42+42=324^2+4^2=32, 52+42=415^2+4^2=41 and 42+52=414^2+5^2=41: cost 115.

Update. c1\mathbf{c}_1 moves to the mean of (1,1)(1,1) and (1,2)(1,2), which is (1,1.5)(1,1.5). c2\mathbf{c}_2 moves to the mean of the other four, (21/4,17/4)=(5.25,4.25)(21/4,17/4)=(5.25,4.25). Cost 30.

Assign. (2,1)(2,1) is now nearer c1\mathbf{c}_1: squared distance 1+0.25=1.251+0.25=1.25, against 3.252+3.252=21.1253.25^2+3.25^2=21.125 to c2\mathbf{c}_2. It changes group. Cost 10.125.

Update. c1=(4/3,4/3)\mathbf{c}_1=(4/3,4/3), the mean of the lower three, and c2=(19/3,16/3)\mathbf{c}_2=(19/3,16/3), the mean of the upper three. Cost 24/9=2.66724/9=2.667.

Assign. No point changes group, so the run stops. The costs were 115→30→10.125→2.667115\to30\to10.125\to2.667.

Both centres in one place. Start both centres at the same point. Every point is then equally near both, so the tie rule gives all of them to c1\mathbf{c}_1, and c2\mathbf{c}_2 gets none. The update moves c1\mathbf{c}_1 to the mean of all the data while c2\mathbf{c}_2 keeps its place. Now the two differ, and the next assignment splits the data. On the clip’s 90 dots, with both centres starting at (0,0)(0,0), that second split is 59 and 31 dots.

Where you’ll meet this

Customers. Shops group customers by what they buy and how often, to see which kinds of customer they have.

Colour palettes. A photo’s pixels are points in a space of red, green and blue; k-means with k=16k=16 finds 16 colours, and each pixel is drawn in its centre’s colour.

Codebooks. Speech and image coders send the number of the nearest centre instead of the whole vector; the centres, the codebook, are often found by k-means.

Operating modes. A machine’s sensor logs fall into groups such as idle, running and starting up, found without anyone labelling the readings.

In signal processing · rounding a vector

Quantization in the signal processing course rounds a vector to the nearest point of a regular grid. A codebook found by k-means is a grid fitted to the data: its points sit where the vectors are, and each vector is rounded to its nearest centre.

Reference card

QuantityFormulaNotes
Assignr(i)r(i): the nearest centre cr\mathbf{c}_rties to the lower rr
Updatecr\mathbf{c}_r = mean of its pointsan empty cluster keeps its centre
Cost∑i=1m∥xi−cr(i)∥2\sum_{i=1}^{m}\lVert\mathbf{x}_i-\mathbf{c}_{r(i)}\rVert^2never rises
Stopan assignment changes nothingalways reached
Startthe answer depends on itseveral starts, keep the lowest cost
Choice of kkthe cost falls as kk rises0 at one centre per point
Boundariesstraight lines between centresround groups of similar size

Keep reading with a free account.

By creating an account you accept the terms of use.

Sign in

Already have an account? Use the service you signed up with.

Or keep reading: get new lessons by email

Are you 13 or over?

Accounts and email updates are for people aged 13 or over. We keep only your answer, never your date of birth.

End of the lesson

Where to go next.

Phasorium

Account

Sign inKeep your place on any device

Subjects

Site

Look