k-means clustering
Find k groups by alternating between assigning points to centroids and moving centroids to means.
Animated explanation
The idea
You have customer data and no labels, and you suspect there are a few kinds of customers. k-means makes that concrete: choose , scatter centroids, then repeat two steps until nothing changes. Assign every point to its nearest centroid. Move every centroid to the average of its points.
Each step lowers the total squared distance from points to their centroids, so the loop always finishes. The result partitions space into convex cells (a Voronoi diagram). It is fast and simple, and it assumes clusters are roughly round, similar in size, and that you know .
Initialisation matters
k-means finds a local minimum. Random starting centroids can put two in one blob and none in another. k-means++ picks the first centroid at random and each next one with probability proportional to its squared distance from the nearest centroid already chosen. Run several restarts (n_init) and keep the lowest inertia.
Choosing k
Inertia always decreases with , so it cannot choose alone. Use the elbow of the inertia curve, the silhouette score (how much closer each point is to its own cluster than to the next), the gap statistic, or simply the number of groups that is useful to the business.
When it fails
Non-convex shapes (rings, moons), clusters of very different size or density, and outliers all break k-means; and features must be scaled, since it uses Euclidean distance. Alternatives: GMMs (elliptical, soft), DBSCAN (arbitrary shape, noise), spectral clustering (graph structure). Mini-batch k-means scales to millions of points.
The algorithm, step by step
- 1Standardise features. Choose and initialise centroids with k-means++.
- 2Assign each point to the nearest centroid.
- 3Move each centroid to the mean of its assigned points.
- 4Repeat until assignments stop changing (or inertia improves by less than a tolerance).
- 5Repeat from several initialisations; keep the lowest inertia.
The maths
Objective (inertia)
Assignment
Update
Silhouette of point i
Strengths and weaknesses
Strengths
- Simple, fast (linear in n per iteration)
- Scales to huge data (mini-batch)
- Easy to explain: prototypes
Weaknesses
- Must choose k
- Assumes round, similar-sized clusters; sensitive to scale and outliers
- Local minima: needs good initialisation
Reach for it when…
Check your understanding
Lambdian Lab
k-means with k-means++
Implement the full algorithm.
- kmeans_pp(X, k, rng): k-means++ initial centroids.
- assign(X, C) → labels; update(X, labels, C) → new centroids (keep a centroid in place if its cluster is empty).
- kmeans(X, k, n_init, iters, seed) → (centroids, labels, inertia) of the best run.
- elbow(X, ks, seed) → list of inertias.