Skip to content

EM Step by Step

This demo takes a few seconds to load and runs entirely in your browser (NumPy and matplotlib via Pyodide; no tgmm or PyTorch is involved). It mirrors the E- and M-steps of GaussianMixture in one dimension, together with its algorithm='em' | 'cem' | 'sem' options (see Fitting algorithms).

Two Gaussian components are fitted to 200 fixed points, starting from deliberately bad means. E-step computes the responsibilities

\[r_{ik}=\frac{\pi_k\,\mathcal N(x_i\mid\mu_k,\sigma_k^2)}{\sum_j\pi_j\,\mathcal N(x_i\mid\mu_j,\sigma_j^2)},\]

and M-step re-estimates the parameters from them, with \(n_k=\sum_i r_{ik}\):

\[\pi_k=\frac{n_k}{n},\qquad \mu_k=\frac{1}{n_k}\sum_i r_{ik}x_i,\qquad \sigma_k^2=\frac{1}{n_k}\sum_i r_{ik}(x_i-\mu_k)^2.\]

The algorithms differ only in the E-step's output: EM keeps the soft \(r_{ik}\), CEM replaces them by the hard \(\arg\max\) assignment, SEM samples each assignment from \(r_{i\cdot}\) (seeded, so the page is reproducible). The M-step is applied to whatever the E-step produced.

Changing the algorithm resets the fit. M-step first runs an E-step if the responsibilities are stale, so E then M is one EM iteration, and Run 10 does ten.

What to look for: with EM the log-likelihood never decreases, and from this symmetric-ish start it first crawls along a plateau before climbing; CEM jumps to a (crisp, hard-partition) fixed point within a step or two and then stops changing; SEM keeps jittering around a stationary level because each assignment is resampled (that is why tgmm never declares SEM converged and offers 'saem' for a convergent variant).