k-means
how it works
The idea in a few sentences and two pictures, then one grouping played step by step.
k-means puts points into k groups. A point such as 1 2 stands 1 across and 2 up; in a sentence it is written 1, 2. Distance is in a straight line: from 1, 2 to 2, 1 is 1 across and 1 down. By Pythagoras' rule from school geometry it is the root of 1 + 1, about 1.41. k-means starts k centres, then repeats two moves. Join: each point joins its nearest centre. Move: each centre moves to the middle of its points, their mean. When a round moves no centre, the groups are settled. Below, two clumps of four, and both centres start in the left clump. The left centre's first points are 1, 2 and 2, 1 and 2, 3. Across, 1 + 2 + 2 shared among 3 is about 1.67; up, 2 + 1 + 3 shared among 3 is 2. So it moves from 1, 2 to 1.67, 2, which is 0.67. The right centre moves 6.25, over to the other clump. After 3 rounds no centre moves. A point equally near two centres keeps its group if one of them is its own; otherwise it joins the centre listed first. Each round measures every point against every centre, so n points and k centres cost n times k distances a round.
With k = 3 and seed 4, it settles after 2 rounds, and the squared distances to the centres add to 24.5.
With scripts on, one slider sets k and another the seed. The plane, the chart and this line change with them.
step 1 of 37
8 points have no group yet. 2 centres start where you put them, each a cross in its own shape.
what it remembers to know where it is
- round
- not yet
- distance in hand
- not yet
- centres moved this round
- not yet
Where it says not yet, nothing is held there at that moment.
step 4 of 37
More than one centre is nearest this point, each 1.41 away. It joins the one typed first, the triangle centre.
what it remembers to know where it is
- round
- 1
- distance in hand
- 1.41
- centres moved this round
- not yet
Where it says not yet, nothing is held there at that moment.
step 12 of 37
The square centre moves 6.25 to the middle of its 5 points, at (7, 6.8).
what it remembers to know where it is
- round
- 1
- distance in hand
- 6.25
- centres moved this round
- 2
step 18 of 37
This point is now nearest the triangle centre, 1.33 away, so it leaves its old group for that one.
what it remembers to know where it is
- round
- 2
- distance in hand
- 1.33
- centres moved this round
- not yet
Where it says not yet, nothing is held there at that moment.
step 24 of 37
The square centre moves 1.56 to the middle of its 4 points, at (8, 8).
what it remembers to know where it is
- round
- 2
- distance in hand
- 1.56
- centres moved this round
- 2
step 35 of 37
The triangle centre is already at the middle of its points, so it stays.
what it remembers to know where it is
- round
- 3
- distance in hand
- 1
- centres moved this round
- 0
step 37 of 37
No centre moved, so no point will change group again. The groups are settled after 3 rounds.
what it remembers to know where it is
- round
- 3
- distance in hand
- not yet
- centres moved this round
- 0
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start k centresPython lines 13 and 14
- repeatPython line 15
- join each point to its nearest centrePython lines 16, 17, 18, 19 and 20
- move each centre to the middle of its pointsPython lines 21, 22, 23, 24, 25, 26 and 27
- until no centre movesPython lines 28 and 29
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
from math import lcm
def k_means(points, centres):
"""Each point's group: the number of the centre it ends with, from 0.
points and centres are (across, up) tuples. Each round joins every
point to its nearest centre, keeping its group on a tie, then moves
each centre to the middle of its points, until no centre moves. A
centre is kept as its points' across and up added, and how many, so
every distance is compared exactly, in whole numbers.
"""
sums = [(x, y, 1) for x, y in centres]
groups = [None] * len(points)
while True:
scale = lcm(*(n * n for _, _, n in sums)) # keeps each squared distance whole
for i, (x, y) in enumerate(points): # join each point
far = [((x * n - sx) ** 2 + (y * n - sy) ** 2) * (scale // (n * n)) for sx, sy, n in sums] # k distances
if groups[i] is None or far[groups[i]] > min(far):
groups[i] = far.index(min(far)) # the first of the nearest
moved = False
for c, (sx, sy, n) in enumerate(sums): # move each centre
held = [(x, y) for (x, y), g in zip(points, groups) if g == c]
if held: # a centre no point is nearest stays
ax, ay, m = sum(x for x, _ in held), sum(y for _, y in held), len(held)
moved = moved or ax * n != sx * m or ay * n != sy * m # a new middle
sums[c] = (ax, ay, m)
if not moved: # until no centre moves
return groups
how it scales
How the distances grow, from ten points to ten thousand.
Each step across or up is ten times the one before, a log-log plot. The rows line climbs one step up for each step across: ten times the points, ten times the distances, as 1 round of . The scattered points climb faster, since more points also take more rounds.
distances measured, ten times more at each mark up
, how many points there are, ten times more at each mark to the right
- points scattered at random, three of them picked as the starting centrespoints only, each measured by a real run, since no single formula for the distances measured of this row is worked out here
- three rows far apart, each centre started at its row's middlesolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
| distances measured | time | |
|---|---|---|
| 1,000 | 3,000 | about 3 microseconds |
| 100,000 | 300,000 | about 300 microseconds |
| 10,000,000 | 30,000,000 | about 30 milliseconds |
The distances measured are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count k-means' distances yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each n it scatters n points over a
square of whole-numbered spots, starts 3 centres on 3 of them, and prints
how many distances the method measures until no centre moves, the mean of
20 scatterings, up to n = 500, in about a second. The scatterings are this
script's own, so its means are near the plot's, not the same; its
cheapest(n), three rows far apart, gives exactly the plot's cheapest counts
on any computer.
"""
import random
from math import lcm
def k_means(points, centres):
"""Each point's group: the number of the centre it ends with, from 0.
points and centres are (across, up) tuples. Each round joins every
point to its nearest centre, keeping its group on a tie, then moves
each centre to the middle of its points, until no centre moves. A
centre is kept as its points' across and up added, and how many, so
every distance is compared exactly, in whole numbers.
"""
sums = [(x, y, 1) for x, y in centres]
groups = [None] * len(points)
while True:
scale = lcm(*(n * n for _, _, n in sums)) # keeps each squared distance whole
for i, (x, y) in enumerate(points): # join each point
far = [((x * n - sx) ** 2 + (y * n - sy) ** 2) * (scale // (n * n)) for sx, sy, n in sums] # k distances
if groups[i] is None or far[groups[i]] > min(far):
groups[i] = far.index(min(far)) # the first of the nearest
moved = False
for c, (sx, sy, n) in enumerate(sums): # move each centre
held = [(x, y) for (x, y), g in zip(points, groups) if g == c]
if held: # a centre no point is nearest stays
ax, ay, m = sum(x for x, _ in held), sum(y for _, y in held), len(held)
moved = moved or ax * n != sx * m or ay * n != sy * m # a new middle
sums[c] = (ax, ay, m)
if not moved: # until no centre moves
return groups
def count(points, centres):
"""The same method on points, counting each distance it measures.
Each centre is kept as the sum of its points and how many, whole
numbers, so it runs fast and still finds every tie exactly.
"""
sums = [(x, y, 1) for x, y in centres]
groups = [None] * len(points)
distances = 0
while True:
for i, (x, y) in enumerate(points):
# Distance squared times the count squared, compared across centres as whole numbers.
far = [((x * n - sx) ** 2 + (y * n - sy) ** 2, n * n) for sx, sy, n in sums]
distances += len(sums) # one distance to each centre
best = 0 if groups[i] is None else groups[i]
for c, (d, n2) in enumerate(far):
if d * far[best][1] < far[best][0] * n2:
best = c
groups[i] = best
moved = False
for c in range(len(sums)):
held = [(x, y) for (x, y), g in zip(points, groups) if g == c]
if held:
sx, sy, n = sum(x for x, _ in held), sum(y for _, y in held), len(held)
old = sums[c]
moved = moved or sx * old[2] != old[0] * n or sy * old[2] != old[1] * n
sums[c] = (sx, sy, n)
if not moved:
return distances
def cheapest(n):
"""n points in three rows far apart, each centre at its row's middle."""
gap = 5 if n <= 12 else n
lengths = [(n - r + 2) // 3 for r in range(3)]
middle = (lengths[0] + 1) // 2
def offset(j, m): # odd m: middle and steps either side; even m: the middle left empty
if m % 2 == 1:
return j - (m - 1) // 2
return j - m // 2 if j < m // 2 else j - m // 2 + 1
points = [(middle + offset(i // 3, lengths[i % 3]), (i % 3) * gap) for i in range(n)]
return points, [(middle, r * gap) for r in range(3)]
def scatter(n, seed):
"""n points on distinct spots, and 3 of them as the starting centres."""
rng = random.Random(seed)
side = max(10, int((2 * n) ** 0.5) + 1)
spots = rng.sample(range((side + 1) ** 2), n)
points = [(s % (side + 1), s // (side + 1)) for s in spots]
return points, points[:3]
if __name__ == "__main__":
print(f"{'n':>6} {'cheapest':>9} {'scattered, mean of 20':>22}")
for n in (10, 20, 50, 100, 200, 500):
mean = sum(count(*scatter(n, seed)) for seed in range(20)) / 20
print(f"{n:>6} {count(*cheapest(n)):>9} {mean:>22.0f}")
best, worst and average
The rows settle in 1 round, the fewest any run can take. Scattered points take a number of rounds no formula gives, so that column is measured.
A case is one kind of input, the thing the method is given, such as a set of points and where its centres start. A bound says how fast that case's cost grows as more points come in.
The rows' count is in the grid: 1 round of 3 distances for each point, 3n, so all three bounds grow as n.
| bestthree rows far apart, each centre started at its row's middle | averagepoints scattered at random, three of them picked as the starting centres | |
|---|---|---|
| distances measured | measured; at least , and at most | |
| how the distances measured grow in each case | ||
| tight, | not worked out here: the floor and the ceiling grow differently, so no is found | |
| ceiling, | ||
| floor, | ||
extra memory: the k centres and each point's group
Extra memory is the room it needs on top of the input itself, while it runs.
| points | distances, rows | rounds, rows | distances, scattered | rounds, scattered |
|---|---|---|---|---|
| 10 | 30 | 1 | 82.5 | 2.75 |
| 100 | 300 | 1 | 2,385 | 7.95 |
| 1,000 | 3,000 | 1 | 50,400 | 16.8 |
| 10,000 | 30,000 | 1 | 1,077,000 | 35.9 |
where the formula comes from
The counts above, worked out in small steps, each naming the line it comes from.
the move: one round, and nothing moves
the line:Six points in three rows, each centre started at its row's middle, 1 across. Round 1 moves no centre. why it is allowed: Each centre starts level with its row. Another row's centre is just as far across and farther up or down, so every point's nearest centre is its own row's. Each row is spread evenly about its centre, so its middle is where the centre already stands. If n is under 3, a row may have no points; that centre stays where it is. No centre moves, and the method stops.
the move: count the one round
the line:why it is allowed: is the distances measured. By line 1 there is one round, and it measures each of the points against each of the 3 centres. For the six points, 18.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2, is , so it is at most .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 3, is at most 3 times .
guess it, thenthe move: a floor
the line:why it is allowed: By line 2, is at least too.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, never drops below 3 times .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: one round's distances
the line:why it is allowed: Each of the points is measured against each of the 3 centres, once a round.
the move: a join never raises the total
the line:why it is allowed: The total squared distance adds each point's squared distance to its own centre. A point changes group only for a centre strictly nearer, so its part of the total falls. On a tie it stays, and the total stays.
guess it, thenthe move: a move never raises the total
the line:number minus 5 squared middle part minus 6, squared 1 -4 16 8 25 4 -1 1 2 4 4 -1 1 2 4 7 2 4 -4 1 9 4 16 -8 9 total 0 38 0 43 1, 4, 4, 7 and 9, each number minus their mean, 5, and minus 6. Each last square is the first square, plus the middle part, plus 1. The middle parts add to 0, so the squares to 6 add to 38 plus 5, 43. why it is allowed: Take 1, 4, 4, 7 and 9. Their mean is 5. Compare their squares to 5 with their squares to 6. Each number minus 6 is the number minus 5, less 1. Squared, that is the square of the number minus 5, a middle part, 2 times the number minus 5 times minus 1, and 1. The numbers minus 5 add to 0, the overs equal the lacks as the average and spread page shows, so the middle parts add to 0. That leaves 38 plus 5 ones, 43. At 6, 1 from the mean, the total grew by 5 ones. At a spot d from the mean it grows by 5 lots of d times d, never below 0. So the mean is the lowest spot, and a centre moved there never raises the total. Across and up each add the same way.
guess it, thenthe move: no grouping comes back
the line:round total after it 1 55.47 2 8 3 8 Section 1's two clumps. The total falls from 55.47 after round 1 to 8 after round 2. Round 3 changes no group, keeps the total and is the last. why it is allowed: Round 1 has no grouping before it. After it, a round that changes no group moves no centre, and is the last. Any other round changes a group, so by lines 2 and 3 it ends on a lower total than the round before, and so lower than every round before it. A grouping fixes the total: each centre with points stands at their mean, and a centre with no points adds nothing. So no grouping can come back.
guess it, thenthe move: count the groupings
the line:why it is allowed: Let be how many groupings there are. Each of the points picks one of 3 groups, 3 times 3 and so on, times. For 2 points, 9; for 3 points, 27.
guess it, thenthe move: a ceiling on the rounds
the line:why it is allowed: By line 4 the rounds before the last each end on a grouping not seen before, at most of them by line 5, then comes the last round. This is only a ceiling: for 3 points it allows 28 rounds, yet a real run on 3 points, a centre on each, takes 1.
guess it, thenthe move: at most double
the line:why it is allowed: is at least 1, so adding 1 to it at most doubles it.
guess it, thenthe move: multiply
the line:why it is allowed: By lines 1 and 7, at most rounds of distances each.
guess it, thenthe move: multiply the numbers
the line:why it is allowed: 3 times 2 is 6.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 9, is at most 6 times .
guess it, thenthe move: at least one round
the line:why it is allowed: Every run plays at least one round, distances by line 1.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11, never drops below 3 times .
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
count it yourself
Count every step on the six points in three rows. A point such as 2 5 stands 2 across and 5 up. After the semicolon come the three centres, each at its row's middle. Then check the distances against the formula.
| step | what happens | distances measured | rounds |
|---|---|---|---|
| 1 | 6 points have no group yet. 3 centres start where you put them, each a cross in its own shape. | 0 | 0 |
| 2 | Round 1: every point looks for its nearest centre. | 0 | 1 |
| 3 | This point is nearest the triangle centre, 1 away, so it joins that group. | 3 | 1 |
| 4 | This point is nearest the square centre, 1 away, so it joins that group. | 6 | 1 |
| 5 | This point is nearest the circle centre, 1 away, so it joins that group. | 9 | 1 |
| 6 | This point is nearest the triangle centre, 1 away, so it joins that group. | 12 | 1 |
| 7 | This point is nearest the square centre, 1 away, so it joins that group. | 15 | 1 |
| 8 | This point is nearest the circle centre, 1 away, so it joins that group. | 18 | 1 |
| 9 | The triangle centre is already at the middle of its points, so it stays. | 18 | 1 |
| 10 | The square centre is already at the middle of its points, so it stays. | 18 | 1 |
| 11 | The circle centre is already at the middle of its points, so it stays. | 18 | 1 |
| 12 | No centre moved, so no point will change group again. The groups are settled after 1 round. | 18 | 1 |
In all, 18 distances measured. The formula from section 4, , gives at : the same.
where you meet it
An old method that toolkits still offer, often as a first way to group points.
scikit-learn, a Python library for machine learning
Its KMeans tool asks for the number of groups. By default it starts the centres spread apart, each next one more likely far from those already chosen. It can also run from several starts and keep the smallest total.
source: scikit-learn's documentation, the user guide's section on clustering and the KMeans reference
where it comes from
Hugo Steinhaus wrote of the idea in 1956. Stuart Lloyd described the join and move rounds in a 1957 Bell Labs note on sending signals with few levels, printed in 1982. James MacQueen gave the name k-means in a 1967 paper.
source: Steinhaus, Sur la division des corps matériels en parties, Bulletin de l'Académie Polonaise des Sciences, 1956. Lloyd, Least Squares Quantization in PCM, IEEE Transactions on Information Theory, 1982. MacQueen, Some Methods for Classification and Analysis of Multivariate Observations, Fifth Berkeley Symposium on Mathematical Statistics and Probability, 1967.
what is used instead
That spread-apart start is called k-means++ (Arthur and Vassilvitskii, 2007); it often finds a lower total in fewer rounds. When the groups are not round blobs, such as a ring round a clump, a method that joins points by how crowded their neighbourhood is suits better.
how it compares
k-means beside itself from another start. The same four points, two groupings.