K-means clustering
K-means clustering computed live in your browser, one action per step: k-means++ seeding, assignment, centroid update. Voronoi cells, 3D views, elbow, silhouette, 100,000 points on the GPU.
Updated
- Lloyd's algorithm
- k-means++ seeding
- Inertia and convergence
- Choosing k: elbow and silhouette
- When k-means fails
Intuition
Two alternating steps
No labels, just a cloud of points to split into groups. K-means is disarmingly simple: drop centres anywhere, then repeat two things — every point joins its nearest centre (assignment), and every centre moves to the middle of its points (update). When a centre moves, some points find another centre closer and switch; then the centres move again… until no point switches.
The three small labs below compute it step by step in your browser. The background shows which centroid is nearest (the Voronoi diagram), the large white-centred dots are the centroids, and the thin lines are their paths.
First: k-means++ picks the 5 centroids one per step (the first 5 steps), then assignment and update alternate; by step 10 no point switches, the five clusters are separated exactly, and the inertia is about 349.1.
Second: the same data split into 4 groups. Two clusters must merge, and the inertia rises to about 773.5. K-means never tells you is wrong — it only minimises the inertia for the you give it.
Third: two curved crescents. K-means' boundaries are always straight lines (the perpendicular bisector between two centroids), so it can only slice across both crescents; it agrees with the true grouping on just 71.4% of points.
Math
The objective: inertia
points , centroids , and a group for each point. K-means minimises
Lloyd's algorithm
Each step on its own cannot increase : assignment is optimal for fixed centroids, and for fixed groups the point minimising a sum of squared distances is the mean. Since and there are finitely many ways to group the points, it stops after finitely many steps (here by scikit-learn's strict criterion: an assignment that changes no label).
On the default data () the first assignment gives all 500 points a group; after that each assignment moves 7, 3, 2… points, quickly reaching zero.
Initialisation: k-means++
Arbitrary initial centroids can be terrible. k-means++ picks the first centroid uniformly at random; after that, each point is chosen with probability proportional to — its smallest squared distance to the centroids chosen so far. Points far from the existing centroids are likely picks, so the centroids start out spread. It comes with an expected approximation guarantee.
Local optima and restarts
Lloyd's algorithm only guarantees a local optimum. With and ten restarts on the same data, random initialisation reaches 349.1 six times and gets stuck at 747, 749, 757 or even 1471 (one centroid holding two clusters with another wedged between); k-means++ reaches 349.1 seven times. In practice you restart several times and keep the lowest inertia (scikit-learn's n_init).
Choosing
The inertia only falls as grows (it is 0 when ), so it cannot be compared directly. Two common approaches:
- Elbow method: plot inertia against and look for the point where the decrease suddenly flattens.
- Silhouette coefficient: for each point, is its mean distance to the other points of its cluster and its mean distance to the nearest other cluster; , averaged over all points. Closer to 1 means cleaner clusters.
| Inertia | Silhouette | |
|---|---|---|
| 3 | 1522 | 0.546 |
| 4 | 773 | 0.605 |
| 5 | 349 | 0.674 |
| 6 | 323 | 0.589 |
| 7 | 297 | 0.523 |
(Each in the table is the best of 3 restarts, which is why shows 323 rather than a single run's 328.9.)
From 4 to 5 the inertia more than halves; each further cluster saves only twenty-odd. The silhouette peaks at 5. Both point to 5 — exactly the number of clusters the data were generated with.
How it is computed, with real numbers
Once the lab above has loaded, this panel works through the same formulas with its current numbers.
Experiment
Follow the lesson
Course
Lesson 1: assignment, update and choosing k
5 steps · each one: set up and run → look → answer
1. Picking initial centroids
k = 5, just 5 steps. Watch the centroids being picked one at a time.
2. Assignment and update
Continue to step 10. Watch the centroid paths and the inertia curve.
3. Too small a k
Default k = 4.
4. Elbow and silhouette
Look at the "Choosing k" chart on the right.
5. Local optima
Random initialisation with 10 restarts. Look at each run's inertia.
Try these settings
With the unequal clusters and , K-means agrees with the true grouping on 98.8% of points: it prefers clusters of similar size, and points at the edge of a big cluster are sometimes claimed by a small cluster's centroid.
Exercises
Exercises
Exercise 1: find the real number of clusters
Change only k so that the converged inertia lies between 340 and 360.
Hint
k = 5: 349.1. k = 6 gives 328.9, already below 340 — inertia keeps falling with k, so the answer is not "the lowest".
- Inertia J ≤ 360
- Inertia J ≥ 340
Exercise 2: rescue random initialisation with restarts
With k = 4 and random initialisation a single run only reaches 783.96. Without changing the initialisation, get the best run to 774 or below.
Hint
Two restarts are enough: the second reaches 773.53. Try a few more and the third falls into a 1491.65 pit.
- Best inertia ≤ 774
Quiz
Further reading
Frequently asked questions
Does K-means always converge?
Yes. Neither assignment nor update can increase the inertia, and there are finitely many groupings, so it stops after finitely many steps. Where it stops is only a local optimum that depends on the initial centroids.
What is k-means++, and why is it better than random initialisation?
A way to choose initial centroids: each new centroid is drawn with probability proportional to its squared distance to the nearest centroid chosen so far, so the initial centroids spread out. It has an O(log k) approximation guarantee in expectation and usually converges faster to better results. It is scikit-learn's default.
How do I choose k for K-means?
Combine domain knowledge with the elbow method (where the inertia curve bends) and the silhouette coefficient (closer to 1 is better). On this page's five clusters both point to k = 5. The gap statistic, or information criteria for Gaussian mixtures, are alternatives.
What are the limitations of K-means?
It assumes convex clusters of similar size and density, is sensitive to outliers (they drag the means), needs k in advance, and is tied to Euclidean distance. Use DBSCAN or spectral clustering for crescents or rings, and Gaussian mixture models when you need soft assignments (a probability for each cluster).
What is the difference between K-means and KNN?
The names are similar but the methods are unrelated. K-means is unsupervised clustering and k is the number of clusters; KNN (k-nearest neighbours) is supervised classification or regression and k is the number of neighbours consulted.
Further reading
- Lloyd, Least squares quantization in PCM, 1982 (a 1957 Bell Labs report): Lloyd's algorithm.
- MacQueen, Some methods for classification and analysis of multivariate observations, 1967: where the name "k-means" comes from.
- Arthur, Vassilvitskii, k-means++: The Advantages of Careful Seeding, 2007.
- Rousseeuw, Silhouettes: a graphical aid to the interpretation and validation of cluster analysis, 1987: the silhouette coefficient.
- scikit-learn, KMeans: this page's reference implementation.