Search

Search papers and lessons

K-Means Clustering

Level 2 · 8 min read

K-means splits unlabelled points into k groups by alternating two steps: assign each point to its nearest centre, then move each centre to the mean of its points. Each step lowers the total squared distance.

On this page

  • Colour = topic mix
  • Probability
  • Linear algebra
  • Learning basics
  • Discrete math
  • Sign in to see your progress

TL;DR

K-means groups unlabelled data into kk 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 x1,…,xN∈Rd\mathbf{x}_1, \dots, \mathbf{x}_N \in \mathbb{R}^d. We want kk centres μ1,…,μk\boldsymbol{\mu}_1, \dots, \boldsymbol{\mu}_k and an assignment ci∈{1,…,k}c_i \in \{1, \dots, k\} for each point, the index of the centre that point ii belongs to.

Definition: K-means objective

Minimise the within-cluster sum of squares

J(c,μ)=∑i=1N∥xi−μci∥2,J(c, \boldsymbol{\mu}) = \sum_{i=1}^{N} \left\lVert \mathbf{x}_i - \boldsymbol{\mu}_{c_i} \right\rVert^2,

where ∥⋅∥\lVert \cdot \rVert is the Euclidean norm and μci\boldsymbol{\mu}_{c_i} is the centre assigned to point ii. Minimising JJ 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:

  1. Assignment step. With the centres fixed, set each cic_i to the index of the nearest centre: ci=arg⁡min⁡j∥xi−μj∥2c_i = \arg\min_j \lVert \mathbf{x}_i - \boldsymbol{\mu}_j \rVert^2.
  2. Update step. With the assignments fixed, set each centre to the mean of its cluster Cj={i:ci=j}C_j = \{ i : c_i = j \}:
μj=1∣Cj∣∑i∈Cjxi.\boldsymbol{\mu}_j = \frac{1}{|C_j|} \sum_{i \in C_j} \mathbf{x}_i.

Why the update is the mean

Take one cluster CC and fix its points. The function f(μ)=∑i∈C∥xi−μ∥2f(\boldsymbol{\mu}) = \sum_{i \in C} \lVert \mathbf{x}_i - \boldsymbol{\mu} \rVert^2 is a sum of squares, so it is smooth and has one minimum. Setting its gradient to zero gives

∇f(μ)=−2∑i∈C(xi−μ)=0⟹μ=1∣C∣∑i∈Cxi.\nabla f(\boldsymbol{\mu}) = -2 \sum_{i \in C} (\mathbf{x}_i - \boldsymbol{\mu}) = \mathbf{0} \quad \Longrightarrow \quad \boldsymbol{\mu} = \frac{1}{|C|} \sum_{i \in C} \mathbf{x}_i.

So the mean is the best single centre for its cluster.

Why the procedure converges

Each step can only lower JJ, or leave it the same. The assignment step picks, for each point, the nearest centre, which is the smallest term in its sum, so JJ 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 JJ does not rise either. There are only finitely many ways to partition NN points into kk clusters, and JJ never increases, so the procedure must stop. It stops at a point where neither step changes anything: a local minimum of JJ, which may not be the global one.

Worked examples

Example
Four points, two clusters

Take the one-dimensional points 0,4,6,100, 4, 6, 10 and k=2k = 2. Start with centres μ1=0\mu_1 = 0 and μ2=10\mu_2 = 10.

  1. Assign. Point 0 is nearest to μ1\mu_1. Point 4 is at distance 4 from μ1\mu_1 and 6 from μ2\mu_2, so it goes to cluster 1. Point 6 is at distance 6 from μ1\mu_1 and 4 from μ2\mu_2, so it goes to cluster 2. Point 10 goes to cluster 2. Clusters: {0,4}\{0, 4\} and {6,10}\{6, 10\}.
  2. Update. μ1=(0+4)/2=2\mu_1 = (0 + 4)/2 = 2 and μ2=(6+10)/2=8\mu_2 = (6 + 10)/2 = 8.
  3. Assign again. Point 0 is at distance 2 from μ1\mu_1 and 8 from μ2\mu_2, 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.
  4. Stop. The objective is J=(0−2)2+(4−2)2+(6−8)2+(10−8)2=4+4+4+4=16J = (0-2)^2 + (4-2)^2 + (6-8)^2 + (10-8)^2 = 4 + 4 + 4 + 4 = 16.

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.

Example
Choosing k with the elbow

Use the points 1,2,9,101, 2, 9, 10 and compare k=1k = 1, 22 and 33. The best solution for each kk gives its smallest JJ.

  1. k=1k = 1. One centre at the mean 5.55.5. The squared distances are 4.52+3.52+3.52+4.52=20.25+12.25+12.25+20.25=654.5^2 + 3.5^2 + 3.5^2 + 4.5^2 = 20.25 + 12.25 + 12.25 + 20.25 = 65.
  2. k=2k = 2. The clusters {1,2}\{1, 2\} and {9,10}\{9, 10\} have means 1.51.5 and 9.59.5. Each point is at distance 0.50.5 from its mean, so J=4×0.25=1.0J = 4 \times 0.25 = 1.0.
  3. k=3k = 3. The clusters {1,2}\{1, 2\}, {9}\{9\} and {10}\{10\} have means 1.51.5, 99 and 1010. J=0.25+0.25=0.5J = 0.25 + 0.25 = 0.5.

Interpretation: going from k=1k = 1 to k=2k = 2 removes almost all the error, from 65 to 1. Going from 22 to 33 removes only half of what remains. The curve of JJ against kk bends at k=2k = 2, which is the usual "elbow" used to pick kk. 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 NkdN k d operations. It also has known weaknesses.

SituationProblemBetter choice
Starting centres are randomDifferent starts give different local optimaRun several times and keep the lowest JJ, or use k-means++ seeding
Clusters are long, thin or curvedSquared distance cuts them along the wrong lines[[mixture-model
Features have very different unitsThe feature with the largest numbers dominates the distancesStandardise the features first
Outliers are presentA single far point pulls its centre toward itRemove or clip outliers, or use a robust variant
You need soft membership or a probability per clusterEach point gets one hard labelA mixture model fitted by expectation-maximisation
You do not know kkThe objective always falls as kk growsUse 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 JJ 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 0,4,6,100, 4, 6, 10. Start with centres μ1=0\mu_1 = 0 and μ2=10\mu_2 = 10 and run one full iteration. What are the clusters, the new centres and the objective?Show answer

Assignment: {0,4}\{0, 4\} goes to cluster 1 and {6,10}\{6, 10\} to cluster 2, since 4 is closer to 0 than to 10 and 6 is closer to 10 than to 0. Update: μ1=2\mu_1 = 2 and μ2=8\mu_2 = 8. Objective: (0−2)2+(4−2)2+(6−8)2+(10−8)2=16(0-2)^2 + (4-2)^2 + (6-8)^2 + (10-8)^2 = 16. 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 μ\boldsymbol{\mu} is a smooth function of μ\boldsymbol{\mu} with one minimum. Its gradient is −2∑(xi−μ)-2 \sum (\mathbf{x}_i - \boldsymbol{\mu}), which is zero exactly when μ\boldsymbol{\mu} 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 10810^8 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