Latent Variables & EM
Hidden structure, and how to fit models of it.
A cloud of points that is really three overlapping groups, a pile of documents that each mix a few themes, a survey full of blank answers: in each, the variable that would make modeling easy is the one you never get to see. This lesson builds models with hidden variables and derives EM, the algorithm that fits them by alternately guessing the hidden part and refitting the rest.
What you’ll learn
- Write the marginal likelihood of a latent-variable model and explain why the logarithm of a sum blocks closed-form maximum likelihood.
- Compute responsibilities in a Gaussian mixture by Bayes' rule, and derive the E-step and M-step of EM for it.
- Prove that an EM iteration never decreases the likelihood, and explain why EM still needs good initialization and restarts.
- Derive k-means as the small-variance limit of EM for a Gaussian mixture, and say what that limit throws away.
Hidden variables
A latent-variable model specifies a joint distribution over an observed and an unobserved . The data constrain only the marginal, so the likelihood sums (or integrates) the hidden part away:
Read right to left, the model is a story about how the data were made: first nature draws a hidden cause , then it draws given that cause. Fitting the model means recovering the story's parameters from its visible output alone.
| Model | Hidden | Observed | Where it is developed |
|---|---|---|---|
| Gaussian mixture | which component produced each point | the points | this lesson; Gaussian Mixture Models in Depth |
| Topic model (LDA) | each word's topic and each document's topic proportions | the words of each document | Topic Models & Latent Dirichlet Allocation |
| Missing data | the entries nobody recorded | the entries that were recorded | the last step; Why EM Works |
| Probabilistic PCA, factor analysis | a low-dimensional code | PCA in Depth | |
| Hidden Markov model | the sequence of hidden states | the emitted symbols | Baum–Welch, an early instance of EM |
Why is fitting hard? For i.i.d. examples the log-likelihood is
The logarithm sits outside a sum, so it cannot break the model into its parts. If the were observed, the complete-data log-likelihood would split into simple pieces, often each with a closed-form maximum-likelihood estimate. EM is built on exactly this contrast.
Think first Suppose someone hands you every point of a mixture together with the label of the component that produced it. How do you fit the mixture?
Split the points by label. Each component's weight is its share of the points, , and its mean and covariance are the sample mean and (divide-by-) covariance of its own points. Three textbook formulas and no iteration: the difficulty is entirely in the missing labels. EM replaces each hard label by a probability and uses the same formulas with weights.
A mixture of Gaussians with full covariance matrices is fitted to points in the plane. How many free parameters and how many latent variables does the model have?
- 17 parameters and 1,000 latent variables
- 18 parameters and 1,000 latent variables
- 17 parameters and 3 latent variables
- 20 parameters and 1,000 latent variables
Show the answer
A. 17 parameters and 1,000 latent variables
The weights contribute (they sum to one), the means and the symmetric covariances : 17 global parameters. Each point has its own hidden label, so there are latent variables. Parameters stay fixed as data arrive; latent variables grow with .
The Gaussian mixture model
The Gaussian mixture model tells this story for each point :
- Draw a component with , where and .
- Draw for that component.
Summing out gives the density , which can approximate almost any smooth density with enough components. Seeing updates the prior to a posterior by Bayes' rule: the responsibility of component for point ,
In one dimension with two components of equal weight and equal variance , the log-odds are linear in : , so the responsibility is a sigmoid of , exactly the form of logistic regression. A generative model, read through Bayes' rule, produces a classifier.
A one-dimensional mixture has two equally weighted components, and . What is the responsibility of the second component for the point ?
Show the answer
73 %
The log-odds are , so . The point is three times closer to 2 than to 0, yet a quarter of it is still attributed to the first component: Gaussian tails overlap.
The log-likelihood of the mixture is a sum of logs of sums:
Differentiate with respect to . The derivative of the log brings down exactly the responsibility, because :
Setting it to zero says the mean is a responsibility-weighted average of the points. But the weights depend on itself, so this is a fixed-point equation, not a formula. The natural move is to iterate: compute from the current parameters, then solve the equations with frozen. That is EM.
EM: guess the hidden part, then refit
The expectation–maximization (EM) algorithm of Dempster, Laird & Rubin (1977) alternates two steps from a starting guess :
- E-step. Compute the posterior over the hidden variables under the current parameters, .
- M-step. Maximize the expected complete-data log-likelihood under those posteriors:
For a Gaussian mixture the E-step is the responsibility formula, and separates into one term for the weights and one weighted Gaussian fit per component.
Write , the "effective number" of points in component . The weights appear only in . Maximize it subject to with a Lagrange multiplier : for every , and summing over gives .
Each mean appears only in , a weighted Gaussian log-likelihood. Its gradient vanishes at the weighted mean, and now the weights are fixed numbers:
Differentiating with respect to gives :
import numpy as np
from scipy.stats import multivariate_normal
def em_step(X, pi, mu, Sigma):
"""One EM iteration for a Gaussian mixture; returns new parameters and the old log-likelihood."""
n, K = len(X), len(pi)
# E-step: dens[i, k] = pi_k N(x_i | mu_k, Sigma_k), then normalize each row
dens = np.column_stack([pi[k] * multivariate_normal.pdf(X, mu[k], Sigma[k])
for k in range(K)])
loglik = np.log(dens.sum(axis=1)).sum()
r = dens / dens.sum(axis=1, keepdims=True)
# M-step: weighted maximum likelihood
Nk = r.sum(axis=0)
pi = Nk / n
mu = (r.T @ X) / Nk[:, None]
Sigma = np.stack([(r[:, k, None] * (X - mu[k])).T @ (X - mu[k]) / Nk[k]
for k in range(K)])
return pi, mu, Sigma, loglikIterate until the log-likelihood rises by less than a tolerance. Real implementations compute the E-step in log space (log-sum-exp) to avoid underflow and keep covariances away from singular; sklearn.mixture.GaussianMixture adds reg_covar to each covariance and starts from k-means by default.
Why the likelihood never goes down
Monotonicity follows from one inequality. For any distribution over that is positive wherever the posterior is, multiply and divide by and apply Jensen's inequality to the concave logarithm:
Equality holds when the ratio inside is constant in , that is when . And differs from only by the entropy of , which does not depend on .
Let be the E-step posterior at . The bound holds for every , in particular for at the new parameters:
The M-step maximizes , which is minus a constant, so it cannot do worse than staying put:
The E-step made the bound tight at the old parameters. Chain the three facts:
The argument never used that the M-step finds the maximum: any that raises will do (a generalized EM). What it does not promise is just as important:
- A global maximum. EM climbs to a stationary point of , usually a local maximum, and which one depends on the start.
- Speed. Convergence is typically linear, and slow when the components overlap, because the hidden labels then carry much of the information. Why EM Works makes this precise.
- A finite maximum. If a component's mean lands on a single data point and its covariance shrinks toward zero, that point's density, and with it , grows without bound. Implementations floor the variances or add a small multiple of ; the widget floors the variance in every direction at .
You run EM ten times from random starts on the same data with the same , and the final log-likelihoods range from to . No run shows a collapsed component. Which fit should you keep?
- The run that converged in the fewest iterations
- An average of the ten fitted parameter vectors
- The run with the highest final log-likelihood
- The run whose mixing weights are closest to equal
Show the answer
C. The run with the highest final log-likelihood
All ten runs fit the same model to the same data, so the log-likelihood is directly comparable, and the highest one is the best maximum-likelihood fit found. This only works within one : comparing different needs a penalty or held-out data.
k-means is EM with the uncertainty switched off
Constrain every component to the same spherical covariance and hold the weights fixed at positive values (say ). Only the means are left to learn. Now shrink .
With , the common factor cancels from the responsibility:
If is the unique nearest mean, every exponent as , whatever the fixed weights. The soft assignment hardens into "nearest mean takes all":
The M-step for the means becomes the average of the points assigned to each mean, and the expected complete-data log-likelihood becomes, up to constants, a multiple of minus the inertia. This is Lloyd's k-means algorithm:
| Aspect | k-means | EM for a Gaussian mixture |
|---|---|---|
| Assignments | hard: each point to its nearest centroid | soft: responsibilities |
| Cluster shape | implicitly spheres of equal size | ellipses of any size, shape and orientation (full ) |
| Objective | inertia, which never increases | log-likelihood, which never decreases |
| Output | a partition | a density, plus uncertainty about every point's cluster |
| Cost per iteration | with full covariances, plus for the inverses | |
| Shared weaknesses | local optima, choice of | the same, plus the unbounded likelihood |
In the limit above, a point lies exactly halfway between two means and (and farther from all others), with weights , . What does its responsibility tend to as ?
- 1
- 0.5
- 0.6
- It oscillates and has no limit
Show the answer
C. 0.6
With the exponentials cancel exactly, at every , and only the weights remain: . Ties are the one place the hard limit is not reached; k-means breaks them by an arbitrary rule.
Missing data, other models and what comes next
EM was named for incomplete data, and missing data is its oldest use. If some coordinates of a Gaussian vector are unrecorded, the E-step fills in the expected sufficient statistics of the missing part given the observed part (its conditional mean, and the conditional covariance added to the outer products), and the M-step re-estimates the mean and covariance from the completed statistics. Plugging in the conditional mean alone would understate the variance.
Ignoring why values are missing is justified when they are missing at random: the chance that a value is missing may depend on what was observed but not on the missing value itself. Then the likelihood of the observed data is the right objective. If people with high incomes skip the income question, the data are missing not at random, and EM on the naive model is biased however long it runs.
The same E/M pattern fits probabilistic PCA and factor analysis (Gaussian latent codes), hidden Markov models (latent state sequences, with the E-step computed by the forward–backward recursions), mixtures of experts, and latent Dirichlet allocation, where the exact E-step is intractable and is replaced by a variational approximation. When even approximate posteriors over the latent variables are out of reach, you need the general tools of Approximate Inference: sampling and variational methods.
Key takeaways
- A latent-variable model's likelihood sums the hidden variables out, ; the log of that sum couples everything, while the complete-data log-likelihood would split into easy pieces.
- In a Gaussian mixture, responsibilities are posteriors by Bayes' rule; the M-step is weighted maximum likelihood: , weighted means and weighted covariances.
- EM never decreases the likelihood, because the E-step makes the Jensen bound tight and the M-step raises it. It converges to a stationary point, not necessarily the best one, so restarts and k-means initialization matter.
- k-means is the limit of EM with shared covariance as : assignments harden and the objective becomes the inertia. Hard assignments bias the estimates when clusters overlap.
- The same pattern fits missing data (valid under missing at random), hidden Markov models, factor analysis and topic models; when the E-step is intractable, approximate inference takes over.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In EM for a Gaussian mixture, what does the E-step compute?
- New means, as responsibility-weighted averages of the points
- The gradient of the log-likelihood with respect to the means
- Each point's posterior probability of belonging to each component, under the current parameters
- A hard assignment of each point to its nearest mean
Show the answer
C. Each point's posterior probability of belonging to each component, under the current parameters
The E-step applies Bayes' rule with the current to get . The M-step then uses these as weights.
Your EM implementation reports a log-likelihood that went down between two iterations. What is the most likely explanation?
- A bug or a numerical problem: an exact EM iteration cannot decrease the likelihood
- EM passed the maximum and started to overfit
- EM escaped a local maximum on its way to a better one
- Ordinary randomness from the initialization
Show the answer
A. A bug or a numerical problem: an exact EM iteration cannot decrease the likelihood
The chain holds for every iteration. A decrease means the E- or M-step is wrong, underflow corrupted the responsibilities, or the code tracks a different objective (for example a penalized one) than it prints.
Which change turns EM for a Gaussian mixture into k-means?
- Use diagonal instead of full covariance matrices
- Start from k-means++ initialization
- Run a single EM iteration instead of iterating to convergence
- Fix every covariance to , keep the weights fixed, and let
Show the answer
D. Fix every covariance to , keep the weights fixed, and let
With a shared spherical covariance, responsibilities become a softmax of , which hardens into nearest-mean assignment as ; the M-step for the means becomes the centroid update.
You fit mixtures with components and keep the with the highest training log-likelihood. What goes wrong?
- Nothing: the likelihood is a proper score, so the best wins
- The best achievable log-likelihood never decreases as grows, so you will pick the largest (or a degenerate fit)
- EM cannot be run with more than three components
- The log-likelihood decreases with , so you will always pick
Show the answer
B. The best achievable log-likelihood never decreases as grows, so you will pick the largest (or a degenerate fit)
A mixture with components can imitate one with (give the extra one zero weight), so its maximum likelihood is at least as high, and in practice strictly higher. Choosing needs a complexity penalty such as BIC or held-out likelihood (Gaussian Mixture Models in Depth).
Why does the M-step for a Gaussian mixture have a closed form, when maximizing the log-likelihood directly does not?
- The M-step uses gradient descent until convergence
- Responsibilities are always exactly 0 or 1
- With the responsibilities held fixed, the expected complete-data log-likelihood splits into a term for the weights and a weighted Gaussian fit for each component
- The M-step ignores the mixing weights
Show the answer
C. With the responsibilities held fixed, the expected complete-data log-likelihood splits into a term for the weights and a weighted Gaussian fit for each component
has the logarithm inside the sums, so it decouples: weighted counts give , weighted means and weighted covariances give the rest.
Go deeper
- Why EM Works · The ELBO view: monotone improvement and its variants.
- Gaussian Mixture Models in Depth · Identifiability, singularities and choosing the number of components.
- Topic Models & Latent Dirichlet Allocation · Documents as mixtures of topics.
Further reading
- A. P. Dempster, N. M. Laird & D. B. Rubin, "Maximum likelihood from incomplete data via the EM algorithm," Journal of the Royal Statistical Society B 39(1), 1–38 (1977).
- C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), chapter 9.
- G. J. McLachlan & T. Krishnan, The EM Algorithm and Extensions, 2nd ed. (Wiley, 2008).
- K. P. Murphy, Probabilistic Machine Learning: An Introduction (MIT Press, 2022).