The EM Algorithm
Suppose you measure the heights of 10,000 people but forget to record their sex. The histogram is visibly bimodal, yet you cannot simply fit one Gaussian. The data are a mixture of two populations. The label telling you which population each point came from is missing. This is the generic problem of learning with latent variables: a model that would be easy to fit if we could see the hidden labels, but hard to fit because we cannot. The Expectation-Maximization (EM) algorithm is the classical answer. It underlies an enormous share of unsupervised learning, from Gaussian Mixture Models to hidden Markov models to missing-data imputation. EM matters because "hard" maximum-likelihood problems with latent structure are everywhere in real systems. Examples include clustering customers into hidden segments, decoding noisy communication channels, filling in missing sensor readings, and training topic models over text corpora. In each case, the log-likelihood of the observed data alone is a messy, non-convex function of the parameters. It often involves a log of a sum. EM turns this into an easy iterative recipe. It alternates between guessing the hidden labels (softly, as probabilities) and then re-fitting the model as if those guesses were true counts. The deep reason EM works — and the reason it deserves a full article rather than a one-line trick — is that it is not really an ad hoc heuristic. It is coordinate ascent on a rigorous lower bound to the log-likelihood, the Evidence Lower Bound (ELBO). Every EM iteration provably never decreases the observed-data log-likelihood. This gives the algorithm a clean convergence guarantee, even though the overall optimization problem is non-convex. This article builds EM from first principles. It covers what latent variables and the ELBO are, and the precise E-step and M-step. It explains why the likelihood increases monotonically, and gives the exact time/space complexity for a Gaussian mixture. It also includes a full numerical trace, and the classic failure modes (singular covariances, bad local optima, label switching). It assumes familiarity with Gaussian Mixture Models and Density Estimation Fundamentals. It also sets up the ideas needed for Anomaly Detection Fundamentals, where mixture densities are used to flag low-probability points.
- EM fits models with latent variables by maximizing the observed-data likelihood indirectly, via a lower bound.
- The E-step computes the posterior distribution over hidden variables given current parameters (soft assignments).
- The M-step re-estimates parameters by maximizing the expected complete-data log-likelihood under that posterior.
- Each EM iteration is guaranteed to never decrease the observed log-likelihood — a provable monotonicity property.
- The bound being optimized is the ELBO; EM is coordinate ascent that alternates tightening the bound (E) and maximizing it (M).
- EM converges to a stationary point, not necessarily the global optimum — initialization and degeneracies matter a lot in practice.
EM replaces a hard maximum-likelihood problem with hidden variables by iteratively maximizing a tight lower bound on the log-likelihood, guaranteeing monotone improvement at every step.
The idea
A latent variable model assumes each observed data point is generated together with an unobserved variable (a cluster label, a hidden state, a missing feature). The joint density is , and the observed-data likelihood is obtained by marginalizing out :
For a -component Gaussian mixture, indicates which component generated , and . If we knew for every point, maximum likelihood estimation would be trivial: compute per-cluster means, covariances, and mixing weights in closed form. The difficulty is entirely due to the sum inside the logarithm of the log-likelihood,
which couples all components together and has no closed-form maximizer. EM sidesteps this by introducing, for each data point, a distribution over the hidden variable and using Jensen's inequality to build a lower bound on called the Evidence Lower Bound (ELBO):
The gap between the true log-likelihood and the ELBO is exactly the Kullback–Leibler divergence between and the true posterior :
This identity is the crux of the whole method. It says the bound is tight exactly when , and it is this fact that EM exploits by alternating two moves: set to the exact posterior (closing the gap — the E-step), then maximize the ELBO over with fixed (climbing the bound — the M-step). Because the ELBO touches at the current parameters after the E-step, any improvement of the ELBO in the M-step is an improvement (or at worst no change) of the true log-likelihood too.
How it works
E-step (Expectation). Fix the current parameters . For every data point , compute the posterior responsibility of each latent value :
For a Gaussian mixture, this is the familiar responsibility
No parameters are changed in this step; only beliefs about the hidden labels are updated. This closes the KL gap exactly (setting it to zero), so the ELBO now equals the true log-likelihood at .
M-step (Maximization). With fixed, maximize the ELBO over . Since does not depend on in this step, this reduces to maximizing the expected complete-data log-likelihood:
For a Gaussian mixture this maximization is closed-form: it is weighted maximum likelihood, where each point contributes to cluster with weight :
These two steps are repeated until the log-likelihood stops improving (by more than a tolerance) or a maximum number of iterations is reached. ``` ALGORITHM EM-for-GMM(X, K, tol, max_iter) Input: data X = {x_1, ..., x_N}, number of components K Output: parameters theta = {pi_k, mu_k, Sigma_k}_{k=1..K} Initialize pi_k, mu_k, Sigma_k for k = 1..K // e.g. via k-means++ seeding prev_ll <- -infinity repeat // ---- E-step: compute responsibilities ---- for i = 1..N: for k = 1..K: num[i][k] <- pi_k Gaussian(x_i | mu_k, Sigma_k) denom <- sum_k num[i][k] for k = 1..K: gamma[i][k] <- num[i][k] / denom // posterior p(z_i=k | x_i, theta) // ---- M-step: re-estimate parameters ---- for k = 1..K: N_k <- sum_i gamma[i][k] pi_k <- N_k / N mu_k <- (1 / N_k) sum_i gamma[i][k] x_i Sigma_k <- (1 / N_k) sum_i gamma[i][k] (x_i - mu_k)(x_i - mu_k)^T // ---- check convergence via observed log-likelihood ---- ll <- sum_i log( sum_k pi_k Gaussian(x_i | mu_k, Sigma_k) ) if |ll - prev_ll| < tol: break prev_ll <- ll until max_iter reached return theta ``` Two edge cases the pseudocode must handle in practice: (1) if for some component (an empty cluster), is undefined — guard by re-seeding that component or adding a small floor to ; (2) if a component collapses onto a single point, and the Gaussian density diverges — regularize by adding to every covariance estimate.
Complexity & correctness
Time complexity per iteration (Gaussian mixture, -dimensional data, components, points). The E-step evaluates Gaussian densities; each density evaluation costs for the Mahalanobis term when using a precomputed Cholesky factor of (or once per component per iteration to factor , amortized over the points). So the E-step costs
The M-step computes weighted sums for () and weighted outer products for (), giving
Total per iteration: , dominated by when , which is the typical regime. Space complexity is for the responsibility matrix (or if streamed one point at a time and parameters are accumulated online) plus for the covariances. The number of iterations to convergence is not bounded by the problem size alone — it depends on how close the initialization is to a stationary point — but each individual iteration is cheap and the iteration count is usually small (tens to low hundreds) in practice.
Correctness — the monotonicity theorem. The central claim is:
The proof follows directly from the ELBO decomposition above. Write, for any ,
At the start of iteration , the E-step sets , which makes the KL term exactly zero, so
The M-step then chooses , so in particular
Finally, because the ELBO is a lower bound for any (Jensen's inequality applied to the concave ), in particular for evaluated at the new parameters,
Chaining the two inequalities gives , proving monotone non-decrease. Since is bounded above for well-posed likelihood models (under regularity/regularization to avoid degenerate variance collapse), a monotone bounded sequence converges, so converges to some limit.
What this does not prove. Convergence of the likelihood sequence does not imply convergence to a global maximum, nor even that the parameter sequence converges (though under mild conditions it does, to a stationary point of ). EM is exactly coordinate ascent on the joint objective : the E-step is exact coordinate maximization over (closed form, since the optimal is just the posterior), and the M-step is exact or partial coordinate maximization over . Coordinate ascent on a function bounded above converges to a point where neither coordinate block can be locally improved — a stationary point, which for non-convex may be a local maximum or saddle. This is the fundamental tradeoff of EM: guaranteed monotonic progress, no guarantee of global optimality. In practice this is mitigated by multiple random restarts, sensible initialization (e.g. k-means++), and model-selection criteria like BIC to choose .
Worked example
Consider one-dimensional points, Gaussian components, and a deliberately asymmetric dataset so no accidental symmetry hides an error:
Initialize (deliberately imperfectly): , , , .
Iteration 1 — E-step. Using , compute unnormalized responsibilities and normalize:
| (×π=.5) | (×π=.5) | |||
|---|---|---|---|---|
| 1 | 0.0965 | 0.0000221 | 0.9998 | 0.0002 |
| 2 | 0.0997 | 0.0000866 | 0.9991 | 0.0009 |
| 3 | 0.0965 | 0.0003183 | 0.9967 | 0.0033 |
| 9 | 0.0000866 | 0.0965 | 0.0009 | 0.9991 |
| 10 | 0.0000221 | 0.0997 | 0.0002 | 0.9998 |
| 25 | ≈0 | ≈0 (tiny, ~) | ≈0.0002* | ≈0.9998* |
(*The far outlier is roughly times more likely under component 2's density than component 1's at this scale, so it is assigned almost entirely — but not literally 100% — to component 2; the exact ratio still depends on the tails.)
Iteration 1 — M-step. Compute effective counts and weighted moments:
Notice how the single outlier , softly assigned to component 2, pulls up sharply from the initial 8 to about 14.65 — a preview of EM's known sensitivity to outliers in Gaussian mixtures. New variances are computed the same weighted way, and new mixing weights are , .
Subsequent iterations. As iterations continue, component 1 tightens around the tight cluster , and component 2 stretches to cover with an inflated variance to accommodate the outlier — since a single Gaussian must explain both 9–10 and 25 simultaneously. The observed log-likelihood increases at every step (monotonicity theorem above); after a handful of iterations the parameters stabilize near , small, , large, and , matching the visually obvious two-cluster-plus-outlier structure of the data — while also exposing that this 2-component model is not a great fit for a true three-group structure (two tight clusters and one outlier), a diagnostic used heavily in Anomaly Detection Fundamentals.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Log-likelihood decreases between iterations | Usually a bug: E-step not using current , or normalizing responsibilities incorrectly | Recompute every iteration and assert monotonicity as a unit test |
| Singular covariance ("collapsed" component) | A component's responsibility concentrates on one point, , likelihood | Add a regularizing floor ; cap component shrinkage |
| Converging to a bad local optimum | Non-convex likelihood surface; EM only guarantees a stationary point | Multiple random restarts, k-means++ initialization, compare final across runs |
| Empty / starved cluster () | Poor initialization assigns almost no responsibility to a component | Re-seed empty clusters from high-error points; merge/split heuristics |
| Treating EM as guaranteed to find the MLE | Confusing "monotone non-decreasing" with "converges to global maximum" | Always report multiple restarts' likelihoods; use held-out likelihood for model selection |
| Label switching across runs/iterations | Components are exchangeable — permuting labels gives an identical model | Align labels post hoc by matching means/moments before comparing runs |
| Overfitting with too many components | More components can only increase (never decrease) training likelihood | Use validation likelihood, BIC/AIC, or held-out data to choose |
Pioneers & history
The 1977 paper by Dempster, Laird, and Rubin unified a scattered family of ad hoc "fill in the missing data, re-estimate, repeat" procedures — already used piecemeal in genetics, factor analysis, and hidden Markov model estimation — into a single, formally justified algorithm with a general monotonicity proof. This transformed EM from a collection of tricks into a principled tool applicable to any exponential-family latent variable model.
Origins · 1 minArthur Dempster and how this was discovered
Dempster co-authored the 1977 Journal of the Royal Statistical Society paper "Maximum Likelihood from Incomplete Data via the EM Algorithm," which formalized the E-step/M-step structure and proved the monotone likelihood-increase property for a broad class of missing-data problems, giving the method its name and its mathematical foundation.
Where this matters
EM (and its variational generalizations) is embedded in an enormous range of production systems. Speech recognition and bioinformatics pipelines historically relied on the Baum–Welch algorithm — EM specialized to hidden Markov models — to train phoneme and gene-sequence models. Gaussian mixture models fit with EM are used for speaker verification, background subtraction in video, and soft clustering in customer segmentation, directly building on Gaussian Mixture Models and Density Estimation Fundamentals. Recommender systems and survey-data pipelines use EM-style imputation to handle missing entries under a probabilistic model rather than discarding incomplete rows. In probabilistic topic modeling (e.g., variants of latent Dirichlet allocation), variational EM extends the same E-step/M-step alternation to approximate rather than exact posteriors when the exact posterior is intractable. Fitted mixture densities from EM feed directly into likelihood-based outlier scoring, the starting point for Anomaly Detection Fundamentals: points with very low under the learned mixture are flagged as anomalies, making EM not just a clustering tool but a density-estimation engine for downstream detection systems.
Ask the tutor: Why does adding more mixture components always increase training likelihood, and what does that imply about how you should choose K?
Does EM always find the global maximum of the likelihood?
No. EM guarantees that the observed-data log-likelihood is monotonically non-decreasing across iterations, and under mild regularity conditions the parameter sequence converges to a stationary point of the likelihood. That stationary point can be a local maximum, or in rarer cases a saddle point, rather than the global maximum. In practice practitioners run EM from several different random initializations (or use smarter seeding like k-means++), keep the run with the highest final likelihood, and treat convergence of the likelihood sequence as necessary but not sufficient evidence of a good fit.
Why is it called the "E-step" and "M-step" rather than just one update rule?
The names describe two mathematically distinct operations. The E-step takes an expectation: it computes the posterior distribution of the latent variables given the observed data and current parameters, which is used to form the expected complete-data log-likelihood. The M-step then maximizes that expected quantity over the parameters. Separating them clarifies why the algorithm works: the E-step is exact coordinate maximization over the variational distribution , and the M-step is exact (or partial) coordinate maximization over , jointly performing coordinate ascent on the ELBO.
How does EM relate to k-means clustering?
Hard k-means can be viewed as a limiting, "hard-assignment" special case of EM applied to a Gaussian mixture with equal, isotropic, shrinking-to-zero covariances. In that limit the soft responsibilities become 0/1 assignments to the nearest centroid (the E-step becomes nearest-centroid assignment), and the M-step becomes the usual centroid recomputation. EM generalizes k-means by keeping soft, probabilistic assignments and by allowing each cluster its own shape (covariance) and weight, at the cost of a more expensive per-iteration computation.
What happens if the latent variable is continuous rather than discrete, as in factor analysis?
The same E-step/M-step structure applies, but the sum over in the ELBO becomes an integral, and the E-step computes a posterior density rather than a finite table of responsibilities. For models in the exponential family with conjugate priors (such as linear-Gaussian factor analysis or probabilistic PCA), this posterior is itself Gaussian and has a closed form, so the E-step remains tractable analytically. When the posterior has no closed form, practitioners fall back to variational EM, replacing the exact posterior with a tractable approximate family and optimizing the same ELBO approximately.
Why does EM sometimes get stuck with an empty or nearly-empty cluster?
If initialization places a component's mean far from any data, or in a very low-density region, the E-step assigns it near-zero responsibility for every point. The M-step then computes , and the mean and covariance updates become numerically unstable or undefined, effectively freezing that component in a useless state. Common remedies include re-seeding starved components at high-residual points, initializing means from actual data samples or k-means++ centroids rather than arbitrary values, and monitoring per-component effective counts during training to trigger a restart.
Is EM guaranteed to be more efficient than directly maximizing the log-likelihood with gradient ascent?
Not universally, but in many exponential-family latent variable models it is much simpler because the M-step has a closed-form solution (weighted sample statistics), avoiding step-size tuning and line search altogether. Its per-iteration cost is comparable to a gradient step, and it inherits the guaranteed monotonicity property that plain gradient ascent on a non-concave likelihood does not automatically have. Gradient methods can be competitive or faster when the M-step lacks a closed form, or when second-order or accelerated gradient variants are available, so the choice is model-dependent.
Why can outliers distort EM's estimates of a Gaussian mixture so severely?
Gaussian mixtures assign continuous, never-exactly-zero responsibility based on tail probabilities, and Gaussian tails decay only quadratically in the log-density. A distant outlier can still receive substantial or dominant responsibility for the nearest component, since no other component fits it any better, pulling that component's mean and inflating its variance to partially accommodate the outlier. This is visible in the worked example, where a single far point (25) drags a cluster mean well past its naturally tight neighbors (9, 10). Robust alternatives use heavier-tailed component densities (e.g., Student-t mixtures) or explicit outlier/noise components.