19 EM and Its Extensions
19.1 Learning objectives
By the end of this chapter you should be able to:
- Derive the EM algorithm from the marginal likelihood for a generic latent-variable model, and identify the E-step and M-step as the two halves of a coordinate ascent on the evidence lower bound.
- Implement EM for a canonical biostatistical case, the Gaussian mixture model, and identify the latent structure that makes EM applicable to mixed-effects models.
- Recognize when ECM (Expectation-Conditional-Maximization), MCEM (Monte Carlo EM), or variational EM is more appropriate than ordinary EM.
- Diagnose convergence rigorously: monitor the marginal log-likelihood, watch for slow tails, recognize non-identifiability via flat regions in the M-step.
- Compute observed-information standard errors for EM-fitted models via Louis’s method or supplemented EM (SEM).
- Avoid the common antipatterns: stopping at the conditional log-likelihood instead of the marginal, using EM where direct numerical maximization is faster, missing label-switching in mixture models.
19.2 Orientation
EM is the workhorse of latent-variable estimation. Mixed-effects models, mixture models, hidden Markov models, factor analysis, principal components with missing data, and many missing-data problems all reduce to maximizing a likelihood with unobserved or missing components. The EM algorithm is the standard tool for that maximization.
Chapter 12 treated mixed-effects models via lme4. That package does not use EM. For linear models it uses penalized least squares, and for generalized linear models it uses a Laplace approximation or adaptive Gauss-Hermite quadrature. EM is needed when the likelihood has missing or latent components that admit a closed-form expectation given the observed data. Variational EM and MCEM extend the framework to cases where that expectation is intractable.
In this chapter we shall develop EM from first principles and then treat its modern variants. We begin with the algorithm itself and a two-component Gaussian mixture. We then turn to ECM, MCEM, and variational EM. Next we consider convergence diagnostics, standard errors via Louis’s method, and the problem of label switching. The mathematical derivation gives the variants their structure. The implementations are R packages or short hand-coded loops, depending on the model.
19.3 The statistician’s contribution
EM is famously easy to implement and famously easy to get wrong. The judgments at the center of this chapter concern three questions. When is EM the right tool? When has it converged? When is it producing the wrong answer for a subtle reason?
EM is not always the fastest. For problems in which the joint likelihood is tractable as a function of the parameters, direct maximization via Newton or BFGS is typically faster than EM. The appeal of EM is conceptual (it separates the latent from the observed), and it lies also in the guarantee of monotonic likelihood improvement. It does not lie in speed. When we can compute the gradient of the marginal log-likelihood, we can probably skip EM.
Expect convergence to a local maximum. Mixture models in particular have multiple modes, and EM converges to whichever is closest to the starting point. The remedy is multi-start. That is, we run from many initial values and keep the best. Without this, the reported solution is whichever starting value happened to land near a good mode.
Label switching matters and is not a bug. A two-component mixture has two equivalent solutions that permute the component labels, and neither is preferred. For a single fit this is invisible. For posterior summaries or comparison across multi-start runs, however, the labels must be aligned (by post-processing, say, to order components by their mean). Forgetting this produces artifacts in summaries that look real and are not.
Standard errors require deliberate work. EM produces parameter estimates but does not compute standard errors as a side effect. Louis’s method or supplemented EM (SEM) computes the observed information matrix explicitly. Reporting parameter estimates without standard errors is common enough in EM applications. In our view, doing so without acknowledging the gap is a genuine reporting failure.
19.4 The EM algorithm
Consider a model with parameters \(\boldsymbol\theta\), observed data \(\mathbf{y}\), and unobserved (latent or missing) data \(\mathbf{z}\). The complete-data log-likelihood is \(\ell_c(\boldsymbol\theta; \mathbf{y}, \mathbf{z})\). The marginal log-likelihood, which is the one we actually want to maximize, is
\[ \ell(\boldsymbol\theta; \mathbf{y}) = \log \int p(\mathbf{y}, \mathbf{z} \mid \boldsymbol\theta) \, d\mathbf{z}. \]
Unfortunately, the marginal is intractable in general because of the integral. EM circumvents the integral by alternating between two steps.
E-step. Given the current parameter estimate \(\boldsymbol\theta^{(k)}\), we compute the expected complete-data log-likelihood. In symbols,
\[ Q(\boldsymbol\theta \mid \boldsymbol\theta^{(k)}) = E_{\mathbf{z} \mid \mathbf{y}, \boldsymbol\theta^{(k)}}\!\left[ \ell_c(\boldsymbol\theta; \mathbf{y}, \mathbf{z}) \right]. \]
M-step. We maximize \(Q\) to obtain the new estimate. That is,
\[ \boldsymbol\theta^{(k+1)} = \arg\max_{\boldsymbol\theta} Q(\boldsymbol\theta \mid \boldsymbol\theta^{(k)}). \]
The central result is due to Dempster et al. (1977). Each EM iteration weakly increases the marginal log-likelihood. In symbols, \(\ell(\boldsymbol\theta^{(k+1)}; \mathbf{y}) \ge \ell(\boldsymbol\theta^{(k)}; \mathbf{y})\), with equality only at a stationary point.
The proof uses Jensen’s inequality and the Kullback-Leibler divergence. The intuition is as follows. The E-step constructs a lower bound on the marginal log-likelihood that touches it at the current parameter. The M-step then maximizes that lower bound. Since the bound never exceeds the marginal, raising the bound cannot lower the marginal.
19.4.1 Worked example: two-component Gaussian mixture
To illustrate, consider \(y_i \sim \pi_1 N(\mu_1, \sigma^2) + \pi_2 N(\mu_2, \sigma^2)\) with \(\pi_1 + \pi_2 = 1\). The latent indicator \(z_i\) takes the value 1 if observation \(i\) came from component 1 and 0 otherwise.
In the E-step, given the current parameters, we compute the responsibility. This is the posterior probability that observation \(i\) came from component 1. That is,
\[ \gamma_i = P(z_i = 1 \mid y_i, \boldsymbol\theta^{(k)}) = \frac{\pi_1 \phi(y_i; \mu_1, \sigma)}{\pi_1 \phi(y_i; \mu_1, \sigma) + \pi_2 \phi(y_i; \mu_2, \sigma)}. \]
In the M-step we update the parameters using the responsibilities:
\[ \hat\pi_1 = \frac{1}{n} \sum_i \gamma_i, \quad \hat\mu_1 = \frac{\sum_i \gamma_i y_i}{\sum_i \gamma_i}, \quad \hat\mu_2 = \frac{\sum_i (1-\gamma_i) y_i}{\sum_i (1-\gamma_i)}. \]
The variance update is similar, again weighted by the responsibilities.
em_mixture <- function(y, n_iter = 100, tol = 1e-8) {
# initialize
mu <- quantile(y, c(0.25, 0.75))
sigma <- sd(y)
pi_1 <- 0.5
ll_old <- -Inf
for (k in seq_len(n_iter)) {
# E-step
p1 <- pi_1 * dnorm(y, mu[1], sigma)
p2 <- (1 - pi_1) * dnorm(y, mu[2], sigma)
gamma <- p1 / (p1 + p2)
# M-step
pi_1 <- mean(gamma)
mu[1] <- sum(gamma * y) / sum(gamma)
mu[2] <- sum((1 - gamma) * y) / sum(1 - gamma)
sigma <- sqrt(
(sum(gamma * (y - mu[1])^2) +
sum((1 - gamma) * (y - mu[2])^2)) / length(y)
)
# marginal log-likelihood for convergence check
ll <- sum(log(pi_1 * dnorm(y, mu[1], sigma) +
(1 - pi_1) * dnorm(y, mu[2], sigma)))
if (abs(ll - ll_old) < tol) break
ll_old <- ll
}
list(pi = c(pi_1, 1 - pi_1), mu = mu, sigma = sigma,
loglik = ll, iter = k)
}
set.seed(1)
y <- c(rnorm(200, 0, 1), rnorm(300, 4, 1))
fit <- em_mixture(y)
fit$mu
#> 25% 75% # names come from quantile()
#> 0.09 4.06 # close to truth
fit$pi
#> [1] 0.41 0.59 # close to truthThe same idea extends to \(k\)-component mixtures and to mixtures with covariate-dependent component probabilities. It extends also to hidden Markov models, in which the latent variable is a Markov chain rather than a set of independent indicators.
19.4.2 When EM applies
The EM algorithm is the right tool under three conditions.
- The complete-data likelihood is much simpler than the marginal. If the M-step has a closed form given \(z\) but the marginal does not, EM converts a hard optimization into many easy ones.
- The latent structure is interpretable. In mixture components, latent classes, and missing-at-random data, the latent variable has substantive meaning.
- Direct numerical maximization of the marginal is difficult. If the marginal is smooth and tractable, BFGS is faster than EM and produces standard errors as a side effect.
EM is the wrong tool when the complete-data likelihood is nearly as hard as the marginal. It is also the wrong tool when the M-step has no closed form, in which case ECM or generalized EM becomes necessary (see below).
19.5 ECM: Expectation-Conditional-Maximization
Ordinary EM requires the M-step to maximize \(Q\) jointly over all parameters. For complex models, this joint maximization may not have a closed form. Meng & Rubin (1993) proposed ECM, which replaces the single joint M-step with a sequence of conditional maximizations. That is, we maximize over one parameter (or block) at a time, holding the others fixed.
The convergence guarantee carries over. Each conditional maximization increases \(Q\), and so the marginal log-likelihood increases monotonically.
ECM is appropriate in two situations.
- The joint M-step has no closed form but the conditional M-steps do.
- Some parameters have closed-form updates and others require iterative inner maximization.
A common biostatistical case is the mixed-effects model with several variance components. The variance components do not have a joint closed form, but each one does given the others. ECM therefore updates one component at a time.
19.5.1 MCEM: Monte Carlo EM
The E-step expectation may be intractable, with no closed form and no efficient deterministic computation. In that case MCEM replaces it with a Monte Carlo average. In symbols,
\[ \tilde Q(\boldsymbol\theta \mid \boldsymbol\theta^{(k)}) = \frac{1}{M} \sum_{m=1}^M \ell_c(\boldsymbol\theta; \mathbf{y}, \mathbf{z}^{(m)}) \]
where \(\mathbf{z}^{(m)} \sim p(\mathbf{z} \mid \mathbf{y}, \boldsymbol\theta^{(k)})\) are samples from the conditional posterior of the latent variables given the data and the current parameter.
MCEM applies under two conditions.
- The E-step expectation has no closed form.
- Sampling from \(p(\mathbf{z} \mid \mathbf{y}, \boldsymbol\theta)\) is feasible (often via MCMC).
The method carries three trade-offs.
- The Monte Carlo average has variance \(O(1/M)\), so convergence to a fixed point is noisy.
- \(M\) should typically grow with the iteration to ensure proper convergence (Booth & Hobert, 1999).
- Total cost is the inner sampling cost times the outer iteration count, which can be substantial.
Booth & Hobert (1999) established MCEM as an approach for generalized linear mixed models. We note, however, that lme4 and glmmADMB use a Laplace approximation or quadrature instead.
19.5.2 Variational EM
The E-step expectation may be intractable while Monte Carlo is too expensive. In that case variational EM approximates the conditional posterior of \(\mathbf{z}\) by a tractable family \(q(\mathbf{z}; \boldsymbol\phi)\). It then minimizes the KL divergence to the true posterior.
The E-step becomes an optimization of \(\boldsymbol\phi\) to minimize \(\text{KL}(q \| p(\mathbf{z} \mid \mathbf{y}, \boldsymbol\theta))\). The M-step is unchanged in form, but it uses \(q\) rather than the exact posterior.
Variational EM is the engine behind variational autoencoders and latent Dirichlet allocation. It also underlies the variational implementations of Bayesian models in Stan (variational()) and PyMC. The reader is referred to Chapter 23 for the broader variational-inference picture.
The trade-off is that the variational approximation is biased, whereas Monte Carlo is unbiased. Unfortunately, the bias is hard to characterize in advance, and it depends on the choice of \(q\). Variational EM is the right tool when speed is essential and the bias is acceptable.
19.6 Convergence diagnostics
Three diagnostics characterize EM convergence rigorously.
1. Marginal log-likelihood trace. We plot the marginal log-likelihood against iteration. By the EM theorem, the trace should be monotonically non-decreasing, and if it ever decreases there is a bug. The trace should plateau at convergence. The rate of approach gives the convergence rate, which is linear for ordinary EM and faster for ECM-Newton or accelerated EM variants.
2. Parameter trace. We plot each parameter against iteration. Slow drift in late iterations indicates poor identifiability or a near-flat region of the likelihood. This is not necessarily a bug, but it signals that the standard errors will be large.
3. KKT or gradient at termination. We compute the gradient of the marginal log-likelihood at the candidate solution, and it should be small. EM does not directly produce this gradient, so we compute it separately. A large gradient indicates premature termination.
# at convergence, check the marginal score
score <- function(theta, y) {
numDeriv::grad(function(t) marginal_loglik(t, y), theta)
}
max(abs(score(theta_hat, y)))
#> [1] 4e-08 # well-converged19.7 Standard errors via Louis’s method
As we have noted, EM does not compute standard errors as a side effect, so the observed Fisher information \(I(\boldsymbol\theta)\) must be computed separately. Louis (1982) gives the following expression.
\[ I(\boldsymbol\theta) = -E\!\left[\frac{\partial^2 \ell_c}{\partial \boldsymbol\theta^2} \mid \mathbf{y}\right] - \text{Var}\!\left[\frac{\partial \ell_c}{\partial \boldsymbol\theta} \mid \mathbf{y}\right]. \]
In words, the observed information equals the negative of the expected complete-data Hessian minus the variance of the complete-data score. Both terms are evaluated at \(\hat{\boldsymbol\theta}\) and conditional on the observed data.
The first term is what the information would be if we observed \(\mathbf{z}\) directly (the complete information). The second term penalizes that quantity for the uncertainty introduced by not observing \(\mathbf{z}\) (the missing information). Their difference is what the data actually tell us about \(\boldsymbol\theta\).
For models in which the conditional expectations are tractable, Louis’s method can be implemented in a few lines beyond the EM loop. For complex models, supplemented EM (SEM) numerically estimates the rate of convergence of EM and uses it to compute the observed information. The implementation is more involved, but it is also more general.
19.8 Identifiability and label switching
Mixture models have a fundamental non-identifiability. That is, permuting the component labels gives an equivalent model with the same likelihood. EM converges to one of the equivalent solutions, and which one depends on the starting values.
For a single fit this is invisible, since we report some labeling. For multiple fits (multi-start runs, bootstrap, posterior simulation), however, the labels must be aligned. Three standard approaches are available.
- Order by mean. After each fit, sort components by \(\mu_1 < \mu_2 < \ldots < \mu_k\). Works when the means separate the components clearly.
- Order by mixing weight. Sort by \(\pi_1 \le \pi_2 \le \ldots\).
- Hungarian algorithm. For more complex cases (multivariate components), match across runs by minimizing the total distance between matched components. The
label.switchingR package provides this.
For ordinary EM with a single starting point, label switching does not affect the parameter estimates, but it does affect interpretation. When reporting, we should state explicitly which component is which.
19.9 Worked example: SE for the mixture model
We now add standard errors to the mixture-model EM loop above. For a model this small, we compute the observed information directly, as the negative numerical Hessian of the marginal log-likelihood at the EM estimate. Louis’s formula gives the same matrix. It becomes the more practical route when the marginal log-likelihood is expensive to evaluate but the complete-data quantities are not.
em_mixture_with_se <- function(y, n_iter = 100, tol = 1e-8) {
fit <- em_mixture(y, n_iter, tol)
# parameters: pi_1, mu_1, mu_2, sigma
theta <- c(fit$pi[1], fit$mu, fit$sigma)
# marginal log-likelihood as a function of theta
marginal_ll <- function(theta) {
pi_1 <- theta[1]
mu <- theta[2:3]
sigma <- theta[4]
sum(log(pi_1 * dnorm(y, mu[1], sigma) +
(1 - pi_1) * dnorm(y, mu[2], sigma)))
}
# observed information as the negative numerical Hessian
H <- -numDeriv::hessian(marginal_ll, theta)
se <- sqrt(diag(solve(H)))
list(estimates = theta, se = se,
ci_lo = theta - 1.96 * se,
ci_hi = theta + 1.96 * se,
loglik = fit$loglik)
}
fit <- em_mixture_with_se(y)
fit$estimates
#> 25% 75%
#> 0.41 0.09 4.06 1.00
fit$se
#> [1] 0.023 0.079 0.064 0.035
fit$ci_lo
#> 25% 75%
#> 0.37 -0.07 3.93 0.93For mixture models specifically, mclust::Mclust provides production-grade fitting with BIC-based model selection and standard errors via the bootstrap. The hand-coded version above is intended only as an illustration.
19.10 Collaborating with an LLM on EM
LLMs are reliable for the textbook EM derivations and for the standard mixture, hidden Markov, and missing-data implementations. They are weaker on four points.
- Recognizing when ECM is needed (vs ordinary EM).
- Recognizing when MCEM or variational EM is needed (vs direct optimization of the marginal).
- The bookkeeping of label switching across multiple runs.
- Standard-error computation via Louis or SEM.
Prompt 1: derive the E-step and M-step. Describe the model (likelihood, latent structure). Ask the LLM to derive the E-step expectation and the M-step update, showing intermediate steps.
What to watch for. For standard models (Gaussian mixture, multinomial, Poisson regression with random effects), the LLM should produce correct closed-form updates. For non-standard models, however, it may produce plausible-looking but wrong derivations. We would verify every step against a textbook or published derivation.
Verification. Implement the algorithm and check that the marginal log-likelihood is non-decreasing. If the likelihood ever decreases, the M-step is wrong.
Prompt 2: write convergence diagnostics. Paste the inner EM loop. Ask the LLM to add: a marginal-log-likelihood trace, a parameter trace, and a final gradient check.
What to watch for. The marginal log-likelihood is the diagnostic to monitor. The conditional log-likelihood (complete-data, summed with current responsibilities) is not, and the LLM may confuse the two.
Verification. Run the code on a problem where the answer is known. The marginal log-likelihood at convergence should match the closed-form value, where one exists.
Prompt 3: compute standard errors. Describe the model and the converged parameter. Ask the LLM to implement Louis’s method or supplemented EM.
What to watch for. Louis’s method requires the expected complete-data Hessian and the variance of the complete-data score. The LLM may instead compute the observed complete-data Hessian, without the expectation, which is wrong. We would verify that the expectation is taken over the conditional posterior of the latent variable.
Verification. Compare the result to bootstrap standard errors on the same problem. The two should agree to within bootstrap noise. If they disagree by an order of magnitude, the Louis implementation is wrong.
EM derivations are simple in principle but prone to subtle errors in practice. On the one hand, using an LLM to draft the derivation is acceptable. On the other, using it to generate the implementation without a manual check of the derivation is risky.
19.11 Principle in use
Three habits define defensible EM practice:
- Choose EM deliberately. EM is the right tool when the complete-data likelihood is much simpler than the marginal. For models where direct maximization works, use it.
- Multi-start. Run from several initial values; keep the best by marginal log-likelihood. Local optima are common; multi-start is the cheap defense.
- Compute standard errors explicitly. Louis’s method, supplemented EM, or bootstrap. Reporting point estimates without SEs is incomplete; doing so silently is dishonest.
19.12 Exercises
- Implement EM for a three-component Gaussian mixture with shared variance. Test on synthetic data where the truth is known. Run from 50 random starts; verify the best run reaches the same likelihood each time.
- Modify the mixture-model EM to allow component-specific variances. Show that the algorithm can collapse a component onto a single observation (variance shrinks to zero, density goes to infinity). Add a regularization that prevents this.
- Implement Louis’s method standard errors for the two-component mixture. Compare to bootstrap SEs from 1000 resamples. They should agree to within bootstrap noise.
- Use
mclust::Mclustto fit a Gaussian mixture model on a real dataset (e.g.,iris[, 1:4]). Compare BIC across \(k = 1, \ldots, 8\). Report the selected number of components and interpret. - For a missing-data problem (any biostatistical dataset with a missing covariate), implement EM for the maximum likelihood estimates under a missing-at-random assumption, using all cases. Compare to multiple imputation via
mice. Both should agree to roughly the precision permitted by the data.
19.13 Further reading
- (Dempster et al., 1977), the original EM paper.
- (McLachlan & Krishnan, 2008), The EM Algorithm and Extensions, the canonical reference, includes ECM, MCEM, accelerated EM.
- (Meng & Rubin, 1993), Meng and Rubin, the ECM paper.
- (Booth & Hobert, 1999), Booth and Hobert, MCEM with automated \(M\) scheduling.
- The
mclustandflexmixpackage documentation for applied mixture-model fitting in R.