Lesson 3.11core3 h⚡ live demo

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

  1. k-means minimizes inertia J = Σₖ Σ_{i∈Cₖ} ‖xᵢ − μₖ‖²; Lloyd's algorithm alternates nearest-centroid assignment and mean update.
  2. Both steps can only decrease J, so k-means converges — to a local minimum; use k-means++ initialization and several restarts.
  3. Choose K with the elbow on inertia, the silhouette score, or (for GMMs) BIC.
Show 4 more key ideas
  1. GMMs fit Σₖ πₖ N(μₖ, Σₖ) with EM: E-step computes responsibilities by Bayes' rule, M-step takes responsibility-weighted means/covariances/weights.
  2. k-means is a GMM with covariance σ²I as σ → 0: hard assignments and spherical clusters.
  3. DBSCAN needs no K, finds arbitrary shapes and labels noise, but assumes one density; agglomerative clustering yields a dendrogram but is O(n²).
  4. Clustering embeddings powers topic discovery and deduplication; IVF vector indexes are k-means partitions.

Suggested path through this lesson