2.6 k-means, GMMs and EM
1. Learn
Section titled “1. Learn”- Stanford CS229 main notes (Ng, Ma)Part IV unsupervised learning: k-means clustering, mixtures of Gaussians and the EM algorithm
- Mathematics for Machine Learning (Deisenroth, Faisal, Ong)chapter 11 Density Estimation with Gaussian Mixture Models (pp. 348–369)
2. Bridge
Section titled “2. Bridge”Everything so far was supervised: every input came with a target. Here there are no labels, and the job is to find structure, namely groups, in the inputs alone (CS229 notes, Part IV). It is also your first latent-variable model, the idea that returns as the VAE and diffusion models in Part 6.
k-means picks centroids and minimises the distortion over both the assignments and the centroids. Optimising both at once is hard, so it alternates: assign each point to its nearest centroid (best for fixed ), then move each centroid to its points’ mean (best for fixed ). Neither move can raise , so it converges, but only to a local minimum that depends on the start (CS229 notes, k-means; MML only mentions it, in §11.5 Further Reading).
Gaussian mixtures make this probabilistic. Each point is generated by first picking a hidden component with probability , then drawing . The likelihood of a point sums over the component it might have come from: (MML §11.1). That sum inside the log has no closed-form maximiser.
EM gets around it the same way k-means does, by alternating. The E-step computes each point’s responsibilities by Bayes’ rule, a soft assignment. The M-step refits each component as if those soft assignments were known: weighted means, weighted covariances, and as the average responsibility. Each round can only raise the log likelihood (MML §11.3; CS229 notes, the EM algorithm). k-means is the limit of EM with equal, shrinking, spherical covariances, where responsibilities become hard 0/1 assignments.
In practice densities of far-away points underflow to 0, and is nan. Keep everything in log space and normalise with logsumexp, which subtracts the maximum before exponentiating, the same trick as log-softmax in 2.4 (SciPy, logsumexp).
3. Explore
Section titled “3. Explore”Implement k-means, then EM for a Gaussian mixture, with log densities, logsumexp and stable responsibilities. The tests check the M-step against weighted NumPy statistics, put points hundreds of units away, and require EM to recover the three true means of a synthetic mixture.
stubs/m2_6_em.pyLoading starter file…
Prefer your own editor? Edit exercises/stubs/m2_6_em.py and run mlc check 2.6. The tests are identical; import the results on the progress page.
Locally: mlc check 2.6.
5. Check
Section titled “5. Check”- not yet: All tests pass (0/?)
- not yet: Checkpoint quiz ≥ 80%
Learner log: time spent and points of confusion
Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.