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.
import%20marimo%20as%20mo%0Aimport%20numpy%20as%20np%0Aimport%20matplotlib.pyplot%20as%20plt%0A%0A_g%20%3D%20np.random.default_rng(0)%0Ax%20%3D%20np.concatenate(%5B_g.normal(0.0%2C%201.0%2C%20120)%2C%20_g.normal(4.0%2C%200.8%2C%2080)%5D)%0An%20%3D%20len(x)%0A%0Adef%20pdf(z%2C%20mu%2C%20sig)%3A%0A%20%20%20%20return%20np.exp(-0.5%20*%20((z%5B%3A%2C%20None%5D%20-%20mu)%20%2F%20sig)%20**%202)%20%2F%20(sig%20*%20np.sqrt(2%20*%20np.pi))%0A%0Adef%20loglik(p)%3A%0A%20%20%20%20return%20float(np.log((p%5B%22pi%22%5D%20*%20pdf(x%2C%20p%5B%22mu%22%5D%2C%20p%5B%22sig%22%5D)).sum(1)).sum())%0A%0Adef%20e_step(p%2C%20mode)%3A%0A%20%20%20%20dens%20%3D%20p%5B%22pi%22%5D%20*%20pdf(x%2C%20p%5B%22mu%22%5D%2C%20p%5B%22sig%22%5D)%0A%20%20%20%20r%20%3D%20dens%20%2F%20dens.sum(1%2C%20keepdims%3DTrue)%0A%20%20%20%20if%20mode%20%3D%3D%20%22CEM%22%3A%0A%20%20%20%20%20%20%20%20r%20%3D%20np.eye(2)%5Br.argmax(1)%5D%0A%20%20%20%20elif%20mode%20%3D%3D%20%22SEM%22%3A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20sample%20z_i%20~%20Categorical(r_i)%2C%20seeded%20by%20the%20draw%20counter%0A%20%20%20%20%20%20%20%20r%20%3D%20np.eye(2)%5B(np.random.default_rng(100%20%2B%20p%5B%22draw%22%5D).random(n)%20%3E%20r%5B%3A%2C%200%5D).astype(int)%5D%0A%20%20%20%20return%20%7B**p%2C%20%22r%22%3A%20r%2C%20%22fresh%22%3A%20True%2C%20%22draw%22%3A%20p%5B%22draw%22%5D%20%2B%201%7D%0A%0Adef%20m_step(p)%3A%0A%20%20%20%20r%20%3D%20p%5B%22r%22%5D%3B%20nk%20%3D%20r.sum(0)%3B%20ok%20%3D%20nk%20%3E%201e-9%3B%20nk%20%3D%20np.where(ok%2C%20nk%2C%201.0)%0A%20%20%20%20mu%20%3D%20np.where(ok%2C%20(r%20*%20x%5B%3A%2C%20None%5D).sum(0)%20%2F%20nk%2C%20p%5B%22mu%22%5D)%0A%20%20%20%20sig%20%3D%20np.where(ok%2C%20np.maximum(np.sqrt((r%20*%20(x%5B%3A%2C%20None%5D%20-%20mu)%20**%202).sum(0)%20%2F%20nk)%2C%200.05)%2C%20p%5B%22sig%22%5D)%0A%20%20%20%20q%20%3D%20%7B**p%2C%20%22mu%22%3A%20mu%2C%20%22sig%22%3A%20sig%2C%20%22pi%22%3A%20np.where(ok%2C%20nk%20%2F%20n%2C%201e-9)%2C%20%22fresh%22%3A%20False%2C%20%22it%22%3A%20p%5B%22it%22%5D%20%2B%201%7D%0A%20%20%20%20return%20%7B**q%2C%20%22ll%22%3A%20p%5B%22ll%22%5D%20%2B%20%5Bloglik(q)%5D%7D%0A%0Adef%20step(p%2C%20mode%2C%20kind)%3A%0A%20%20%20%20if%20kind%20%3D%3D%20%22run%22%3A%0A%20%20%20%20%20%20%20%20for%20_%20in%20range(10)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20p%20%3D%20m_step(e_step(p%2C%20mode))%0A%20%20%20%20%20%20%20%20return%20p%0A%20%20%20%20if%20kind%20%3D%3D%20%22E%22%20or%20not%20p%5B%22fresh%22%5D%3A%0A%20%20%20%20%20%20%20%20p%20%3D%20e_step(p%2C%20mode)%0A%20%20%20%20return%20m_step(p)%20if%20kind%20%3D%3D%20%22M%22%20else%20p%0A%0AINIT%20%3D%20%7B%22mu%22%3A%20np.array(%5B1.5%2C%202.5%5D)%2C%20%22sig%22%3A%20np.array(%5B1.5%2C%201.5%5D)%2C%20%22pi%22%3A%20np.array(%5B0.5%2C%200.5%5D)%2C%0A%20%20%20%20%20%20%20%20%22r%22%3A%20None%2C%20%22fresh%22%3A%20False%2C%20%22it%22%3A%200%2C%20%22draw%22%3A%200%7D%0AINIT%5B%22ll%22%5D%20%3D%20%5Bloglik(INIT)%5D%0Aget_s%2C%20set_s%20%3D%20mo.state(INIT)
mode%20%3D%20mo.ui.dropdown(%5B%22EM%22%2C%20%22CEM%22%2C%20%22SEM%22%5D%2C%20value%3D%22EM%22%2C%20label%3D%22algorithm%22%2C%20on_change%3Dlambda%20_%3A%20set_s(INIT))%0Ab_e%20%3D%20mo.ui.button(label%3D%22E-step%22%2C%20on_click%3Dlambda%20_%3A%20set_s(lambda%20p%3A%20step(p%2C%20mode.value%2C%20%22E%22)))%0Ab_m%20%3D%20mo.ui.button(label%3D%22M-step%22%2C%20on_click%3Dlambda%20_%3A%20set_s(lambda%20p%3A%20step(p%2C%20mode.value%2C%20%22M%22)))%0Ab_run%20%3D%20mo.ui.button(label%3D%22Run%2010%22%2C%20on_click%3Dlambda%20_%3A%20set_s(lambda%20p%3A%20step(p%2C%20mode.value%2C%20%22run%22)))%0Ab_reset%20%3D%20mo.ui.button(label%3D%22Reset%22%2C%20on_click%3Dlambda%20_%3A%20set_s(INIT))%0Amo.hstack(%5Bmode%2C%20b_e%2C%20b_m%2C%20b_run%2C%20b_reset%5D%2C%20justify%3D%22start%22)
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.
_p%20%3D%20get_s()%0A_g%20%3D%20np.linspace(-4%2C%208%2C%20400)%0A_bins%20%3D%20np.linspace(-4%2C%208%2C%2041)%0Afig%2C%20(ax1%2C%20ax2)%20%3D%20plt.subplots(1%2C%202%2C%20figsize%3D(11%2C%204))%0Aif%20_p%5B%22r%22%5D%20is%20None%3A%0A%20%20%20%20ax1.hist(x%2C%20_bins%2C%20color%3D%220.7%22)%0Aelse%3A%0A%20%20%20%20ax1.hist(%5Bx%2C%20x%5D%2C%20_bins%2C%20weights%3D%5B_p%5B%22r%22%5D%5B%3A%2C%200%5D%2C%20_p%5B%22r%22%5D%5B%3A%2C%201%5D%5D%2C%20stacked%3DTrue%2C%20color%3D%5B%22%232a78d6%22%2C%20%22%23eb6834%22%5D)%0A_dens%20%3D%20_p%5B%22pi%22%5D%20*%20pdf(_g%2C%20_p%5B%22mu%22%5D%2C%20_p%5B%22sig%22%5D)%20*%20n%20*%20(_bins%5B1%5D%20-%20_bins%5B0%5D)%0Afor%20_k%2C%20_c%20in%20enumerate(%5B%22%232a78d6%22%2C%20%22%23eb6834%22%5D)%3A%0A%20%20%20%20ax1.plot(_g%2C%20_dens%5B%3A%2C%20_k%5D%2C%20%22--%22%2C%20color%3D_c)%0Aax1.plot(_g%2C%20_dens.sum(1)%2C%20color%3D%22k%22)%0Aax1.set_title(%22data%20coloured%20by%20responsibility%3B%20fitted%20densities%22)%0Aax2.plot(_p%5B%22ll%22%5D%2C%20%22o-%22%2C%20color%3D%22k%22)%0Aax2.set_xlabel(%22iteration%22)%3B%20ax2.set_ylabel(%22log-likelihood%22)%3B%20ax2.set_title(f%22log-likelihood%20trace%20(%7Bmode.value%7D)%22)%0Afig
_q%20%3D%20get_s()%0A_next%20%3D%20%22M-step%20(responsibilities%20are%20fresh)%22%20if%20_q%5B%22fresh%22%5D%20else%20%22E-step%22%0Amo.md(%22%7C%20%7C%20component%201%20%7C%20component%202%20%7C%5Cn%7C---%7C---%7C---%7C%5Cn%22%0A%20%20%20%20%20%20%2B%20f%22%7C%20%24%5C%5Cmu_k%24%20%7C%20%7B_q%5B'mu'%5D%5B0%5D%3A.2f%7D%20%7C%20%7B_q%5B'mu'%5D%5B1%5D%3A.2f%7D%20%7C%5Cn%7C%20%24%5C%5Csigma_k%24%20%7C%20%7B_q%5B'sig'%5D%5B0%5D%3A.2f%7D%20%7C%20%7B_q%5B'sig'%5D%5B1%5D%3A.2f%7D%20%7C%5Cn%22%0A%20%20%20%20%20%20%2B%20f%22%7C%20%24%5C%5Cpi_k%24%20%7C%20%7B_q%5B'pi'%5D%5B0%5D%3A.2f%7D%20%7C%20%7B_q%5B'pi'%5D%5B1%5D%3A.2f%7D%20%7C%5Cn%5Cn%22%0A%20%20%20%20%20%20%2B%20f%22Iterations%3A%20**%7B_q%5B'it'%5D%7D**%3B%20log-likelihood%20**%7B_q%5B'll'%5D%5B-1%5D%3A.2f%7D**%3B%20next%20step%3A%20**%7B_next%7D**.%22)
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).