Clustering: k-means, GMMs/EM, DBSCAN and hierarchical
Finding structure when nobody gave you labels
Clustering is the first unsupervised tool you reach for: grouping customers, deduplicating data, discovering topics in a pile of embeddings. k-means also hides inside production systems you will use later — the IVF index of a vector database is literally k-means centroids (9.3 Vector search and indexes) — and the EM algorithm for mixtures introduces the evidence lower bound that variational autoencoders optimize (8.8 Generative models I: VAEs and GANs).
You'll be able to
- State the k-means objective, run Lloyd's algorithm by hand and explain why it converges
- Write the E- and M-steps of EM for a Gaussian mixture and relate k-means to a GMM limit
- Choose between k-means, GMMs, DBSCAN and agglomerative clustering from the shape and scale of the data
- Evaluate clusterings with silhouette scores and external indices, and cluster embeddings sensibly
Key ideas
- k-means minimizes inertia J = Σₖ Σ_{i∈Cₖ} ‖xᵢ − μₖ‖²; Lloyd's algorithm alternates nearest-centroid assignment and mean update.
- Both steps can only decrease J, so k-means converges — to a local minimum; use k-means++ initialization and several restarts.
- Choose K with the elbow on inertia, the silhouette score, or (for GMMs) BIC.
Show 4 more key ideas
- GMMs fit Σₖ πₖ N(μₖ, Σₖ) with EM: E-step computes responsibilities by Bayes' rule, M-step takes responsibility-weighted means/covariances/weights.
- k-means is a GMM with covariance σ²I as σ → 0: hard assignments and spherical clusters.
- DBSCAN needs no K, finds arbitrary shapes and labels noise, but assumes one density; agglomerative clustering yields a dendrogram but is O(n²).
- Clustering embeddings powers topic discovery and deduplication; IVF vector indexes are k-means partitions.
Suggested path through this lesson
Structure without labels
Clustering asks: can these points be grouped so that members of a group are similar to each other and different from the rest? There is no ground truth, so every algorithm bakes in a definition of "group": a compact blob around a center (k-means), a probability distribution (mixture models), a dense region (DBSCAN) or a nested hierarchy (agglomerative). Pick the algorithm by which definition matches your data, and always look at the result.
k-means: the objective
Given points and a target number of clusters , k-means seeks centroids and an assignment of points to clusters that minimize the within-cluster sum of squares (the inertia):
Exact minimization is NP-hard, so we use Lloyd's algorithm: initialize centroids; then alternate (1) assign each point to its nearest centroid and (2) update each centroid to the mean of its points, until assignments stop changing.
Math check (why it converges). Step 1 cannot increase : with centroids fixed, moving a point to a closer centroid lowers its term. Step 2 cannot increase either: with assignments fixed, is minimized by setting its gradient to zero, i.e. , the mean. decreases monotonically, is bounded below by 0, and there are finitely many assignments — so the algorithm terminates. It terminates at a local minimum, which is why we restart several times and keep the best .
Worked example. Points on a line: , , initial centroids , . Assignment: ; . Update: , . Assignment: (3 is 2 away from 1 but 4.6 from 7.6); . Update: , . Nothing changes afterwards; . A bad initialization (say is good; is bad) can end in a worse local minimum — hence k-means++ initialization, which picks each new centroid with probability proportional to , its squared distance to the nearest existing centroid, and guarantees an expected -competitive solution.
Choosing : plot against and look for an elbow; or compute the silhouette of each point, with the mean distance to its own cluster and the mean distance to the nearest other cluster — values near 1 are well placed, near 0 are on a border. k-means assumes roughly spherical, similarly sized clusters, is sensitive to feature scaling and outliers, and must be told . Scale features first (3.13 Feature engineering, data quality and data-centric ML); use PCA to denoise if is large (3.12 Dimensionality reduction: PCA, t-SNE and UMAP).
Gaussian mixtures and EM
A Gaussian mixture model describes the data as a weighted sum of Gaussians,
with a latent cluster variable for each point. Maximum likelihood has no closed form because of the sum inside the log, so we use Expectation–Maximization:
- E-step: compute responsibilities, the posterior probability that point came from component (Bayes' rule, 1.7 Probability II: Bayes, independence, MLE and MAP):
- M-step: re-estimate parameters with responsibility-weighted statistics, :
Each iteration increases the log-likelihood (EM maximizes a lower bound on it — the same evidence lower bound a VAE optimizes, 8.8 Generative models I: VAEs and GANs). GMMs give soft assignments, elliptical clusters of different sizes, and a density you can use for anomaly scores. k-means is the limit of a GMM with shared covariance as : responsibilities become one-hot and the M-step becomes the mean update. Choose for a GMM with BIC/AIC rather than an elbow.
Density and hierarchy
DBSCAN needs no . With a radius and a minimum count minPts, a core point has at least minPts neighbours within ; clusters are maximal sets of density-connected core points plus their border points; everything else is labelled noise. It finds arbitrary shapes (rings, crescents) and flags outliers, but one global struggles when densities vary (HDBSCAN fixes this by building a hierarchy over ).
Agglomerative clustering starts with every point as its own cluster and repeatedly merges the two closest clusters, where "closest" is defined by a linkage: single (nearest members; chains), complete (farthest members; compact), average, or Ward (merge that increases total within-cluster variance least; most k-means-like). The merge history is a dendrogram, which you cut at a height to get any number of clusters — useful when the hierarchy itself is the insight (taxonomies, document trees). Cost is time and memory, so it is for thousands, not millions, of points.
| method | needs K? | cluster shape | outliers | scales to |
|---|---|---|---|---|
| k-means | yes | spherical, similar size | sensitive | millions |
| GMM + EM | yes (BIC) | elliptical, soft | moderate | large |
| DBSCAN/HDBSCAN | no | arbitrary, dense | labels them | large |
| agglomerative | cut later | depends on linkage | sensitive | ~10⁴ |
Evaluating and using clusters
Without labels, use internal indices (silhouette, Davies–Bouldin) and stability (do clusters survive re-sampling and re-seeding?). With labels available for checking, use the adjusted Rand index or normalized mutual information (1.9 Information theory: entropy, cross-entropy and KL divergence). Always visualize with PCA or UMAP (3.12 Dimensionality reduction: PCA, t-SNE and UMAP) and read actual members of each cluster.
Clustering embeddings is a workhorse of the LLM era: cluster sentence embeddings (9.2 Embeddings deep dive) to discover topics (BERTopic = UMAP + HDBSCAN + class-based TF-IDF), to deduplicate near-identical training data, or to pick diverse examples for few-shot prompts. And the inverted-file index that makes vector search fast partitions the space with k-means centroids (9.3 Vector search and indexes).
Where this shows up later
- Dimensionality reduction before and after clustering — 3.12 Dimensionality reduction: PCA, t-SNE and UMAP; feature scaling — 3.13 Feature engineering, data quality and data-centric ML.
- EM's lower bound is the ELBO of variational autoencoders — 8.8 Generative models I: VAEs and GANs; soft assignments reappear as softmax responsibilities and as attention weights — 7.2 Scaled dot-product and multi-head attention, fully derived.
- Clustering embeddings for topics and dedup — 9.2 Embeddings deep dive; IVF indexes built on k-means — 9.3 Vector search and indexes; clustering agent trajectories for error analysis — 10.9 Evaluating agents.
Common pitfalls (4)
- Running k-means on unscaled features or on data with many outliers — centroids get dragged.
- Trusting one run: different seeds give different local minima; compare inertia across restarts.
- Reading the elbow plot as if it always had an elbow; often it doesn't, and silhouette or domain knowledge should decide.
- Using DBSCAN with one ε on data whose density varies across regions (use HDBSCAN).
Recap: all 7 key points
- k-means minimizes inertia J = Σₖ Σ_{i∈Cₖ} ‖xᵢ − μₖ‖²; Lloyd's algorithm alternates nearest-centroid assignment and mean update.
- Both steps can only decrease J, so k-means converges — to a local minimum; use k-means++ initialization and several restarts.
- Choose K with the elbow on inertia, the silhouette score, or (for GMMs) BIC.
- GMMs fit Σₖ πₖ N(μₖ, Σₖ) with EM: E-step computes responsibilities by Bayes' rule, M-step takes responsibility-weighted means/covariances/weights.
- k-means is a GMM with covariance σ²I as σ → 0: hard assignments and spherical clusters.
- DBSCAN needs no K, finds arbitrary shapes and labels noise, but assumes one density; agglomerative clustering yields a dendrogram but is O(n²).
- Clustering embeddings powers topic discovery and deduplication; IVF vector indexes are k-means partitions.
Watch
Lloyd's algorithm and choosing K with the elbow method.
Read
Try it live
Interactive demo
runs in your browserExercises
- Lloyd's algorithm by hand
Run k-means with K = 2 on the points {0, 1, 4, 9, 10} starting from centroids 0 and 1. Record assignments, centroids and J at every iteration until convergence. Expected: final centroids 5/3 ≈ 1.67 and 9.5, J ≈ 8.67 + 0.5 = 9.17.
- Shapes that break k-means
Generate
make_blobs,make_moonsandmake_circlesdata. Cluster each with KMeans, GaussianMixture, DBSCAN and AgglomerativeClustering(ward and single linkage); plot a 3×4 grid. Expected: k-means/GMM win on blobs, DBSCAN and single linkage win on moons/circles. - Cluster real embeddings
Take ~2,000 short texts (e.g. 20 Newsgroups headlines), embed them with a small sentence-embedding model, reduce with PCA to 50 dimensions, run k-means for K ∈ {5, 10, 20} and print the 10 texts nearest each centroid. Compute silhouette scores. Expected: readable topics emerge; silhouette peaks at a modest K.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →