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
iter 0iter 1iter 2iter 3iter 4iter 5min Σ‖x − c‖²
Preparing the lab…

Intuition

Two alternating steps

No labels, just a cloud of points to split into groups. K-means is disarmingly simple: drop kk 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.

Five clusters, k = 5Preparing…
Same data, k = 4Preparing…
Moons, k = 2Preparing…

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 kk is wrong — it only minimises the inertia for the kk 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

nn points xix_i, kk centroids μ1,…,μk\mu_1,\dots,\mu_k, and a group c(i)c(i) for each point. K-means minimises

J=∑i=1n∥xi−μc(i)∥2J = \sum_{i=1}^{n} \big\|x_i - \mu_{c(i)}\big\|^2

Lloyd's algorithm

Assignment:   c(i)=arg⁡min⁡j∥xi−μj∥2,Update:   μj=1∣Sj∣∑i∈Sjxi\text{Assignment: }\; c(i) = \arg\min_j \|x_i - \mu_j\|^2, \qquad \text{Update: }\; \mu_j = \frac{1}{|S_j|}\sum_{i\in S_j} x_i

Each step on its own cannot increase JJ: assignment is optimal for fixed centroids, and for fixed groups the point minimising a sum of squared distances is the mean. Since J≥0J \ge 0 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 (k=4k = 4) 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 D(x)2D(x)^2 — 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 O(log⁡k)O(\log k) expected approximation guarantee.

Local optima and restarts

Lloyd's algorithm only guarantees a local optimum. With k=5k = 5 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 kk

The inertia only falls as kk grows (it is 0 when k=nk = n), so it cannot be compared directly. Two common approaches:

  • Elbow method: plot inertia against kk and look for the point where the decrease suddenly flattens.
  • Silhouette coefficient: for each point, aa is its mean distance to the other points of its cluster and bb its mean distance to the nearest other cluster; s=(b−a)/max⁡(a,b)s = (b-a)/\max(a,b), averaged over all points. Closer to 1 means cleaner clusters.
kkInertiaSilhouette
315220.546
47730.605
53490.674
63230.589
72970.523

(Each kk in the table is the best of 3 restarts, which is why k=6k = 6 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. 1. Picking initial centroids

    k = 5, just 5 steps. Watch the centroids being picked one at a time.

    Why does k-means++ tend to pick points far from the existing centroids?
  2. 2. Assignment and update

    Continue to step 10. Watch the centroid paths and the inertia curve.

    Why does the inertia only ever go down?
  3. 3. Too small a k

    Default k = 4.

    What happens when five clusters are split into 4 groups?
  4. 4. Elbow and silhouette

    Look at the "Choosing k" chart on the right.

    Which k fits best?
  5. 5. Local optima

    Random initialisation with 10 restarts. Look at each run's inertia.

    Why do some runs stop at 747 or even 1471?

Try these settings

With the unequal clusters and k=3k = 3, 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

What shape are K-means' cluster boundaries?
Why can't you choose k by the lowest inertia?
What happens if features have different units (one in metres, one in millimetres)?

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