Skip to content

2.6 k-means, GMMs and EM

ready≈ 8.5 hoursNeeds: 1.4, 2.1
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (k-means / EM stepper)
  4. 4 Do
  5. 5 Check

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 kk centroids and minimises the distortion J=∑i∥xi−μci∥2J = \sum_i \lVert\mathbf{x}_i - \boldsymbol\mu_{c_i}\rVert^2 over both the assignments cic_i and the centroids. Optimising both at once is hard, so it alternates: assign each point to its nearest centroid (best cc for fixed μ\boldsymbol\mu), then move each centroid to its points’ mean (best μ\boldsymbol\mu for fixed cc). Neither move can raise JJ, 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 zz with probability πz\pi_z, then drawing x∼N(μz,Σz)\mathbf{x}\sim\mathcal{N}(\boldsymbol\mu_z, \boldsymbol\Sigma_z). The likelihood of a point sums over the component it might have come from: p(x)=∑jπj N(x∣μj,Σj)p(\mathbf{x}) = \sum_j \pi_j\,\mathcal{N}(\mathbf{x}\mid\boldsymbol\mu_j,\boldsymbol\Sigma_j) (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 rij=p(z=j∣xi)r_{ij} = p(z = j \mid \mathbf{x}_i) by Bayes’ rule, a soft assignment. The M-step refits each component as if those soft assignments were known: weighted means, weighted covariances, and πj\pi_j 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 0/00/0 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).

M-step updates for a Gaussian mixturestep 1 of 4
  1. Q(θ)=∑i∑jrij[log⁡πj+log⁡N(xi∣μj,Σj)]Q(\boldsymbol\theta) = \sum_i\sum_j r_{ij}\left[\log\pi_j + \log\mathcal{N}(\mathbf{x}_i\mid\boldsymbol\mu_j, \boldsymbol\Sigma_j)\right]

k-means / EM stepper

Clustering, GMM ellipses, local optima

Static view on small screens. Open this page on a laptop to interact.

iteration 0 next: Assign points

k-means alternates two moves that each lower the distortion: give every point to its nearest centroid, then move every centroid to the mean of its points. Try "New starting point" a few times: some starts end in a worse local optimum.

Points from three Gaussian blobs. In k-means mode, colours are hard assignments and crosses are centroids. In EM mode, colours blend by responsibility and ellipses show each component’s 1σ and 2σ contours. Buttons perform the next half-step (assign or E-step, update or M-step), run 20 iterations, or restart from a new initialisation. An inset plots the distortion or the log likelihood over iterations. Keyboard: Tab to the buttons; the first one performs the next half-step.

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.

EM for a Gaussian mixture stubs/m2_6_em.py

Loading 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.

Hints · kmeans 0/3 revealed
Hints · gmm_e_step 0/3 revealed
Hints · gmm_m_step 0/3 revealed

Locally: mlc check 2.6.

1. What does the E-step compute?
2. Why can EM or k-means end at different answers from different starts?
3. k-means is EM for a Gaussian mixture with…
4. A point lies 200 units from every component. Computing responsibilities directly as p_j / Σ p gives…
5. Across EM iterations, the log likelihood of the data…
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
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.