Learning/Learning with Hidden Variables: The EM Algorithm

Lesson 5.42,713 words

Learning with Hidden Variables: The EM Algorithm

Complete data can be learned by counting; real data usually hide some variables — the disease behind the symptoms, the cluster behind the points. This part develops the expectation-maximization algorithm, which learns those models by alternating an expected completion of the missing data with a re-estimation of the parameters.

╌╌╌╌

This builds on Learning Probabilistic Models, which framed learning as Bayesian inference and derived the maximum-likelihood, MAP, and Bayesian estimators for the case of complete data — where every example fixes a value for every variable, so each parameter is just a count. Here we drop that assumption. When some variables are never observed, counting is impossible, and the learning problem needs the algorithm this part is about.

Learning with hidden variables: the EM algorithm

Everything so far assumed complete data. Real data are usually incomplete: some variables are never observed. A medical record lists symptoms, diagnosis, and treatment, but rarely the underlying disease. Such a hidden (or latent) variable is worth keeping precisely because it can dramatically reduce the number of parameters: a disease node with three predisposing causes and three symptoms may need parameters, but splicing the disease out and connecting causes directly to symptoms — now no longer conditionally independent — can balloon that to over . Hidden variables buy compactness at the cost of a harder learning problem: you cannot count what you cannot see.

The expectation–maximization algorithm, EM, solves this in a general way. Its one idea: pretend you know the parameters, use them to infer a probability distribution over the hidden variables, then refit the parameters as if that inferred completion were real data — and iterate. Each pass alternates an expectation step (complete the data in expectation) with a maximization step (re-estimate the parameters).

Unsupervised clustering with a mixture of Gaussians

The cleanest instance is unsupervised clustering: discovering categories in unlabeled data. Model the data as generated by a mixture distribution with components. A hidden variable names the component that generated a point, and the density is

For continuous data the natural component is a multivariate Gaussian, giving a mixture of Gaussians with parameters (the weight), (the mean), and (the covariance) for each component . If you knew which component generated each point you could fit each Gaussian directly; if you knew the parameters you could assign each point to a component. When neither is known, EM alternates between the two estimates.

Initialize the parameters arbitrarily, then iterate two steps. In the E-step, compute the responsibility , the probability that point came from component , by Bayes' rule from the current parameters. In the M-step, refit each component to all the data, weighting each point by its responsibility.

One EM pass on a mixture of Gaussians. The E-step assigns each point a soft responsibility to each cluster (shading); the M-step moves each cluster's mean and covariance to the responsibility-weighted data. Iterating tightens the components onto the true clusters.

Writing for the effective number of points assigned to component , the M-step updates are responsibility-weighted versions of the Gaussian ML estimators derived earlier:

The E-step computes the expected values of the hidden indicator variables ( if point came from component , else ); the M-step maximizes the log likelihood given those expectations. Applied to data sampled from a three-component mixture, EM reconstructs a model nearly indistinguishable from the generator. As pseudocode:

Algorithm:EM-Mixture-of-Gaussians\textsc{EM-Mixture-of-Gaussians} — cluster unlabeled data into kk Gaussians
  1. 1
    input: data x1,,xN\mathbf{x}_1, \ldots, \mathbf{x}_N, number of components kk
  2. 2
    initialize wi,μi,Σiw_i, \mu_i, \Sigma_i arbitrarily for i=1i = 1 to kk
  3. 3
    repeat
  4. 4
    for each point jj and component ii do
    E-step
  5. 5
    pijαwiP(xjC=i)p_{ij} \gets \alpha\, w_i\, P(\mathbf{x}_j \mid C = i)
    responsibility, normalized over ii
  6. 6
    for each component ii do
    M-step
  7. 7
    nijpijn_i \gets \sum_j p_{ij}
  8. 8
    μi1nijpijxj\mu_i \gets \frac{1}{n_i} \sum_j p_{ij}\, \mathbf{x}_j
  9. 9
    Σi1nijpij(xjμi)(xjμi)\Sigma_i \gets \frac{1}{n_i} \sum_j p_{ij}\, (\mathbf{x}_j - \mu_i)(\mathbf{x}_j - \mu_i)^\top
  10. 10
    wini/Nw_i \gets n_i / N
  11. 11
    until log likelihood LL converges
  12. 12
    return {wi,μi,Σi}\{w_i, \mu_i, \Sigma_i\}

One EM iteration, worked in numbers

Consider a single pass on four one-dimensional points, , which plainly form two clusters. Fit a two-component mixture, and initialize deliberately badly to see EM correct itself: means , , standard deviations , and equal weights .

E-step. For each point compute the responsibility by Bayes' rule, . With and , the point gets . The full set of responsibilities to component 1:

The two low points lean toward component 1, the two high points toward component 2, with the boundary points fractionally split — exactly the soft assignment that distinguishes EM from hard -means.

M-step. The effective counts are and . The new means are responsibility-weighted averages:

The weighted variances give and , and the mixing weights become , . In one step the means have jumped from toward the true cluster centers near and , and the data log likelihood rose from to . That increase is guaranteed on every iteration.

One EM iteration on four 1-D points. Top: initial components (means at 0 and 4). The E-step assigns each point soft responsibilities (arrow thickness); the M-step pulls each mean to its responsibility-weighted data, so mu1 moves from 0 to 1.42 and mu2 from 4 to 4.45, raising log L from -9.40 to -7.76.

Two facts anchor EM's behavior. It increases the log likelihood of the data at every iteration — this can be proved in general — and under mild conditions it converges to a local maximum. It resembles gradient-based hill-climbing but has no step-size parameter to tune.

The log likelihood of the data as a function of EM iteration. It rises monotonically toward the value under the true model (dashed), climbing fast early and slowly near convergence — the typical EM trajectory.

EM is not foolproof. A component can shrink onto a single point, sending its variance to zero and its likelihood to infinity; two components can merge onto the same data. These degenerate local maxima worsen in high dimensions. Placing priors on the parameters (the MAP version of EM), restarting a collapsing component, and sensible initialization all help.

EM for Bayesian networks and HMMs

The same insight extends beyond mixtures. To learn a Bayesian network with hidden variables, treat the E-step as computing, by ordinary Bayes-net inference, the expected counts that you would otherwise tabulate from complete data. The canonical example is the two-bag candy mixture: two bags of candy have been tipped together, so each piece has a (cherry or lime), a (red or green), and either a or not, but the it came from is hidden. Within a bag the three features are independent — a naive-Bayes model — but the distribution of each feature depends on the bag.

The two-bag candy mixture as a Bayesian network. The hidden Bag at the root selects a bag; conditioned on it, Flavor, Wrapper, and Holes are independent (naive Bayes). Seven parameters: theta = P(Bag=1), and for each feature a probability given each bag. The CPT for Flavor is shown; Wrapper and Holes are analogous.

For that model, with the bag hidden, the expected count of candies from bag is

and each CPT parameter is updated by the ratio of expected counts,

One EM iteration on the candy bags, in numbers

The Gaussian mixture above was carried through with real numbers; the candy net deserves the same. Generate candies from a true model in which the two bags are equally likely, bag 1 is mostly cherry / red / holed and bag 2 mostly lime / green / no-hole:

Because is hidden, the data are just counts of the eight observable candy types , worked here with the sample counts and initialization AIMA uses:1

The 1000 sampled candies by observable type. Columns are wrapper x holes, rows are flavor. Bag is not recorded. Red-wrapped cherries with a hole (273) are the most common type, reflecting bag 1's true profile; green no-hole limes (167) reflect bag 2.

Initialize the parameters deliberately off the truth, and every feature probability for bag 1 and for bag 2.

E-step. For each of the eight candy types, compute the responsibility by Bayes' rule on the naive-Bayes model,

For the 273 red-wrapped cherry candies with holes, every factor favors bag 1, so

and the eight responsibilities range from down to for the type that best matches bag 2:

E-step responsibilities P(Bag=1) for the eight candy types under the initial parameters, with each type's count. A cherry/red/hole candy is 0.835 likely to be bag 1; a lime/green/no-hole candy only 0.308. The types matching neither profile sit at 0.5. These are soft, not hard, assignments.

M-step. Sum the responsibilities over all candies to get the expected count of bag-1 candies, then divide by for the new prior. Weighting each type's count by its responsibility (the candies contribute , and so on across all eight), the expected bag-1 total is , so

The feature parameters follow the same ratio-of-expected-counts recipe. For , sum the responsibilities of the four cherry types for the numerator and all eight for the denominator, . Doing this for every parameter gives

Every bag-1 parameter has moved up from toward the true , and every bag-2 parameter down from toward the true — one iteration already separates the bags in the right direction. The log likelihood of the 1000 candies rises from about under to about after this single step, an improvement in the likelihood itself by a factor of roughly .

The data log likelihood over EM iterations on the candy bags. One step lifts it from about -2044 to -2021; by the tenth iteration the learned model (about -1982) fits better than the generating model, after which progress slows to a crawl.

Two features of the candy run mirror the general theory. The assignments are soft — the ambiguous types sit at exactly and contribute to both bags — which is why EM, unlike a hard bag-by-bag count, can make progress with the bag entirely unobserved. And each parameter update reads off only a local posterior: needs the posterior over for each candy and nothing about or beyond what that posterior already summarizes. This locality is what turns the update into a by-product of ordinary Bayes-net inference.

The general lesson: the parameter updates for Bayesian-network learning with hidden variables are read directly off the results of inference on each example, and only local posteriors — over each variable and its parents — are needed. Exact inference algorithms such as variable elimination produce these as a by-product, with no learning-specific computation.

The final case is the hidden Markov model. An HMM is a dynamic Bayesian network with one discrete state variable, and each data point is an observation sequence. The complication over general Bayes nets is that the transition probabilities are shared across all time steps ( for all ), so the update sums expected transition counts over time,

The expected counts come from the forward–backward algorithm, run as smoothing rather than filtering — you must consider later evidence to estimate that a transition occurred. This instance of EM is the Baum–Welch algorithm.

The general form

Strip the examples away and one equation is left. Let be all observed values, all hidden variables, and all parameters. EM iterates

The E-step is the summation: the expected complete-data log likelihood under the posterior over the hidden variables. The M-step is the maximization of that expected log likelihood over the parameters. Every instance is this equation with specialized: the component indicator for mixtures, an unobserved variable's value for Bayes nets, the sequence state for HMMs.

Algorithm:Expectation-Maximization\textsc{Expectation-Maximization} — parameter learning with hidden variables
  1. 1
    input: observed data x\mathbf{x}, model with hidden variables Z\mathbf{Z}
  2. 2
    initialize parameters θ(0)\boldsymbol{\theta}^{(0)}
  3. 3
    i0i \gets 0
  4. 4
    repeat
  5. 5
    compute the posterior P(Zx,θ(i))P(\mathbf{Z} \mid \mathbf{x}, \boldsymbol{\theta}^{(i)})
    E-step
  6. 6
    Q(θ)zP(zx,θ(i))L(x,zθ)Q(\boldsymbol{\theta}) \gets \sum_{\mathbf{z}} P(\mathbf{z} \mid \mathbf{x}, \boldsymbol{\theta}^{(i)})\, L(\mathbf{x}, \mathbf{z} \mid \boldsymbol{\theta})
  7. 7
    θ(i+1)argmaxθQ(θ)\boldsymbol{\theta}^{(i+1)} \gets \arg\max_{\boldsymbol{\theta}} Q(\boldsymbol{\theta})
    M-step
  8. 8
    ii+1i \gets i + 1
  9. 9
    until L(xθ(i))L(\mathbf{x} \mid \boldsymbol{\theta}^{(i)}) converges
  10. 10
    return θ(i)\boldsymbol{\theta}^{(i)}

Why EM climbs: the evidence lower bound

The monotone-increase guarantee follows from one inequality. The quantity EM actually wants to raise is the log likelihood of the observed data, , a log-of-a-sum that is hard to optimize directly because the hidden is buried inside. Introduce any distribution over the hidden variables and rewrite, then apply Jensen's inequality (the log of an average is at least the average of the logs, since is concave):

The right-hand side is the evidence lower bound (ELBO). The gap between it and the true log likelihood coincides with the Kullback–Leibler divergence , so the bound is tight — equality holds — precisely when , the posterior over the hidden variables.

EM is coordinate ascent on this bound. The E-step maximizes over with fixed, and the maximizer is the posterior — which is why the E-step computes exactly that posterior, and after it the bound touches the log likelihood. The M-step then maximizes over with fixed, which (dropping the -free entropy of ) is the expected complete-data log likelihood maximized earlier. Because each step never lowers and the E-step makes equal the log likelihood, the log likelihood itself cannot decrease:

That chain is the whole convergence proof. It also explains the failure modes: EM maximizes a bound that only touches the true objective at the current parameters, so it can settle at any local maximum, and where the likelihood is unbounded (a Gaussian component collapsing onto one point) EM will climb toward infinity.

EM as coordinate ascent on the evidence lower bound. The E-step raises the bound L until it touches the log likelihood at the current theta (KL = 0); the M-step slides theta to the bound's maximum, raising the true log likelihood; the next E-step re-tightens the bound at the new theta.

Once the general form is understood, variants follow. When the exact E-step is intractable — large Bayes nets — an approximate E-step still yields effective learning: with an MCMC sampler, each configuration of hidden and observed variables visited is treated as a complete observation, and parameters update after each transition. Variational and loopy methods serve the same role for very large networks. The same latent-variable-and-EM story reappears in the deep-learning treatment of latent-variable models, where a neural network parameterizes the components and the E-step becomes an approximate inference network rather than exact Bayes' rule — the variational autoencoder is EM with the posterior itself learned.

From EM to modern probabilistic learning

The candy bags and mixtures of Gaussians in this lesson are the classical core of statistical learning; the same machinery scales into much of modern machine learning, and the public literature fills in the pieces AIMA only sketches.

EM's own history and generality. The algorithm was named and given its general form by Dempster, Laird, and Rubin (1977), who proved the monotone-likelihood result via the lower-bound argument above; the coordinate-ascent-on-the-ELBO view was made explicit by Neal and Hinton (1998), which is what licenses partial or incremental E-steps that update only some responsibilities per pass and still converge.2 The Baum–Welch algorithm for HMMs actually predates the general EM formulation (Baum et al., 1970), a special case discovered first.3

Conjugate priors and the exponential family. The beta–binomial and Dirichlet–multinomial conjugacies used here are instances of a general fact: every distribution in the exponential family has a conjugate prior, and Bayesian updating reduces to adding sufficient statistics to the prior's hyperparameters. This structure, laid out in Bishop's Pattern Recognition and Machine Learning (2006), is what makes tractable Bayesian inference possible at all, and it is the backbone of latent Dirichlet allocation (Blei, Ng, and Jordan, 2003), the topic model that applies exactly the mixture-and-EM idea of this lesson to documents, with words drawn from latent topics.4

When EM is intractable: variational inference and MCMC. For models where the exact posterior in the E-step cannot be computed, two families of approximation dominate. Variational inference replaces the true posterior with the closest member of a tractable family by maximizing the same ELBO derived above — turning inference into optimization (Jordan et al., 1999; Blei, Kucukelbir, and McAuliffe, 2017).5 Markov-chain Monte-Carlo instead draws samples from the posterior; Gelman et al.'s Bayesian Data Analysis is the standard reference. The variational autoencoder (Kingma and Welling, 2013) is the meeting point of both threads and this lesson: it is EM in which a neural network amortizes the E-step, learning a single inference network that approximates the posterior for every data point at once, trained by maximizing the ELBO with the reparameterization trick.6 Read that way, the latent-variable models behind modern generative AI are direct descendants of the mixture-of-Gaussians EM worked here.

Learning Bayes-net structure, in practice. The score-and-search sketch of this lesson corresponds to real algorithms: the BIC/MDL score penalizes structure by a term proportional to , and the constraint-based PC algorithm (Spirtes, Glymour, and Scheines, 1993) recovers structure from conditional-independence tests, a starting point for the modern field of causal discovery.7

EM is the standard method for learning when data are incomplete. Whenever a model has variables you cannot observe — clusters without labels, diseases behind symptoms, states behind an emission sequence — the procedure is the same: complete the data in expectation, maximize as if it were real, repeat.

Footnotes

  1. AIMA, §20.3.1 — Unsupervised clustering: learning mixtures of Gaussians, and the two-bag naive-Bayes candy mixture worked through one EM iteration. The 1000-sample counts, the initialization , the E-step responsibility of the 273 red-holed cherries (), the resulting and the other updated parameters, and the log-likelihood rise from to (and to by the tenth iteration) are all from AIMA's Figure 20.13 example.
  2. Dempster, A. P., Laird, N. M., and Rubin, D. B. (1977), Maximum Likelihood from Incomplete Data via the EM Algorithm, Journal of the Royal Statistical Society, Series B 39(1): 1–38 — the general formulation and monotone-likelihood proof; Neal, R., and Hinton, G. (1998), A View of the EM Algorithm that Justifies Incremental, Sparse, and Other Variants, gives the ELBO coordinate-ascent view.
  3. Baum, L. E., Petrie, T., Soules, G., and Weiss, N. (1970), A Maximization Technique Occurring in the Statistical Analysis of Probabilistic Functions of Markov Chains, Annals of Mathematical Statistics 41(1): 164–171 — the forward–backward (Baum–Welch) procedure for HMMs, a special case of EM found before the general algorithm.
  4. Bishop, C. M. (2006), Pattern Recognition and Machine Learning, Springer — exponential families and conjugate priors; Blei, D., Ng, A., and Jordan, M. (2003), Latent Dirichlet Allocation, Journal of Machine Learning Research 3: 993–1022 — a mixture model over documents fit by variational EM.
  5. Jordan, M. I., Ghahramani, Z., Jaakkola, T. S., and Saul, L. K. (1999), An Introduction to Variational Methods for Graphical Models, Machine Learning 37: 183–233; Blei, D., Kucukelbir, A., and McAuliffe, J. (2017), Variational Inference: A Review for Statisticians, JASA 112: 859–877 — approximate posterior inference by maximizing the ELBO over a tractable family.
  6. Kingma, D. P., and Welling, M. (2013), Auto-Encoding Variational Bayes, ICLR 2014 (arXiv:1312.6114) — the variational autoencoder, amortizing the E-step with a learned inference network and the reparameterization trick.
  7. Spirtes, P., Glymour, C., and Scheines, R. (1993), Causation, Prediction, and Search, Springer — the constraint-based PC algorithm for recovering network structure from conditional-independence tests; the BIC score is from Schwarz, G. (1978), Estimating the Dimension of a Model, Annals of Statistics 6: 461–464.

╌╌ END ╌╌