Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Group points around k centres
k-Means finds k centres and gives each data point to its nearest centre, choosing the centres so that points sit as close as possible to their own centre. Lloyd’s algorithm finds them by repeating two moves:
- Assign: each point joins its nearest centre.
- Update: each centre moves to the average of its points.
Repeat until no point changes group. Try it below, then click “new random start”: sometimes the algorithm settles on a worse answer and cannot get out.
k-Means is the default first look at unlabelled data: grouping flight-telemetry snapshots into operating regimes, compressing colours or sensor codebooks (vector quantisation), initialising mixture models, and building “visual words” for image features. It is fast, simple and scales to millions of points.
- 1. In the update step, a centre moves to…
- 2. Lloyd's algorithm stops when…
- 3. Different starting centres can lead to…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.Lloyd by hand
Data x = 1, 2, 3, 10, 11, 12 with k = 2 and starting centres 1 and 2.
- Assign: 1 goes to centre 1; everything else is closer to 2. Inertia = 0 + 0 + 1 + 64 + 81 + 100 = 246.
- Update: centre 1 stays at 1; centre 2 moves to (2 + 3 + 10 + 11 + 12)/5 = 7.6. Inertia 89.2.
- Assign: 2 and 3 are now closer to 1 than to 7.6. Inertia 41.68.
- Update: centres become 2 and 11. Inertia 4.
- Assign: nothing changes, so it has converged.
The objective (inertia, within-cluster sum of squares). It is the sum over all points of the squared distance to the assigned centre. For the four corners of a 2 × 2 square with a single centre, the centre is (1, 1) and the inertia is 4·2 = 8.
Cost. Each iteration computes n·k distances in d dimensions, O(nkd). For n = 10⁶, k = 100, d = 50 that is 5 × 10⁹ multiply-adds per iteration.
The steps in plain English:
- Pick k starting centres (for example, k random data points).
- Assign each point to its nearest centre.
- Move each centre to the mean of its points. If a centre has no points, keep it, or re-seed it.
- Repeat 2–3 until assignments stop changing. Run several random starts and keep the one with the lowest inertia.
- 1. Inertia of 0, 1, 5, 6 with centres 0.5 and 5.5?
- 2. Inertia of 0, 1, 5, 6 with one centre?
- 3. Cost of one Lloyd iteration?
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.Why it works and where it fails
Monotone decrease. The objective is
J(C, assignment) = Σᵢ ‖xᵢ − c₍ₐ₍ᵢ₎₎‖².
- With the centres fixed, sending each point to its nearest centre minimises J over assignments.
- With the assignments fixed, J splits into one sum per cluster. Each is minimised by the cluster mean, because Σ‖x − c‖² = Σ‖x − x̄‖² + m‖x̄ − c‖².
Each half-step therefore never increases J. There are finitely many partitions, so Lloyd stops after finitely many iterations at a local minimum (no single half-step improves it).
Local minima are common. Exercise 1: on 9 well-separated blobs, only 28% of 40 random starts reached the best inertia (474.8); the worst stopped at 3.14× that. The typical failure is two centres sharing one blob while one centre covers two blobs. Lloyd cannot fix it, because no single reassignment or mean shift helps.
Geometry. The assignments form a Voronoi partition: the boundaries are perpendicular bisectors between centres, so every cluster is convex. k-Means therefore assumes roughly spherical clusters of similar spread. It splits elongated clusters, merges nearby small ones, and cannot find rings or moons.
Practicalities.
- Scale features first. Distances mix units.
- Empty clusters can happen. Keep the old centre or re-seed it at the point farthest from its centre.
- k is an input. Choose it with the elbow plot, silhouette, gap statistic or domain knowledge.
- Outliers pull means. Consider k-medoids.
from sklearn.cluster import KMeans
km = KMeans(n_clusters=5, init="random", n_init=20, random_state=0).fit(X)
km.cluster_centers_, km.labels_, km.inertia_- 1. Why does the update step never increase inertia?
- 2. k-Means clusters are always…
- 3. Lloyd's algorithm is guaranteed to reach…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Hardness. Minimising the k-means objective exactly is NP-hard, even for k = 2 in general dimension (Aloise et al., 2009) or in the plane with general k (Mahajan et al., 2009). Lloyd is a heuristic, a coordinate descent on J.
Iterations. In practice Lloyd converges in a few dozen iterations. In the worst case it can need exponentially many (Vattani, 2011). Smoothed analysis shows polynomial expected time under small random perturbations (Arthur, Manthey and Röglin, 2011).
Probabilistic view. k-Means is the limit of EM for a Gaussian mixture with equal, spherical covariances σ²I and equal weights as σ → 0. The soft responsibilities become hard nearest-centre assignments. This explains the bias toward round, equally sized clusters.
Restarts. If a single start reaches the optimum with probability p, then n independent starts all miss with probability (1 − p)ⁿ. For 95% confidence you need n = ⌈log 0.05 / log(1 − p)⌉: 5 restarts for p = 0.5, 14 for p = 0.2, 29 for p = 0.1.
Interview questions.
- Why does k-means converge? Each step decreases a bounded objective, and there are finitely many partitions.
- What does k-means assume? Convex, roughly spherical clusters of similar variance and size, in a space where Euclidean distance is meaningful.
- How do you choose k? Elbow, silhouette, gap statistic, BIC of a GMM, stability across subsamples, or the downstream task.
- 1. Restarts for 95% confidence when p = 0.25?
- 2. k-Means is the small-variance limit of…
- 3. Exact k-means minimisation is…
Level 4: Expert
★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.How many restarts does k-means need?
History.
- Stuart Lloyd devised the algorithm at Bell Labs in 1957 for pulse-code modulation; it was published in 1982.
- E. W. Forgy (1965) published the same procedure.
- J. MacQueen (1967) coined “k-means” and gave the online version.
- H. Steinhaus (1956) had proposed the idea earlier.
Exercise 1.
- On 3 blobs, Lloyd took 5 iterations, lowering the inertia from 4212 to 525.2 and matching 99.7% of points to their true blob.
- On 9 blobs, 28% of 40 random starts reached the best inertia of 474.8.
Exercise 2. Blobs sat on a square grid (spacing 5, standard deviation 0.8, 30 points each). Each k had 200 random-init runs. The optimum is Lloyd started from the true centres. The ratio columns give expected best inertia divided by the optimum for 1, 5 and 20 restarts.
| k | single start hits optimum | restarts for 95% | ratio, 1 | ratio, 5 | ratio, 20 |
|---|---|---|---|---|---|
| 4 | 52.5% | 5 | 1.217 | 1.000 | 1.000 |
| 9 | 17.5% | 16 | 1.673 | 1.093 | 1.000 |
| 16 | 2.0% | 149 | 2.165 | 1.580 | 1.290 |
| 25 | 0.5% | 598 | 2.056 | 1.606 | 1.360 |
- Random initialisation degrades quickly with k. At k = 4 a handful of restarts suffices. At k = 16–25, even 20 restarts leave the expected best about 30% above the optimum, even though the blobs are perfectly separated.
- Restarts alone don’t scale. Better seeding (k-means++, next topic) attacks the cause: random starts often place several centres in one blob.
k-Means in AI, robotics and aerospace
- Vector quantisation: codebooks for compressing telemetry, images and speech features.
- Operating-regime discovery: clustering flight-data snapshots into phases (climb, cruise, descent) before fitting per-regime models.
- Visual vocabularies and anchors: bag-of-visual-words for place recognition, and anchor-box sizes for object detectors.
References
- S. P. Lloyd (1982). “Least squares quantization in PCM.” IEEE Transactions on Information Theory 28(2).
- J. MacQueen (1967). “Some methods for classification and analysis of multivariate observations.” Proc. 5th Berkeley Symposium.
- D. Aloise, A. Deshpande, P. Hansen, P. Popat (2009). “NP-hardness of Euclidean sum-of-squares clustering.” Machine Learning 75.
- A. Vattani (2011). “k-means requires exponentially many iterations even in the plane.” Discrete & Computational Geometry 45.
- A. K. Jain (2010). “Data clustering: 50 years beyond K-means.” Pattern Recognition Letters 31(8).