Skip to content

k-means

learning

Level 2 of 3

Also called Lloyd's algorithm and k-means clustering.

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.

02468100246810
Two clumps of four, both centres started in the left clump, at 1, 2 and 3, 2. After 3 rounds the right centre stands at 8, 8 in the middle of the right clump, and the left one at 2, 2.
02468100246810
050100150123ktotaltotal squared distance

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.

Three clumps of four. At k = 3, seed 5 starts two centres in the top clump and settles at a total of 81.38, a worse grouping than seed 4's 24.5. In seed 4's chart the total falls from 177.33 at 1 group to 85.13 at 2 and 24.5 at 3, where each clump has its own centre.
Two clumps, both centres in one: 7 moments of its 37 steps, the steps between them left for the watch page
  1. step 1 of 37

    02468100246810

    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.

    watch from here

  2. step 4 of 37

    024681002468101.411.41

    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.

    watch from here

  3. step 12 of 37

    024681002468106.25

    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

    watch from here

  4. step 18 of 37

    024681002468101.336.25

    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.

    watch from here

  5. step 24 of 37

    024681002468101.56

    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

    watch from here

  6. step 35 of 37

    02468100246810

    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

    watch from here

  7. step 37 of 37

    02468100246810

    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.

    watch from here

the steps, in plain words
  1. start k centresPython lines 13 and 14
  2. repeatPython line 15
  3. join each point to its nearest centrePython lines 16, 17, 18, 19 and 20
  4. move each centre to the middle of its pointsPython lines 21, 22, 23, 24, 25, 26 and 27
  5. 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 3n3n. The scattered points climb faster, since more points also take more rounds.

distances measured, ten times more at each mark up

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

nn, 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
what three rows cost, at a billion distances measured a second
nndistances measuredtime
1,0003,000about 3 microseconds
100,000300,000about 300 microseconds
10,000,00030,000,000about 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestthree rows far apart, each centre started at its row's middleaveragepoints scattered at random, three of them picked as the starting centres
distances measured3n3nmeasured; at least 3n3n, and at most 6n×3n6n \times 3^n
how the distances measured grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)not worked out here: the floor and the ceiling grow differently, so no Θ\Theta is found
ceiling, OOO(n)O(n)O(n×3n)O(n \times 3^n)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n)\Omega(n)

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.

pointsdistances, rowsrounds, rowsdistances, scatteredrounds, scattered
1030182.52.75
10030012,3857.95
1,0003,000150,40016.8
10,00030,00011,077,00035.9
The rows always take 1 round. For scattered points each number is the mean of 20 runs, so it can have a decimal part, such as 2.75 rounds. The distances are the rounds times 3n, and for 10 points 3n is 30, so 2.75 times 30 is 82.5. They take more rounds as they grow.

where the formula comes from

The counts above, worked out in small steps, each naming the line it comes from.

Question 1: nn points in three rows far apart, one above another, each spread evenly about the same middle across, and each centre started at its row's middle. How many distances, DD?
  1. the move: one round, and nothing moves

    the line:
    round 1: each point joinsits own row’s centre,and no centre moves\begin{gathered} \text{round 1: each point joins} \\ \text{its own row's centre,} \\ \text{and no centre moves} \end{gathered}
    02468100246810
    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.

  2. the move: count the one round

    the line:
    D=3nD = 3n

    why it is allowed: DD is the distances measured. By line 1 there is one round, and it measures each of the nn points against each of the 3 centres. For the six points, 18.

  3. the move: a ceiling

    the line:
    D≤3nD \le 3n

    why it is allowed: By line 2, DD is 3n3n, so it is at most 3n3n.

  4. the move: read it as a bound

    the line:
    D∈O(n)D \in O(n)

    why it is allowed: By line 3, DD is at most 3 times nn.

  5. the move: a floor

    the line:
    D≥3nD \ge 3n

    why it is allowed: By line 2, DD is at least 3n3n too.

  6. the move: read it as a bound

    the line:
    D∈Ω(n)D \in \Omega(n)

    why it is allowed: By line 5, DD never drops below 3 times nn.

  7. the move: ceiling and floor together

    the line:
    D∈Θ(n)D \in \Theta(n)

    why it is allowed: Lines 4 and 6 bound DD by the same growth, nn.

try it with a small nn: at n=6n = 6, line 2 gives D=18D = 18, which you can work out by hand

Question 2: why does k-means always stop, and between what floor and ceiling do its distances, DD, lie on nn scattered points with 3 centres?
  1. the move: one round's distances

    the line:
    each round measures3n distances\begin{gathered} \text{each round measures} \\ 3n \text{ distances} \end{gathered}

    why it is allowed: Each of the nn points is measured against each of the 3 centres, once a round.

  2. the move: a join never raises the total

    the line:
    a point that changes grouplowers the total\begin{gathered} \text{a point that changes group} \\ \text{lowers the total} \end{gathered}

    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.

  3. the move: a move never raises the total

    the line:
    a centre moved to itsmean never raises it\begin{gathered} \text{a centre moved to its} \\ \text{mean never raises it} \end{gathered}
    numberminus 5squaredmiddle partminus 6, squared
    1-416825
    4-1124
    4-1124
    724-41
    9416-89
    total038043
    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.

  4. the move: no grouping comes back

    the line:
    every round before thelast ends on a groupingnot seen before\begin{gathered} \text{every round before the} \\ \text{last ends on a grouping} \\ \text{not seen before} \end{gathered}
    roundtotal after it
    155.47
    28
    38
    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.

  5. the move: count the groupings

    the line:
    G=3nG = 3^n

    why it is allowed: Let GG be how many groupings there are. Each of the nn points picks one of 3 groups, 3 times 3 and so on, nn times. For 2 points, 9; for 3 points, 27.

  6. the move: a ceiling on the rounds

    the line:
    at most 3n+1rounds\begin{gathered} \text{at most } 3^n + 1 \\ \text{rounds} \end{gathered}

    why it is allowed: By line 4 the rounds before the last each end on a grouping not seen before, at most GG 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.

  7. the move: at most double

    the line:
    at most 2×3nrounds\begin{gathered} \text{at most } 2 \times 3^n \\ \text{rounds} \end{gathered}

    why it is allowed: 3n3^n is at least 1, so adding 1 to it at most doubles it.

  8. the move: multiply

    the line:
    D is at most3n×2×3n\begin{gathered} D \text{ is at most} \\ 3n \times 2 \times 3^n \end{gathered}

    why it is allowed: By lines 1 and 7, at most 2×3n2 \times 3^n rounds of 3n3n distances each.

  9. the move: multiply the numbers

    the line:
    D is at most6n×3n\begin{gathered} D \text{ is at most} \\ 6n \times 3^n \end{gathered}

    why it is allowed: 3 times 2 is 6.

  10. the move: read the bound

    the line:
    a ceiling ofO(n×3n)\begin{gathered} \text{a ceiling of} \\ O(n \times 3^n) \end{gathered}

    why it is allowed: By line 9, DD is at most 6 times n×3nn \times 3^n.

  11. the move: at least one round

    the line:
    D is at least 3n\begin{gathered} D \text{ is at least } 3n \end{gathered}

    why it is allowed: Every run plays at least one round, 3n3n distances by line 1.

  12. the move: read it as a bound

    the line:
    a floor of Ω(n)\begin{gathered} \text{a floor of } \Omega(n) \end{gathered}

    why it is allowed: By line 11, DD never drops below 3 times nn.

try it with a small nn: at n=3n = 3, line 5 gives G=27G = 27, 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.

0 0, 0 5, 0 10, 2 0, 2 5, 2 10; 1 0, 1 5, 1 10, every step written down
stepwhat happensdistances measuredrounds
16 points have no group yet. 3 centres start where you put them, each a cross in its own shape.00
2Round 1: every point looks for its nearest centre.01
3This point is nearest the triangle centre, 1 away, so it joins that group.31
4This point is nearest the square centre, 1 away, so it joins that group.61
5This point is nearest the circle centre, 1 away, so it joins that group.91
6This point is nearest the triangle centre, 1 away, so it joins that group.121
7This point is nearest the square centre, 1 away, so it joins that group.151
8This point is nearest the circle centre, 1 away, so it joins that group.181
9The triangle centre is already at the middle of its points, so it stays.181
10The square centre is already at the middle of its points, so it stays.181
11The circle centre is already at the middle of its points, so it stays.181
12No centre moved, so no point will change group again. The groups are settled after 1 round.181

In all, 18 distances measured. The formula from section 4, 3n3n, gives D=18D = 18 at n=6n = 6: 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.

02468100246810
Started at 5, 3 and 5, 7, the centres are already their groups' middles, so it stops after 1 round, top against bottom. The total is 64.
02468100246810
The same points started at 2, 5 and 8, 5 settle left against right after 2 rounds. The total is 16, a better grouping.

race them on one row of your own