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 core insight

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 X={x1,…,xN}\mathbf{X} = \{x_1, \ldots, x_N\} and postulate that each xix_i was generated alongside an unobserved latent variable ziz_i drawn from some distribution. The complete-data log-likelihood would be easy to optimize if we knew Z={z1,…,zN}\mathbf{Z} = \{z_1, \ldots, z_N\}, but we do not. The observed-data log-likelihood is:

1
ℓ(θ)=log⁡p(X∣θ)=log⁡∑Zp(X,Z∣θ)\quad \ell(\theta) = \log p(\mathbf{X} \mid \theta) = \log \sum_{\mathbf{Z}} p(\mathbf{X}, \mathbf{Z} \mid \theta)

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: θ\theta is the vector of all model parameters; p(X,Z∣θ)p(\mathbf{X}, \mathbf{Z} \mid \theta) 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 q(Z)q(\mathbf{Z}) over latent variables. By Jensen's inequality applied to the concave log function:

2
ℓ(θ)≥∑Zq(Z)log⁡p(X,Z∣θ)q(Z)  =  L(q,θ)\quad \ell(\theta) \geq \sum_{\mathbf{Z}} q(\mathbf{Z}) \log \frac{p(\mathbf{X}, \mathbf{Z} \mid \theta)}{q(\mathbf{Z})} \;=\; \mathcal{L}(q, \theta)

Explanation: This is the Evidence Lower BOund (ELBO); the gap between the true log-likelihood and this bound is exactly the KL divergence from q(Z)q(\mathbf{Z}) to the true posterior p(Z∣X,θ)p(\mathbf{Z} \mid \mathbf{X}, \theta). Symbols: L(q,θ)\mathcal{L}(q, \theta) is the lower bound; q(Z)q(\mathbf{Z}) is a free variational distribution we choose; the ratio inside the log separates into the complete-data log-likelihood minus the entropy of qq.

E-Step: Tighten the Bound

Set q(Z)=p(Z∣X,θold)q(\mathbf{Z}) = p(\mathbf{Z} \mid \mathbf{X}, \theta^{\text{old}}), the posterior over latents given current parameters. This makes the KL gap zero, so the bound touches the true likelihood. Define the Q-function:

3
Q(θ,θold)=EZ∣X,θold ⁣[log⁡p(X,Z∣θ)]\quad Q(\theta, \theta^{\text{old}}) = \mathbb{E}_{\mathbf{Z} \mid \mathbf{X}, \theta^{\text{old}}}\!\left[\log p(\mathbf{X}, \mathbf{Z} \mid \theta)\right]

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: EZ∣X,θold[⋅]\mathbb{E}_{\mathbf{Z} \mid \mathbf{X}, \theta^{\text{old}}}[\cdot] denotes expectation over the posterior of Z\mathbf{Z}; θold\theta^{\text{old}} is held fixed during this step; θ\theta is the free variable we will optimize in M-step.

M-Step: Maximize the Bound

4
θnew=arg⁡max⁡θ  Q(θ,θold)\quad \theta^{\text{new}} = \arg\max_{\theta}\; Q(\theta, \theta^{\text{old}})

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:

5
ℓ(θnew)≥Q(θnew,θold)≥Q(θold,θold)=ℓ(θold)\quad \ell(\theta^{\text{new}}) \geq Q(\theta^{\text{new}}, \theta^{\text{old}}) \geq Q(\theta^{\text{old}}, \theta^{\text{old}}) = \ell(\theta^{\text{old}})

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 KK components is one of the canonical EM applications. Each data point xi∈RDx_i \in \mathbb{R}^D is assumed drawn from one of KK Gaussians with mixing weights πk\pi_k, means μk\mu_k, and covariances Σk\Sigma_k. ```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!" ```

researcher · Arthur Dempster | b. 1929 | Co-originator of the EM Algorithm

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.

researcher · Nan Laird | b. 1943 | Convergence Analysis and Statistical Rigor

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.

Figure
EM Algorithm Iteration Flow
EM Algorithm — Iteration Cycle Initialise θ⁽⁰⁾ randomly E-Step Compute Q(θ, θᵒˡᵈ) M-Step Maximise Q → θⁿᵉʷ Converged ? No — θᵒˡᵈ ← θⁿᵉʷ, repeat Yes → θ* Guarantee: ℓ(θⁿᵉʷ) ≥ ℓ(θᵒˡᵈ) at every iteration — log-likelihood is monotonically non-decreasing
Figure
ELBO Geometry — Bound Tightening
EM as Iterative Lower-Bound Maximisation θ ℓ(θ) ℓ(θ) true log-likelihood 𝓛(q¹,θ) — bound at θ¹ θ¹ 𝓛(q²,θ) — bound at θ² θ² ℓ increases KL gap=0 at θᵒˡᵈ

Intuition

The Mental Model

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
History
1950
Baum and colleagues begin work on what will become the forward-backward algorithm — an efficient E-step for Hidden Markov Models — though the unifying EM framework does not yet exist.
1958
Hartley publishes "Maximum Likelihood Estimation from Incomplete Data", one of the earliest papers identifying the E-step / M-step structure informally, for specific exponential family models.
1970
Baum, Petrie, Soules, and Weiss publish the full Baum-Welch algorithm for HMM parameter estimation — a specific instantiation of EM — predating the general framework by seven years.
1977
Dempster, Laird, and Rubin publish "Maximum Likelihood from Incomplete Data via the EM Algorithm" in JRSS-B, unifying dozens of ad-hoc algorithms, naming the steps E and M, and proving the monotone convergence theorem. This becomes one of the most cited papers in statistics.
1983
Wu publishes a rigorous convergence analysis of EM, proving it converges to a stationary point and characterizing the convergence rate as linear (not superlinear), explaining why EM can be slow near a maximum.
1993
Fessler and Hero introduce Space-Alternating Generalized EM (SAGE), a variant that updates parameters one at a time rather than jointly, accelerating convergence in large-scale imaging problems.
1999
Neal and Hinton recast EM as coordinate ascent on the ELBO in their paper "A view of the EM algorithm that justifies incremental, sparse, and other variants", directly foreshadowing variational inference and VAEs.
2004
Blei, Ng, and Jordan introduce Latent Dirichlet Allocation and a variational EM procedure to train it, making EM-style inference central to topic modeling at web scale.
2013
Kingma and Welling introduce the Variational Autoencoder, which replaces the exact E-step with a learned amortized approximate posterior — this is EM generalized to deep neural networks.

Why It Matters

Real-World Impact
Gaussian Mixture Models (scikit-learn `GaussianMixture`)EM is the exact training algorithm; the sklearn implementation uses the full covariance EM update derived above, with multiple random restarts controlled by `n_init` to mitigate local optima — used widely for density estimation, anomaly detection, and soft clustering in production systems.
Hidden Markov Models for Speech RecognitionThe Baum-Welch algorithm is EM applied to HMMs; all classical automatic speech recognition systems (including early versions of Siri and Google Voice) trained acoustic models with Baum-Welch EM over tens of millions of speech frames before deep learning displaced it.
Expectation Propagation in Bayesian InferenceEP generalizes the E-step to approximate non-conjugate posteriors by moment matching — used in Microsoft's TrueSkill player ranking system (Xbox Live) to estimate skill ratings from win/loss outcomes with uncertainty.
Latent Dirichlet Allocation (topic modeling)Training LDA uses variational EM where the E-step fits a per-document variational posterior and the M-step updates global topic-word distributions; deployed by Google, Twitter, and the New York Times for content recommendation and news clustering.
EM for Missing Data ImputationMICE (Multiple Imputation by Chained Equations) and EM-based imputation are standard preprocessing steps in clinical ML pipelines where patient records have structured missingness — used in EHR modeling at scale.
Variational Autoencoders (VAEs)The VAE training objective is the ELBO from equation [2], with the E-step approximated by an encoder network and the M-step approximated by gradient ascent on the decoder — this is the direct deep-learning descendant of EM, central to image generation, molecular design, and representation learning.
K-Means as a Degenerate EMK-means is precisely EM on a GMM where covariances are fixed as σ2I\sigma^2 I and σ→0\sigma \to 0, turning soft responsibilities into hard assignments; understanding this connection explains both why k-means works and why it fails when clusters are non-spherical.

Prerequisites

What This Leads To

See Also

Maximum Likelihood Estimation · Gaussian Mixture Models · Variational Inference · Hidden Markov Models · Jensen's Inequality and Convexity

Before this

Where this leads