The EM Algorithm
The Expectation-Maximization (EM) algorithm is an iterative optimization procedure for finding maximum likelihood estimates of parameters in statistical models where some data is unobserved (latent). It matters in modern AI because it underlies or motivates a vast family of models — Gaussian Mixture Models, Hidden Markov Models, Latent Dirichlet Allocation, and even variational autoencoders trace their theoretical roots to EM. The remarkable fact: EM is guaranteed to never decrease the likelihood at each iteration, yet it can converge to a local maximum while the algorithm itself has no idea it is stuck there.
The fundamental obstacle in latent variable models is that the likelihood function couples the observed data and the missing data in a way that makes direct optimization intractable. EM sidesteps this by alternating between two steps: first pretend you know the parameters and use them to form a probability distribution over the missing data (E-step), then treat that distribution as fixed and optimize the parameters as if the missing data were real (M-step). Each full cycle is guaranteed to move uphill on the true log-likelihood surface. The "aha moment" is realizing that you are not optimizing the hard objective directly — you are iteratively constructing and then maximizing a tight lower bound to it.
How It Works
Setting Up the Problem
Suppose we have observed data and postulate that each was generated alongside an unobserved latent variable drawn from some distribution. The complete-data log-likelihood would be easy to optimize if we knew , but we do not. The observed-data log-likelihood is:
Explanation: The log-likelihood of the observed data requires summing (or integrating) over all possible configurations of the latent variables, which moves the sum inside the log and makes direct maximization analytically painful. Symbols: is the vector of all model parameters; is the joint density of observed and latent data; the sum becomes an integral for continuous latents.
The EM Lower Bound (ELBO)
Introduce any distribution over latent variables. By Jensen's inequality applied to the concave log function:
Explanation: This is the Evidence Lower BOund (ELBO); the gap between the true log-likelihood and this bound is exactly the KL divergence from to the true posterior . Symbols: is the lower bound; is a free variational distribution we choose; the ratio inside the log separates into the complete-data log-likelihood minus the entropy of .
E-Step: Tighten the Bound
Set , the posterior over latents given current parameters. This makes the KL gap zero, so the bound touches the true likelihood. Define the Q-function:
Explanation: The Q-function is simply the expected complete-data log-likelihood, where the expectation is taken with respect to the posterior distribution of the latent variables computed under the old parameters. Symbols: denotes expectation over the posterior of ; is held fixed during this step; is the free variable we will optimize in M-step.
M-Step: Maximize the Bound
Explanation: With the posterior over latents fixed from the E-step, we maximize the expected complete-data log-likelihood over the model parameters, which is typically an analytically tractable problem.
Convergence Guarantee
The monotonic non-decrease property follows directly from the bound structure:
Explanation: Each EM iteration increases (or leaves unchanged) the true observed-data log-likelihood because the M-step increases Q, and Q lower-bounds ℓ tightly at the current parameter value. ---
Worked Example: Gaussian Mixture Models in PyTorch
A Gaussian Mixture Model (GMM) with components is one of the canonical EM applications. Each data point is assumed drawn from one of Gaussians with mixing weights , means , and covariances . ```python import torch import torch.nn.functional as F class GMMwithEM: def __init__(self, K: int, D: int, n_iter: int = 100): self.K, self.D, self.n_iter = K, D, n_iter
# Random initialisation — run multiple times! self.pi = torch.ones(K) / K # mixing weights self.mu = torch.randn(K, D) # means self.Sigma = torch.stack([torch.eye(D)] * K) # covariances def _log_gaussian(self, X: torch.Tensor) -> torch.Tensor: """Log N(x | mu_k, Sigma_k) for every (n, k) pair. Returns [N, K].""" N = X.shape[0] log_probs = torch.zeros(N, self.K) for k in range(self.K): dist = torch.distributions.MultivariateNormal( self.mu[k], covariance_matrix=self.Sigma[k] ) log_probs[:, k] = dist.log_prob(X) return log_probs # [N, K] def e_step(self, X: torch.Tensor) -> torch.Tensor: """Compute responsibilities r[n, k] = p(z=k | x_n, theta_old).""" log_probs = self._log_gaussian(X) # [N, K] log_weighted = log_probs + torch.log(self.pi).unsqueeze(0) # [N, K]
# Numerically stable softmax over K log_r = log_weighted - torch.logsumexp(log_weighted, dim=1, keepdim=True) return log_r.exp() # responsibilities [N, K] def m_step(self, X: torch.Tensor, r: torch.Tensor) -> None: """Update pi, mu, Sigma from responsibilities.""" N_k = r.sum(dim=0) # effective counts [K] self.pi = N_k / N_k.sum() self.mu = (r.T @ X) / N_k.unsqueeze(1) # [K, D] for k in range(self.K): diff = X - self.mu[k] # [N, D] self.Sigma[k] = (r[:, k].unsqueeze(1) diff).T @ diff / N_k[k] self.Sigma[k] += 1e-6 torch.eye(self.D) # numerical stability def fit(self, X: torch.Tensor) -> list[float]: log_likelihoods = [] for _ in range(self.n_iter): r = self.e_step(X) self.m_step(X, r)
# Track observed log-likelihood log_probs = self._log_gaussian(X) + torch.log(self.pi) ll = torch.logsumexp(log_probs, dim=1).sum().item() log_likelihoods.append(ll) return log_likelihoods
# Usage torch.manual_seed(0) X = torch.cat([torch.randn(200, 2) + t for t in [2., -2.]]) # two clusters model = GMMwithEM(K=2, D=2, n_iter=50) lls = model.fit(X) print(f"Final log-likelihood: {lls[-1]:.2f}")
# ll should increase monotonically — assert this during debugging! assert all(lls[i+1] >= lls[i] - 1e-4 for i in range(len(lls)-1)), "EM violated monotonicity!" ```
Arthur Dempster is a statistician at Harvard who spent his career developing foundational frameworks for statistical inference under uncertainty. Together with Nan Laird and Donald Rubin, he formalized and named the EM algorithm in the landmark 1977 paper "Maximum Likelihood from Incomplete Data via the EM Algorithm" in the Journal of the Royal Statistical Society. A surprising historical note: many special cases of EM had been independently derived in the 1950s–60s (for HMMs, factor analysis, and mixture models) without anyone recognizing the unifying principle — Dempster, Laird, and Rubin's contribution was the unification, the proof of monotone convergence, and the memorable two-letter name.
Nan Laird is a biostatistician at Harvard School of Public Health best known for her work on longitudinal data analysis and mixed models. In the 1977 EM paper she was responsible for much of the rigorous statistical analysis, including the proof that EM monotonically non-decreases the observed-data likelihood and a careful treatment of the convergence rate. A surprising personal fact: Laird went on to apply EM-type ideas extensively in epidemiological genetics and is now perhaps even better known for her work on genome-wide association studies than for her foundational contribution to the most widely-used unsupervised learning algorithm in classical ML.
Intuition
Imagine you are a chef trying to perfect a secret spice blend, but you cannot directly observe which spice creates which flavor note — the spices interact. The EM approach is: given your current best guess of the blend, assign partial credit to each spice for each flavor you taste (E-step: "I think 70% of this sweetness comes from cinnamon, 30% from cardamom"). Then, holding those credit assignments fixed, adjust the actual quantities of each spice to best explain the flavors (M-step: "Given that credit assignment, use more cinnamon"). Repeat. Each round you explain the dish slightly better. You are never solving the hard problem — "which spice caused what?" — you are sidestepping it by working with soft probabilistic assignments instead of hard ones. The algorithm can still get stuck if your initial blend is wildly wrong (a local optimum), which is why you always try multiple starting blends.
Historical Development
Origins · 1 minhow this was discovered
Why It Matters
Prerequisites
What This Leads To
See Also
Maximum Likelihood Estimation · Gaussian Mixture Models · Variational Inference · Hidden Markov Models · Jensen's Inequality and Convexity