Clustering: k-means and Gaussian mixtures
Watch k-means and the EM algorithm group points step by step. Drag the points, compare k-means++ with a random start, choose the number of clusters with the elbow plot and BIC, and see when k-means fails and what a Gaussian mixture adds.
Clustering means splitting data points into groups (clusters) so that points in the same group are similar. Nobody gives the algorithm the right groups: there are no labels. This page shows the two classic methods on points in the plane:
- k-means describes each cluster by one point, its centre . It repeats two steps: give every point to its nearest centre, then move every centre to the mean of its points.
- A Gaussian mixture model (GMM) describes each cluster by a Gaussian distribution: a centre, a covariance (the size, shape and direction of an ellipse) and a weight (the share of the data). It is fitted with the EM algorithm (expectation–maximization), which also repeats two steps.
In the first simulation you run both methods one step at a time on data that you can change. In the second one you see the same data clustered by both methods side by side, and you find out when k-means gives the wrong answer. The math behind the pictures is in section 4.
1. k-means and EM, step by step #
Press Step again and again, and watch the two steps of k-means. Each data point takes the colour of its cluster (blue, orange, aqua, violet, magenta, yellow for clusters 1 to 6). The large ringed dots are the centres ; the lines behind them are their paths. With k-means the coloured regions are the Voronoi cells: each region holds the places that are closest to one centre. Press New start to see the seeding step by step: with k-means++ the size of a grey dot shows its chance to be picked as the next centre. Switch the method to Gaussian mixture (EM): the ellipses show 1 and 2 standard deviations of each Gaussian, a point's colour mixes the cluster colours with its responsibilities, and the background shows the mixture density. Drag points, click to add points or a whole cloud, and drag a centre to pick your own start. The first chart shows the objective of this run after every step; the second chart is the elbow plot (k-means) or BIC (mixture) for . Click it to change .
2. When k-means fails #
Move the slider and watch the two clusterings change. The first panel shows k-means, the second a Gaussian mixture fitted with EM. Both get the true number of clusters and keep the best of several runs, so a failure is not bad luck. Colours are matched to the true clusters, and a ring marks each point in the wrong cluster. The chart shows the adjusted Rand index (ARI) of both methods against the slider value: means a perfect clustering, about means no better than random groups. Press Show the true clusters to see the answer, and try the other kinds of data.
3. Try this #
- Can the objective go up? Keep blobs and and press Step slowly. Question: after an assign step and after an update step, can the inertia (the sum of squared distances from each point to its centre) become larger? What to see: the chart only goes down. After an update step, some points lie in a region of another colour: the next assign step moves exactly these points. Here k-means stops after 2 iterations with .
- A bad start. Set Start to random points and press To the end. Question: do the four centres find the four blobs? What to see: no. Two centres share one blob, and one centre sits between two blobs. k-means stops with , three times the of the good answer, and it never escapes: this is a local minimum. Press New start a few times with both kinds of start. In our runs, random points ended in a worse local minimum in 16 of 40 starts, and k-means++ in 4 of 40. Step through a k-means++ start: the big grey dots (likely picks) are always far from the centres chosen so far.
- How many clusters? Look at the elbow plot for blobs. Question: where does the curve bend? What to see: the best inertia drops fast up to (2539, 1066, 591, 180) and then slowly (158, 142, …). The bend, the elbow, is at the true . Now pick rings or elongated: the curve has no clear elbow. Switch the method to Gaussian mixture and read the BIC chart: for blobs and elongated the minimum is at the true .
- Long clusters. In the second figure, pick elongated and move length / width from 1 to 7. Question: at what point does k-means start to cut across the clusters? What to see: the ARI of k-means falls from to about near a ratio of , while the mixture stays near . At the default setting k-means puts 70 points in the wrong cluster, but its inertia () is lower than the inertia of the true clusters (). k-means is not stuck here: its objective prefers the wrong answer. In the first figure, choose elongated, Gaussian mixture, and spherical covariance: with circles only, EM fails like k-means.
- One big cluster, two small ones. Pick uneven sizes. Question: which points does k-means give to the wrong cluster? What to see: the outer points of the big cluster, on the side of the small clusters. The true sizes are 180, 30 and 30; k-means finds about 160, 36 and 44. The mixture learns the weights and a large covariance for the big cluster, and gets every point right. On the chart, the ARI of k-means falls when the spread ratio grows above about 3, while the ARI of the mixture stays near up to a ratio of about 5.5.
- Rings. Pick rings. Question: can either method separate the inner ring from the outer one? What to see: no; both ARIs stay near for every radius. The ARI of the mixture is even a little below : its clusters agree with the rings a little less than random groups would. A ring is not convex: the straight line between two of its points leaves the ring. A k-means region is always convex, and a Gaussian puts most of its mass near its centre, which here is in the middle of the other ring. In the first figure, the BIC of the mixture on rings keeps falling up to : the mixture covers each ring with several small Gaussians. That is a good model of the density, but not two clusters.
4. The math behind the figures #
k-means minimizes the inertia #
We have points and want clusters. k-means chooses centres and an assignment for each point that make the inertia (the within-cluster sum of squares) small:
Lloyd's algorithm (the usual k-means algorithm) changes one group of variables at a time:
- Assign step. Keep the centres fixed. Each term of is smallest when is the nearest centre: .
- Update step. Keep the assignment fixed. The sum of squares is a convex quadratic in ; its gradient is zero at the mean: , where is the number of points in cluster .
Each step minimizes over one group of variables, so never increases. There are only finitely many assignments, and none can repeat with a lower , so the algorithm stops after finitely many steps, when no point changes cluster. But it stops at a local minimum, which depends on the start. Finding the global minimum is NP-hard in general, so in practice we run k-means from several starts and keep the lowest .
Why the regions are polygons. A place is closer to than to when . Expand both sides; the terms cancel and we get a linear inequality:
So the border between two clusters is a straight line: the perpendicular bisector of the two centres. A Voronoi cell is an intersection of half-planes, so it is a convex polygon. This explains the failures in section 2: k-means cannot follow a ring (not convex), and it puts the border halfway between two centres even when one cluster is much wider than the other (uneven variance). For long clusters, a cut across them gives a lower than the true clusters, so the objective itself prefers the wrong answer.
Worked example (one dimension). Points with and start centres and .
- Assign: is closer to (distance ) than to (distance ); is closer to (distance ) than to (distance ). Clusters and , with .
- Update: the means are and ; now .
- Assign: is now closer to (distance ) than to (distance ). Clusters and , .
- Update: , , . The next assign step changes nothing, so k-means stops. The inertia went : down at every step.
Which statement about Lloyd's algorithm is true?
Both steps minimize over one group of variables, so neither can increase it, and the assign step usually lowers it too (in the worked example, from to ). But "never increases" does not mean "finds the global minimum": in experiment 2, a random start stops at while the best clustering has .
k-means++: a better start #
k-means++ (Arthur and Vassilvitskii, 2007) chooses the start centres among the data points. The first centre is a uniformly random point. Each next centre is point with probability
where is the distance from to the nearest centre chosen so far. This is sampling: points far from all centres, probably in a cluster without a centre yet, are likely to be picked. Points that already have a centre nearby are rarely picked. The authors proved that the start alone already has expected inertia at most times the optimal ; Lloyd's steps only lower it further. It is the default start in scikit-learn.
In the worked example with first centre , the squared distances are with sum , so the second centre is with probability .
Three points on a line: , and . k-means++ picked as the first centre. What is the probability that the second centre is ?
The squared distances to the nearest centre are , and , with sum , so . Using distances in place of squared distances gives . k-means++ is random, not "farthest point first": the point still has a chance of . The randomness makes it robust to a single outlier far away.
Gaussian mixtures #
A Gaussian mixture says that each point was made in two steps: first pick a cluster with probabilities (the mixing weights, , ), then draw from the Gaussian of that cluster, . The cluster is a hidden (latent) variable. The density of one point is
and we fit by maximizing the log-likelihood . The sum inside the logarithm couples all clusters, so there is no closed-form maximum. If we knew the cluster of every point, the problem would be easy: fit one Gaussian per cluster. EM uses this idea with soft guesses of the clusters.
E-step (expectation). Compute the responsibilities: the posterior probability that point came from cluster , by Bayes' rule with the current parameters,
Each row sums to . These are the colour mixes in the figure.
M-step (maximization). Fit each Gaussian to all points, each point weighted by its responsibility. With (the "soft size" of cluster ):
With spherical covariance the widget uses with .
EM never decreases the log-likelihood, just as Lloyd's algorithm never increases . The widget stops when changes by less than . Like k-means, EM finds a local maximum that depends on the start; the widget starts the means with k-means++ or random points, each covariance as a circle, and .
Why EM never decreases the log-likelihood
For any distribution over the cluster of point , the log-likelihood of that point splits into two parts (see the ELBO lesson):
The E-step sets , which is . Then the KL term is , so . The M-step maximizes over ; for Gaussians the maximizer is exactly the formulas above (set the gradients to zero; for use a Lagrange multiplier for ). So
The first inequality holds because KL is never negative (Jensen's inequality).
One dimension, two Gaussians with , , and . What is the responsibility of the first Gaussian for the point ?
. The weights and the normalizing constants cancel because they are equal. The answer is the hard assignment of k-means; EM keeps a chance that the point came from the second Gaussian.
What EM adds to k-means #
- Shape and orientation. Each cluster has its own covariance , an ellipse. The border between two Gaussians is where : a quadratic curve (a conic), not only a straight line. This fixes the long clusters.
- Sizes. The weights and the covariances let a wide, large cluster win the points far from its centre. This fixes the uneven clusters.
- Soft assignments. A point between two clusters gets two responsibilities near , not a forced choice, so we can see which assignments are uncertain.
- A probability model. is a density: it gives a likelihood for choosing (below), and a low flags an unusual point (anomaly detection).
k-means is a limit of EM. Fix all covariances to and all weights to , and let . Then goes to for the nearest centre and for the others: the E-step becomes the assign step, and the M-step for becomes the update step. So k-means is "hard EM" for round clusters of the same size and weight, and this is exactly the case where it works well.
What EM does not fix: a Gaussian is still one blob around one centre, so a ring stays out of reach. Methods built on neighbours, such as spectral clustering, DBSCAN, or a kernel version of k-means, can follow such shapes.
A trap: the likelihood has no maximum. Put one mean exactly on a data point, , with
. The term grows without limit
as , and so does . A Gaussian that sits on one point (or on points along a line) can
collapse. Practical code adds a small ridge to each covariance (scikit-learn adds , called
reg_covar), uses a prior, or restarts. The widget adds too, and it stops with a message when a
covariance becomes almost singular. To see it: press Clear all, set Click to adds a cloud and click
once, then set it to adds a point and click once far away. With and Gaussian mixture, press
To the end. k-means++ gives the lonely point its own Gaussian, and that Gaussian shrinks onto it.
Choosing the number of clusters #
The inertia always goes down when grows (with it is ), so we cannot simply minimize it.
- Elbow plot. Plot the best for each and look for the bend: after it, more clusters reduce only a little. This works for well-separated blobs and often gives no clear answer otherwise.
- BIC. For a probability model, the Bayesian information criterion trades fit against size. Here are the fitted parameters and is the number of free parameters. A 2D mixture with full covariances has ( weights, numbers per mean, per covariance). Smaller is better. On blobs the BIC is smallest at .
- Other tools: the silhouette score, the log-likelihood on held-out data, and, most important, whether the clusters are useful for the task.
Measuring the result. When the true groups are known (as in the second figure), the adjusted Rand index compares two clusterings: it counts the pairs of points that are put together or apart in both, and corrects for the agreement expected by chance. It is for identical clusterings (up to renaming the clusters) and about for random ones.
5. Related lessons #
- ML Fundamentals: the track has a full lesson on clustering, Gaussian mixtures and EM, with anomaly detection and hierarchical clustering.
- The ELBO: variational inference, VAEs and importance-weighted bounds: EM as coordinate ascent on the ELBO, and how VAEs replace the exact E-step by a network.
- Jensen's inequality and the KL divergence: the inequality behind the EM guarantee.
- Positive definite matrices and Cholesky: covariance matrices and their ellipses.
- PCA as SVD of centered data: the axes of a covariance ellipse are its eigenvectors.
- Gaussian integrals and Laplace's method: working with the multivariate Gaussian.
- Nonconvex landscapes: local minima, the same problem k-means and EM have.
- Probability and Statistics: maximum likelihood, Bayes' rule and latent variables.
- Generative models: from mixtures of Gaussians to VAEs and diffusion models.