Skip to content
Classical machine learning Core 27 min read

Clustering, mixtures and EM

Clustering finds groups in data that has no labels. Its central algorithm, k-means, turns out to be the zero-variance limit of fitting a Gaussian mixture with EM, and EM, which alternates between guessing the hidden variables and refitting, is the template for every latent-variable model up to the VAE.

10,000 ft

Most data is unlabelled. Clustering is the oldest way to find structure in it: customer segments, cell types, topics, duplicate documents, anomalies (the points that belong nowhere). Two of its ideas reach far beyond grouping. Vector quantisation, replacing a vector by its nearest centroid, is how vector databases compress billions of embeddings (see vector search) and how VQ-VAEs and many audio and image tokenisers turn continuous signals into discrete tokens. Expectation–maximisation (EM), the algorithm for fitting models with hidden variables, generalises into variational inference and the evidence lower bound (ELBO) that trains VAEs and underlies diffusion models. Clustering of embeddings is also a workhorse of data curation for pre-training.

2,000 ft

"Which points belong together?" has no single answer, so there are several families of algorithm, each encoding a different idea of what a cluster is. The two to master:

  1. k-means picks \(k\) centres and alternates two steps (assign each point to its nearest centre; move each centre to the mean of its points), each of which lowers the within-cluster sum of squares. Fast, simple, assumes round clusters of similar size.
  2. Gaussian mixture models (GMMs) say each point was generated by first picking a hidden component \(z\), then sampling from that component's Gaussian. EM fits it by alternating an E-step (compute each point's soft membership, the posterior \(p(z \mid \mathbf{x})\)) and an M-step (refit each Gaussian by weighted maximum likelihood). The likelihood never decreases.
  3. Shrink every Gaussian to the same tiny variance and soft memberships become hard: EM becomes k-means.
  4. Density-based (DBSCAN, HDBSCAN), hierarchical and spectral methods handle shapes and densities that centroids cannot.

Five ideas of what a cluster is
Five ideas of what a cluster is. Unlabelled points which ones belong together?, Centroid k-means: near a centre, Probabilistic GMM + EM: drawn from one component, Density DBSCAN, HDBSCAN: dense region, gaps between, Hierarchical merge closest groups: a tree of clusterings, Graph spectral: few edges cut between groups, hard limit ofFive ideas of what a cluster is. Unlabelled points which ones belong together?, Centroid k-means: near a centre, Probabilistic GMM + EM: drawn from one component, Density DBSCAN, HDBSCAN: dense region, gaps between, Hierarchical merge closest groups: a tree of clusterings, Graph spectral: few edges cut between groups, hard limit of

Ground level

What is a cluster? There is no neutral answer

Supervised learning has a target to be right about. Clustering does not, so every method smuggles in a definition. Kleinberg (2002) made this precise: he listed three properties anyone would want from a clustering function of pairwise distances (scale invariance: multiplying all distances by a constant changes nothing; richness: every partition is reachable for some distances; consistency: shrinking within-cluster distances and growing between-cluster distances does not change the result) and proved that no function satisfies all three. Every algorithm gives one up. The practical lesson: choose the method whose notion of cluster matches your problem, and judge the result by what it is for (a segmentation that marketing can act on, a deduplication that improves a model), not by an abstract score.

k-means

Given points \(\mathbf{x}_1..\mathbf{x}_n \in \mathbb{R}^d\) and a number \(k\), find centres \(\boldsymbol\mu_1..\boldsymbol\mu_k\) and assignments \(z_i \in \{1..k\}\) minimising the within-cluster sum of squares

\[ J = \sum_{i=1}^{n}\lVert\mathbf{x}_i - \boldsymbol\mu_{z_i}\rVert^2 . \]

Lloyd's algorithm alternates:

  1. Assign: \(z_i = \arg\min_j \lVert\mathbf{x}_i - \boldsymbol\mu_j\rVert^2\) (best \(z\) for fixed \(\boldsymbol\mu\)).
  2. Update: \(\boldsymbol\mu_j = \frac{1}{|C_j|}\sum_{i: z_i = j}\mathbf{x}_i\) (best \(\boldsymbol\mu\) for fixed \(z\); the mean minimises summed squared distance).

Each step can only lower \(J\), and there are finitely many assignments, so it terminates, at a local minimum. Finding the global minimum is NP-hard in general. Each iteration costs \(O(nkd)\).

Worked example

Six numbers, \(x = 1, 2, 3, 7, 8, 12\), with \(k = 2\) and a deliberately poor start \(\mu = (1, 4)\):

iteration centres assignment of 1, 2, 3, 7, 8, 12 \(J\)
0 1, 4 A A B B B B \(0+1+1+9+16+64 = 91\)
1 1.5, 7.5 A A A B B B 23.5
2 2, 9 A A A B B B 16 (converged)

After the first update the right-hand centre is the mean of \(\{3, 7, 8, 12\}\), 7.5, which is now farther from 3 than the left centre (1.5) is, so 3 changes sides, and one more update lands on centres 2 and 9 with \(J = (1 + 0 + 1) + (4 + 1 + 9) = 16\).

Initialisation and k-means++

Lloyd's algorithm is only as good as its start. Put two initial centres in the same true cluster and the algorithm may never separate them. k-means++ (Arthur and Vassilvitskii, 2007) picks the first centre uniformly at random and each next centre with probability proportional to \(D(\mathbf{x})^2\), the squared distance to the nearest centre already chosen. Far-away points are likely picks, so centres spread out, and the expected cost is provably within a factor \(O(\log k)\) of optimal before Lloyd even runs. It is the default in every major library; in practice you also run several restarts (n_init) and keep the lowest \(J\).

Choosing \(k\)

\(J\) always falls as \(k\) grows (\(k = n\) gives \(J = 0\)), so it cannot choose \(k\) on its own. Common tools, none decisive:

  • Elbow: plot \(J\) against \(k\) and look for the bend where extra clusters stop paying.
  • Silhouette: for each point, \(s = (b - a)/\max(a, b)\), where \(a\) is its mean distance to its own cluster and \(b\) to the nearest other cluster. \(s\) near 1 means well placed; average over points and pick the \(k\) with the highest mean.
  • Information criteria with a GMM: BIC \(= p\ln n - 2\ln\hat L\), where \(p\) counts parameters, penalises extra components properly because the GMM has a likelihood.
  • The gap statistic (Tibshirani, Walther and Hastie, 2001) compares \(\log J\) with its value on uniform reference data.
  • Downstream use, usually the real answer: the \(k\) that makes the segments actionable or the downstream model best.

Where k-means fails

k-means puts boundaries halfway between centres, so its clusters are Voronoi cells: convex, and implicitly assumed round (isotropic) and of similar spread. It fails on elongated or differently sized clusters, on non-convex shapes (two interleaved crescents, concentric rings), and on data with outliers, which drag means. It also needs a meaningful Euclidean distance, so features must be scaled. Each failure motivates a different method below.

Gaussian mixture models

A GMM is a generative story: to make a point, roll a \(k\)-sided die with probabilities \(\pi_1..\pi_k\) to choose a component \(z\), then draw \(\mathbf{x} \sim \mathcal{N}(\boldsymbol\mu_z, \Sigma_z)\). The marginal density is

\[ p(\mathbf{x}) = \sum_{j=1}^{k}\pi_j\,\mathcal{N}(\mathbf{x}\mid\boldsymbol\mu_j,\Sigma_j). \]

Each component has its own covariance, so clusters can be elongated, tilted and of different sizes, and membership is soft: the posterior probability that point \(i\) came from component \(j\), called its responsibility,

\[ r_{ij} = p(z_i = j\mid\mathbf{x}_i) = \frac{\pi_j\,\mathcal{N}(\mathbf{x}_i\mid\boldsymbol\mu_j,\Sigma_j)}{\sum_l \pi_l\,\mathcal{N}(\mathbf{x}_i\mid\boldsymbol\mu_l,\Sigma_l)} . \]

If we knew the \(z_i\), fitting would be trivial: the maximum-likelihood estimate of each Gaussian from its own points. If we knew the parameters, the \(r_{ij}\) would follow from Bayes' rule. EM alternates between the two.

EM: expectation–maximisation

EM, and where it went
EM, and where it went. EM (1977) fill in hidden z, refit, repeat, ELBO view (Neal and Hinton 1998) coordinate ascent on a lower bound, Variational inference q(z) from a tractable family, VAE (2013) encoder amortises q(z given x), k-means (Lloyd) hard E-step, Vector quantisation VQ-VAE codebooks, IVF and product quantisation vector search indexes, zero-variance limitEM, and where it went. EM (1977) fill in hidden z, refit, repeat, ELBO view (Neal and Hinton 1998) coordinate ascent on a lower bound, Variational inference q(z) from a tractable family, VAE (2013) encoder amortises q(z given x), k-means (Lloyd) hard E-step, Vector quantisation VQ-VAE codebooks, IVF and product quantisation vector search indexes, zero-variance limit

For a GMM, one EM iteration is:

  • E-step: compute \(r_{ij}\) for every point and component with the current parameters.
  • M-step: with \(N_j = \sum_i r_{ij}\) (the "effective number of points" in component \(j\)),
\[ \pi_j = \frac{N_j}{n}, \qquad \boldsymbol\mu_j = \frac{1}{N_j}\sum_i r_{ij}\mathbf{x}_i, \qquad \Sigma_j = \frac{1}{N_j}\sum_i r_{ij}(\mathbf{x}_i - \boldsymbol\mu_j)(\mathbf{x}_i - \boldsymbol\mu_j)^\top . \]

These are exactly the ordinary maximum-likelihood formulas with each point counted fractionally.

Worked example: one EM step by hand

The same six numbers, two 1-D components, initialised at \(\mu = (3, 7)\), \(\sigma^2 = (4, 4)\), \(\pi = (0.5, 0.5)\). With equal variances the responsibility depends only on the difference in squared distances. For \(x = 3\):

\[ \frac{p(z{=}1, x)}{p(z{=}2, x)} = \exp\Big(-\frac{(3-3)^2 - (3-7)^2}{2\cdot 4}\Big) = e^{2}, \qquad r_{1} = \frac{e^2}{1 + e^2} = \sigma(2) = 0.881 . \]

(A sigmoid of a linear function of \(x\): two equal-variance Gaussians induce exactly a logistic regression posterior.) All six:

\(x\) 1 2 3 7 8 12
\(r_{i1}\) 0.982 0.953 0.881 0.119 0.047 0.001

M-step: \(N_1 = 2.983\), \(N_2 = 3.017\), so \(\pi = (0.497, 0.503)\); \(\mu_1 = \sum r_{i1}x_i/N_1 = 2.264\), \(\mu_2 = 8.699\); \(\sigma_1^2 = 2.157\), \(\sigma_2^2 = 6.947\). The log-likelihood climbs over successive iterations from \(-17.34\) to \(-15.17\), \(-14.38\), \(-14.35\) and converges near \(\mu = (1.99, 8.93)\), \(\sigma^2 = (0.66, 5.04)\): the right-hand component has learned that it is wider, because 12 is far from 7 and 8. k-means cannot represent that.

1237812 r₁=.98r₁=.88r₁=.12r₁=.001 start: μ=(3, 7), σ²=(4, 4) after EM: μ=(1.99, 8.93), σ²=(0.66, 5.04)
EM on six points. Dashed: the two weighted components at initialisation. Solid: after convergence. The left component tightens around 1, 2, 3; the right one widens to cover 7, 8 and the outlying 12. Labels show the first E-step's responsibilities for component 1.

k-means is hard-assignment EM

Fix every covariance to \(\Sigma_j = \varepsilon I\) and every \(\pi_j = 1/k\). Then \(r_{ij} \propto \exp(-\lVert\mathbf{x}_i - \boldsymbol\mu_j\rVert^2/2\varepsilon)\). As \(\varepsilon \to 0\) the nearest centre's term dominates every other one exponentially, so \(r_{ij} \to 1\) for the nearest centre and \(0\) otherwise: the E-step becomes k-means' assignment step, and the M-step's weighted mean becomes the plain cluster mean. k-means is EM for a mixture of identical, infinitely narrow spherical Gaussians, which is exactly why it struggles with clusters that are not round and equally sized.

Density-based clustering: DBSCAN and HDBSCAN

DBSCAN (Ester, Kriegel, Sander and Xu, 1996) defines clusters as dense regions separated by sparse ones. With a radius \(\varepsilon\) and a count minPts: a core point has at least minPts neighbours within \(\varepsilon\); clusters are the connected components of core points (two core points are connected if within \(\varepsilon\) of each other), plus border points within reach; everything else is noise. It finds arbitrary shapes, needs no \(k\), and labels outliers explicitly, but a single \(\varepsilon\) cannot fit clusters of very different densities. HDBSCAN (Campello, Moulavi and Sander, 2013) runs DBSCAN at all \(\varepsilon\) at once, builds the resulting hierarchy and keeps the most persistent clusters, leaving essentially one intuitive knob, the minimum cluster size. It is the usual default for clustering embeddings, for example in BERTopic (embeddings → UMAP → HDBSCAN → topic words).

Hierarchical clustering

Agglomerative clustering starts with every point as its own cluster and repeatedly merges the two closest clusters, recording a dendrogram; cutting it at any height gives a clustering, so you never commit to \(k\) up front. "Closest" is the linkage: single (closest pair; finds long chains, prone to chaining through noise), complete (farthest pair; compact clusters), average, and Ward (the merge that least increases the within-cluster sum of squares, k-means' objective, built bottom-up). Naive implementations cost \(O(n^2)\) memory and up to \(O(n^3)\) time, so it suits thousands of points, not millions.

Spectral clustering

Build a similarity graph (connect each point to its nearest neighbours, weight \(W_{ij} = e^{-\lVert\mathbf{x}_i - \mathbf{x}_j\rVert^2/2s^2}\)), form the graph Laplacian \(L = D - W\) with \(D\) the diagonal of degrees, take the eigenvectors of its \(k\) smallest eigenvalues as new coordinates for each point, and run k-means there. The quadratic form \(\mathbf{f}^\top L\mathbf{f} = \tfrac12\sum_{ij}W_{ij}(f_i - f_j)^2\) is small when \(\mathbf{f}\) is nearly constant across strongly connected points; a graph with \(k\) connected components has exactly \(k\) zero eigenvalues, whose eigenvectors are the component indicators. Spectral clustering is a relaxation of the NP-hard normalised-cut problem, and it separates rings and crescents that defeat k-means. The idea of embedding a neighbour graph through its Laplacian returns in Laplacian eigenmaps and UMAP.

Clustering inside modern AI

  • Vector search. An IVF index runs k-means on the embeddings to make a coarse quantiser (search only the few closest cells); product quantisation (Jégou, Douze and Schmid, 2011) splits each vector into \(m\) sub-vectors and runs k-means with 256 centroids in each sub-space, so every sub-vector is stored as one byte. FAISS (Johnson, Douze and Jégou, 2017) runs this at billion scale on GPUs.
  • Discrete tokens for continuous signals. VQ-VAE (van den Oord, Vinyals and Kavukcuoglu, 2017) maps each encoder output to its nearest codebook vector, and its exponential-moving-average codebook update is online k-means. Descendants of this idea tokenise images and audio for multimodal and speech models (see speech and audio).
  • Data curation. SemDeDup (Abbas et al., 2023) clusters web-scale image–text embeddings with k-means and removes near-duplicates within each cluster, reporting that half of a LAION subset can be removed "with minimal performance loss, effectively halving training time". Clustering embeddings to balance topics in pre-training mixtures is now routine.
  • Analysis. Clustering an LLM's activations or embeddings is a quick first look at what it represents, before reaching for the heavier tools of interpretability.

History

  • 1956: Steinhaus proposes the k-means idea. 1957: Lloyd devises the alternating algorithm for pulse-code modulation at Bell Labs (published only in 1982). 1967: MacQueen coins "k-means".
  • 1977: Dempster, Laird and Rubin unify a scattered set of special cases as the EM algorithm and prove the likelihood never decreases.
  • 1996: DBSCAN makes "dense regions separated by sparse ones" an algorithm, with explicit noise.
  • 1998: Neal and Hinton recast EM as coordinate ascent on a free-energy lower bound, the step that leads to variational inference.
  • 2000–2002: spectral clustering (Shi and Malik's normalised cuts; Ng, Jordan and Weiss); Kleinberg's impossibility theorem.
  • 2007: k-means++ and von Luxburg's spectral clustering tutorial.
  • 2011–2017: product quantisation and FAISS make k-means the backbone of vector search; VQ-VAE puts a k-means codebook inside a neural network.

First principles

Why alternating minimisation works. k-means and EM both optimise a function of two groups of unknowns (assignments and parameters) where optimising one group with the other fixed is easy, though doing both jointly is hard. Each half-step cannot make things worse, so the objective is monotone and the procedure converges, to a stationary point that depends on the start. That is the whole reason for k-means++ and restarts.

Why EM increases the likelihood. For any distribution \(q(z)\) over the hidden variables, Jensen's inequality gives a lower bound on the log-likelihood, the ELBO, and the gap is exactly \(\mathrm{KL}(q \,\Vert\, p(z\mid\mathbf{x},\theta))\) (derived below). The E-step sets \(q\) to the true posterior, closing the gap so that the bound touches the log-likelihood at the current \(\theta\). The M-step raises the bound by moving \(\theta\). Since the log-likelihood is at least the bound everywhere, and the two were equal before the move, the log-likelihood cannot have fallen. When the posterior is intractable you cannot close the gap; restricting \(q\) to a tractable family and maximising the same bound is variational inference, and learning a network that outputs \(q\) for each \(\mathbf{x}\) is the VAE.

Why maximum likelihood for mixtures is ill-posed. Put one component's mean exactly on a data point and shrink its variance: its density at that point goes to infinity and so does the likelihood. The global "optimum" is degenerate. EM finds sensible local optima in practice because it starts away from the singularity; libraries add a small diagonal to every covariance (reg_covar in scikit-learn, 1e-6 * I in the code below), or you can put a prior on the covariances (MAP-EM).

Why soft beats hard near boundaries. A point halfway between two clusters gets \(r \approx 0.5\) in a GMM and contributes half its weight to each mean; k-means gives it entirely to one side, so a few borderline points can flip assignments back and forth between iterations. Soft assignment is smoother and, being a proper likelihood, supports model comparison (BIC) and density estimation (anomaly scores are just low \(p(\mathbf{x})\)).

Why clusters are not identifiable. Relabel the components and the likelihood is unchanged: there are \(k!\) equivalent optima. This "label switching" is harmless for clustering but matters when you average samples in Bayesian mixture models.

The maths

k-means as coordinate descent. For fixed \(z\), \(J\) is a sum of independent quadratics in each \(\boldsymbol\mu_j\); setting \(\nabla_{\boldsymbol\mu_j}J = -2\sum_{i:z_i=j}(\mathbf{x}_i - \boldsymbol\mu_j) = 0\) gives the cluster mean. For fixed \(\boldsymbol\mu\), \(J\) separates over points and each \(z_i\) is chosen independently as the nearest centre.

GMM log-likelihood. Shapes: \(X \in \mathbb{R}^{n\times d}\), \(\boldsymbol\pi \in \Delta^{k-1}\) (the probability simplex), \(\boldsymbol\mu_j \in \mathbb{R}^d\), \(\Sigma_j \in \mathbb{R}^{d\times d}\) symmetric positive definite, \(R \in \mathbb{R}^{n\times k}\) with rows summing to 1.

\[ \ell(\theta) = \sum_{i=1}^n \log\sum_{j=1}^k \pi_j\,\mathcal{N}(\mathbf{x}_i\mid\boldsymbol\mu_j,\Sigma_j), \qquad \log\mathcal{N}(\mathbf{x}\mid\boldsymbol\mu,\Sigma) = -\tfrac12(\mathbf{x}-\boldsymbol\mu)^\top\Sigma^{-1}(\mathbf{x}-\boldsymbol\mu) - \tfrac12\log\lvert\Sigma\rvert - \tfrac d2\log 2\pi . \]

The log of a sum does not decompose, so setting gradients to zero gives coupled equations with no closed form. Compute the inner sum with log-sum-exp: densities of far-away points underflow to zero in float64 long before their logs are troublesome.

Derivation: the ELBO decomposition and why EM is monotone

For any distribution \(q(z)\) with \(q(z) > 0\) wherever \(p(z\mid\mathbf{x},\theta) > 0\):

\[ \log p(\mathbf{x}\mid\theta) = \sum_z q(z)\log p(\mathbf{x}\mid\theta) = \sum_z q(z)\log\frac{p(\mathbf{x}, z\mid\theta)}{p(z\mid\mathbf{x},\theta)} = \underbrace{\sum_z q(z)\log\frac{p(\mathbf{x},z\mid\theta)}{q(z)}}_{\mathcal{F}(q,\theta)\ =\ \text{ELBO}} + \underbrace{\sum_z q(z)\log\frac{q(z)}{p(z\mid\mathbf{x},\theta)}}_{\mathrm{KL}(q\,\Vert\,p(z\mid\mathbf{x},\theta))\ \ge\ 0} . \]

E-step: with \(\theta^{t}\) fixed, \(\mathcal{F}\) is maximised over \(q\) by making the KL zero: \(q^{t+1}(z) = p(z\mid\mathbf{x},\theta^t)\). Then \(\mathcal{F}(q^{t+1},\theta^t) = \log p(\mathbf{x}\mid\theta^t)\).

M-step: with \(q^{t+1}\) fixed, \(\mathcal{F}(q,\theta) = \mathbb{E}_{q}[\log p(\mathbf{x},z\mid\theta)] + H(q)\), and the entropy \(H(q)\) does not depend on \(\theta\), so maximise the expected complete-data log-likelihood \(Q(\theta) = \mathbb{E}_q[\log p(\mathbf{x},z\mid\theta)]\) to get \(\theta^{t+1}\).

Chain: \(\log p(\mathbf{x}\mid\theta^{t+1}) \ge \mathcal{F}(q^{t+1},\theta^{t+1}) \ge \mathcal{F}(q^{t+1},\theta^t) = \log p(\mathbf{x}\mid\theta^t)\). The first inequality is KL \(\ge 0\), the second is the M-step. So the likelihood never decreases. EM is coordinate ascent on \(\mathcal{F}\), which is why partial E-steps or partial M-steps (any \(\theta\) that merely increases \(Q\), "generalised EM") still work, as Neal and Hinton showed.

Derivation: the GMM M-step

With responsibilities \(r_{ij}\) fixed, the complete-data objective is

\[ Q = \sum_i\sum_j r_{ij}\Big[\log\pi_j - \tfrac12(\mathbf{x}_i-\boldsymbol\mu_j)^\top\Sigma_j^{-1}(\mathbf{x}_i-\boldsymbol\mu_j) - \tfrac12\log\lvert\Sigma_j\rvert\Big] + \text{const}. \]

Means: \(\nabla_{\boldsymbol\mu_j}Q = \Sigma_j^{-1}\sum_i r_{ij}(\mathbf{x}_i - \boldsymbol\mu_j) = 0 \Rightarrow \boldsymbol\mu_j = \sum_i r_{ij}\mathbf{x}_i / N_j\).

Covariances: using \(\partial\log\lvert\Sigma\rvert/\partial\Sigma^{-1} = -\Sigma\) and \(\partial(\mathbf{a}^\top\Sigma^{-1}\mathbf{a})/\partial\Sigma^{-1} = \mathbf{a}\mathbf{a}^\top\), differentiate with respect to \(\Sigma_j^{-1}\): \(\tfrac12\sum_i r_{ij}\big[\Sigma_j - (\mathbf{x}_i-\boldsymbol\mu_j)(\mathbf{x}_i-\boldsymbol\mu_j)^\top\big] = 0\), so \(\Sigma_j = \frac1{N_j}\sum_i r_{ij}(\mathbf{x}_i-\boldsymbol\mu_j)(\mathbf{x}_i-\boldsymbol\mu_j)^\top\).

Weights: maximise \(\sum_j N_j\log\pi_j\) subject to \(\sum_j\pi_j = 1\). The Lagrangian \(\sum_j N_j\log\pi_j + \lambda(1 - \sum_j\pi_j)\) gives \(N_j/\pi_j = \lambda\); summing, \(\lambda = n\), so \(\pi_j = N_j/n\).

Responsibilities as a softmax. Writing \(a_{ij} = \log\pi_j + \log\mathcal{N}(\mathbf{x}_i\mid\boldsymbol\mu_j,\Sigma_j)\), the E-step is \(r_{ij} = \operatorname{softmax}_j(a_{ij})\). With shared covariance \(\Sigma\), the quadratic term \(\mathbf{x}^\top\Sigma^{-1}\mathbf{x}\) is common to all \(j\) and cancels in the softmax, so the posterior is a softmax of functions linear in \(\mathbf{x}\): shared-covariance GMMs produce linear boundaries (this is linear discriminant analysis), separate covariances produce quadratic ones.

Spectral clustering's key identity. For any \(\mathbf{f} \in \mathbb{R}^n\) and \(L = D - W\) with \(W\) symmetric and non-negative, \(\mathbf{f}^\top L\mathbf{f} = \sum_i D_{ii}f_i^2 - \sum_{ij}W_{ij}f_if_j = \tfrac12\sum_{ij}W_{ij}(f_i - f_j)^2 \ge 0\). So \(L\) is PSD, \(\mathbf{1}\) is an eigenvector with eigenvalue 0, and the indicator of any connected component also has eigenvalue 0.

In practice

  • Scale features first. All distance-based methods (k-means, DBSCAN, spectral, hierarchical) are at the mercy of units. Standardise, or use a distance that suits the data (for embeddings, normalise vectors to unit length first: then \(\lVert\mathbf{a}-\mathbf{b}\rVert^2 = 2 - 2\cos(\mathbf{a},\mathbf{b})\), so Euclidean neighbours are cosine neighbours).
  • Defaults that work: k-means++ with n_init of 10 or so for speed and large \(n\) (MiniBatchKMeans beyond a few million points); GMM with full covariances when \(d\) is small and data are plentiful, diagonal covariances when \(d\) is large; HDBSCAN for embeddings, shapes and outliers; agglomerative with Ward linkage when you want a dendrogram.
  • Reduce dimension first for high-dimensional data. In hundreds of dimensions distances concentrate (all pairs look similarly far apart). Clustering on 10–50 PCA components, or on a UMAP embedding with HDBSCAN, is standard for text and single-cell data; see dimensionality reduction for the caveats of clustering on a UMAP picture.
  • Validate stability, not just scores. Re-run on bootstrap samples or with different seeds and check whether the same clusters reappear (adjusted Rand index between runs). Unstable clusters are not findings.
  • Mixtures are density models. A fitted GMM gives \(p(\mathbf{x})\), so it doubles as an anomaly detector (flag low-density points) and as a simple generative model.

Common misconceptions

“The algorithm found 5 clusters, so the data has 5 groups”

k-means returns \(k\) clusters for any data, including uniform noise. Whether those clusters are real is a separate question: check stability across resamples, compare with a null (the gap statistic does this), and look at whether the groups mean anything.

“EM finds the maximum-likelihood estimate”

It finds a stationary point, usually a local maximum, that depends on initialisation; the global supremum of a GMM likelihood is even infinite. Run several initialisations (k-means is a good one) and keep the best likelihood.

“Soft assignments mean the model is uncertain about the cluster structure”

Responsibilities are uncertainty about which component generated a point given fixed parameters. Uncertainty about the parameters themselves (how many clusters, where they are) needs Bayesian treatment or resampling.

Build it

k-means++ with Lloyd's algorithm, and a full-covariance GMM fitted by EM (with log-sum-exp in the E-step), on three elongated, overlapping clusters, the shape that breaks k-means.

import numpy as np
from itertools import permutations
rng = np.random.default_rng(3)

# Three elongated, overlapping Gaussian clusters (k-means' worst case: non-spherical)
means = np.array([[0, 0], [3, 3], [0, 6]])
covs = [np.array([[4.0, 1.8], [1.8, 1.0]])] * 3
X = np.vstack([rng.multivariate_normal(m, c, 300) for m, c in zip(means, covs)])
truth = np.repeat(np.arange(3), 300)

def kmeans_pp(X, k):                       # k-means++: sample centres with prob ∝ D(x)^2
    C = [X[rng.integers(len(X))]]
    for _ in range(k - 1):
        d2 = np.min(((X[:, None] - np.array(C)[None])**2).sum(-1), axis=1)
        C.append(X[rng.choice(len(X), p=d2 / d2.sum())])
    return np.array(C)

def kmeans(X, k, iters=100):
    C = kmeans_pp(X, k)
    for _ in range(iters):
        z = ((X[:, None] - C[None])**2).sum(-1).argmin(1)           # assignment step
        C_new = np.array([X[z == j].mean(0) for j in range(k)])     # update step
        if np.allclose(C, C_new): break
        C = C_new
    return z, C

def log_gauss(X, mu, S):                   # log N(x | mu, S) for every row of X
    d = X - mu; L = np.linalg.cholesky(S)
    sol = np.linalg.solve(L, d.T)
    return -0.5 * (sol**2).sum(0) - np.log(np.diag(L)).sum() - 0.5 * X.shape[1] * np.log(2 * np.pi)

def gmm_em(X, k, iters=200):
    n, d = X.shape; _, mu = kmeans(X, k)                            # initialise from k-means
    S = np.array([np.cov(X.T)] * k); pi = np.full(k, 1 / k); prev = -np.inf
    for t in range(iters):
        logp = np.stack([np.log(pi[j]) + log_gauss(X, mu[j], S[j]) for j in range(k)], 1)
        m = logp.max(1, keepdims=True)                              # log-sum-exp for stability
        ll = (m[:, 0] + np.log(np.exp(logp - m).sum(1))).sum()
        R = np.exp(logp - m); R /= R.sum(1, keepdims=True)          # E-step: responsibilities
        Nk = R.sum(0); pi = Nk / n; mu = (R.T @ X) / Nk[:, None]    # M-step: weighted MLE
        S = np.array([((R[:, j, None] * (X - mu[j])).T @ (X - mu[j])) / Nk[j] + 1e-6 * np.eye(d)
                      for j in range(k)])
        if t in (0, 1, 2, 5, 10, 20) or ll - prev < 1e-6:
            print(f"EM iter {t:3d}: log-likelihood = {ll:9.2f}")
        if ll - prev < 1e-6: break
        prev = ll
    return R.argmax(1)

def accuracy(z):                          # best match between cluster ids and true labels
    return max(np.mean(np.array(p)[z] == truth) for p in permutations(range(3)))

zk, _ = kmeans(X, 3)
zg = gmm_em(X, 3)
print(f"k-means agreement with truth: {accuracy(zk):.3f}")
print(f"GMM-EM  agreement with truth: {accuracy(zg):.3f}")

Output:

EM iter   0: log-likelihood =  -4248.81
EM iter   1: log-likelihood =  -3979.05
EM iter   2: log-likelihood =  -3682.83
EM iter   5: log-likelihood =  -3448.85
EM iter  10: log-likelihood =  -3411.26
EM iter  20: log-likelihood =  -3359.67
EM iter  29: log-likelihood =  -3359.67
k-means agreement with truth: 0.888
GMM-EM  agreement with truth: 0.987

The log-likelihood rises at every iteration, as the ELBO argument guarantees, and settles after 29 iterations. Because the true clusters are tilted ellipses, k-means' straight Voronoi boundaries cut through them and misassign 11% of points; the GMM learns the shared tilt in its covariances and recovers 98.7% (the remainder is genuine overlap that no method could resolve).

Things to try

  • Replace k-means++ with uniform random initialisation and run k-means 20 times with different seeds. Record the spread of final \(J\) values.
  • Constrain the GMM to spherical covariances (S[j] = np.eye(d) * variance) and check that its accuracy falls towards k-means'.
  • Fit GMMs with \(k = 1..6\) and compute BIC \(= p\ln n - 2\ell\) with \(p = (k-1) + kd + k\,d(d+1)/2\). Does it pick 3?
  • Make one cluster ten times smaller than the others and compare k-means and the GMM.
  • Generate two interleaved crescents. Show that both k-means and the GMM fail, then implement DBSCAN (about 20 lines with a neighbour matrix) and show that it succeeds.

Check yourself

Why can each step of k-means only decrease J?

The assignment step picks, for each point, the centre that minimises its own term, so no term can increase. The update step replaces each centre by the mean of its points, which is the unique minimiser of the sum of squared distances to those points. Both steps are exact minimisations over one group of variables with the other fixed.

Two 1-D Gaussians with equal weights and variances σ² = 1 sit at μ = 0 and μ = 4. What is the responsibility of the first component for x = 1?

The ratio is \(\exp(-\tfrac12[(1-0)^2 - (1-4)^2]) = \exp(4) \approx 54.6\), so \(r_1 = 54.6/55.6 \approx 0.982\). Equivalently \(r_1 = \sigma(4)\).

Why does k-means with Euclidean distance prefer clusters of similar spatial extent?

The boundary between two centres is the perpendicular bisector, always halfway between them regardless of how spread out each cluster is. A wide cluster next to a tight one loses its outer points to the tight cluster's centre. A GMM with per-component variances moves the boundary towards the tighter component.

In a GMM, what goes wrong if a component's covariance collapses, and how do practitioners prevent it?

If a component sits on a single point with \(\Sigma \to 0\), its density at that point goes to infinity and the likelihood is unbounded: a degenerate, meaningless optimum. Prevent it by adding a small constant to the covariance diagonal, placing a prior on covariances (MAP-EM), or restarting the component elsewhere when \(N_j\) gets tiny.

Where does the 'E' in EM come from? What expectation is taken?

The M-step maximises the expected complete-data log-likelihood \(Q(\theta) = \mathbb{E}_{z\sim p(z\mid\mathbf{x},\theta^{t})}[\log p(\mathbf{x}, z\mid\theta)]\). The E-step computes the posterior needed for that expectation; for a GMM, that is just the responsibilities.

Hard: show that the VAE's training objective is the same ELBO EM uses, and say what the VAE gives up.

The VAE maximises \(\mathbb{E}_{q_\phi(z\mid\mathbf{x})}[\log p_\theta(\mathbf{x}\mid z)] - \mathrm{KL}(q_\phi(z\mid\mathbf{x})\,\Vert\,p(z)) = \mathbb{E}_q[\log p_\theta(\mathbf{x}, z) - \log q_\phi(z\mid\mathbf{x})]\), which is \(\mathcal{F}(q,\theta)\). EM's E-step makes \(q\) the exact posterior, closing the gap; the VAE cannot (its posterior is intractable), so it restricts \(q\) to Gaussians output by an encoder and maximises the bound jointly over \(\theta\) and \(\phi\) by stochastic gradients. It gives up the guarantee that the likelihood rises at each step and accepts a permanent gap, the KL between \(q_\phi\) and the true posterior.

Hard: product quantisation stores a 768-dimensional float32 embedding with m = 96 sub-quantisers of 256 centroids each. What is the compression ratio, and why does PQ beat running k-means with the same number of bits on the full vector?

The raw vector takes \(768 \times 4 = 3{,}072\) bytes; PQ stores 96 one-byte codes, so the ratio is 32. Ninety-six bytes is 768 bits, equivalent to a single codebook of \(2^{768}\) centroids: impossible to train or store. PQ gets that effective codebook as a Cartesian product of 96 small codebooks with only \(96 \times 256\) centroids to learn, at the price of assuming the sub-spaces can be quantised independently.

Go deeper

Papers

Videos and lectures

Articles and docs

  • How HDBSCAN Works — McInnes et al. Mutual reachability, the condensed tree and cluster stability, with pictures.
  • scikit-learn: Clustering — The comparison chart of ten algorithms on toy shapes is worth a long look.

Courses and books

Code

  • FAISS — k-means, IVF and product quantisation at billion scale; reading its clustering code is a lesson in practical k-means.
  • BERTopic (paper) — Grootendorst, 2022. Embeddings → UMAP → HDBSCAN → topic words: a widely used modern clustering pipeline for text.

Where this leads