Supervised learning had labels to grade every prediction. Unsupervised learning begins by admitting it has none — and must therefore define what structure means before finding it. k-means makes the oldest, simplest definition: a cluster is a set of points that are close to a shared center. That single sentence, made mathematical, produces the most-used clustering algorithm in existence, a beautiful convergence argument, and — because the definition is so specific — a precise catalog of when the algorithm is the wrong tool.
The objective, and why it is hard
Given points and a target of clusters, k-means seeks centers and an assignment minimizing the within-cluster sum of squares (inertia):
Exact minimization is NP-hard even for — the assignment space is combinatorial. What is easy is optimizing each block of variables with the other held fixed, and that observation is the whole algorithm.
Lloyd’s algorithm = alternating minimization
- Assignment step (fix , minimize over ): each point picks its nearest center — separately per point, trivially optimal.
- Update step (fix , minimize over ): each center moves to the mean of its assigned points, because the mean is the minimizer of summed squared distance ( — the same two-line calculus as least squares).
Each step can only lower (or leave it fixed), , and there are finitely many assignments — so Lloyd’s algorithm must converge in finitely many steps. That is a genuine proof, and you can watch every clause of it hold:
Step through on the blobs: assignments flip, centroids glide, inertia drops, and after a handful of steps the assignments stop changing — converged, exactly as the proof promises. Now the fine print, live. Press Re-initialize repeatedly: convergence is only to a local optimum, and different starts land at different inertias (with random init and k=3 you will occasionally see two centroids split one blob while a third spans two — a classically bad local optimum k-means++ mostly avoids). Then switch to the two moons: watch a perfectly converged, perfectly wrong answer — the objective was minimized and the structure was still missed, because moons are not center-based structure. Convergence and correctness are different theorems, and k-means only comes with the first.
Initialization is half the algorithm
Because only the local optimum is guaranteed, where you start matters. k-means++ (Arthur & Vassilvitskii, 2007) seeds centers one at a time, choosing each new center with probability proportional to its squared distance from the nearest already-chosen center — spreading seeds across the data’s extent. The payoff is not just empirical: k-means++ guarantees expected inertia within of optimal, which random initialization cannot promise at all. In practice: k-means++ plus a few restarts (keep the lowest ) is the standard recipe, and it is what the widget’s default does.
Choosing k, honestly
The objective cannot choose for you — decreases monotonically in (more centers never hurt), hitting zero at . The working tools:
- Elbow heuristic: plot vs , look for the bend where returns diminish. Honest status: a heuristic, often ambiguous, frequently overruled by domain knowledge.
- Silhouette score: for each point, compare mean distance to its own cluster () vs the nearest other cluster (): . Averages near 1 mean tight, separated clusters; near 0 means the “clusters” are a partition of a continuum.
- The uncomfortable truth: k-means will happily carve a single Gaussian into pieces with a respectable-looking result. Clustering algorithms find structure only in the sense that they impose it; validation must come from outside the objective.
The assumptions in the objective
Squared Euclidean distance to a mean encodes three bets, each a failure mode when false: clusters are convex and roughly spherical (moons/rings break this — the widget shows it), similarly sized in radius (a big cluster bleeds into a small one’s territory, since boundaries are equidistant hyperplanes), and features are commensurately scaled (a feature in grams dominates one in kilograms 10⁶-fold — standardize first, the same lecture as regularization and PCA). And because the mean itself is not robust, single outliers drag centroids; k-medoids swaps in medians at higher cost. The next two lessons relax the geometry: mixtures make cluster shape learnable (k-means turns out to be a degenerate special case), and DBSCAN abandons centers entirely.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs, make_moons
X, _ = make_blobs(n_samples=300, centers=3, random_state=0)
km = KMeans(n_clusters=3, init="k-means++", n_init=10, random_state=0).fit(X)
print(km.inertia_) # the J this lesson defined
Xm, _ = make_moons(n_samples=300, noise=0.06, random_state=0)
km2 = KMeans(n_clusters=2, n_init=10, random_state=0).fit(Xm)
# converged fine; the assignment is still geometrically wrong — plot it
Exercises
Work these before the next lesson
- Prove the update step: show minimizes , and complete the finite-convergence argument for Lloyd’s algorithm. Why does the argument NOT show convergence to the global optimum?
Solution
Worked solutions are part of Premium — unlock all of them for £5/month →
- 5 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →
References
- S. Lloyd, “Least squares quantization in PCM”, 1957/1982 — the algorithm, born in signal processing.
- D. Arthur & S. Vassilvitskii, “k-means++: The Advantages of Careful Seeding”, SODA 2007.
- Hastie, Tibshirani & Friedman, The Elements of Statistical Learning, §14.3.