The EM algorithm in general: lower bound, monotonicity and convergence
Expectation-maximization through the evidence lower bound, convergence, variants and missing data.
After this lesson you can
- Derive the lower bound and EM updates.
- Explain monotonicity, convergence and the role of missing information.
- Compare EM variants and coordinate ascent.
- Explain missing-data assumptions and implement EM.
Before you start
Motivation: latent variables and missing data everywhere
In the previous lesson you fitted a Gaussian mixture by alternating two steps: calculating responsibilities and re-estimating weights, means and covariances as if those responsibilities were labels. That procedure is not a trick unique to mixtures. It is the best-known instance of a general recipe that appears whenever a model has something unobserved:
- Probabilistic clustering. Each point’s component label is a latent variable. Gaussian, Bernoulli (for binary data) and multinomial mixtures (for word counts) are fitted alike.
- Sequences. In a hidden Markov model the hidden state at each time is latent; the Baum-Welch algorithm is EM with a forward-backward E-step.
- Factors. In factor analysis and probabilistic PCA (lesson 12 of this module), each observation is a linear combination of unobserved factors plus noise.
- Missing data. A survey with unanswered questions, a failed sensor, an incomplete medical record: missing entries are latent variables of the complete-data model.
- Deep models. The variational autoencoder maximizes the same bound you will derive here, with the posterior approximated by a network.
In all these cases the complete-data likelihood (observed plus latent) is easy: it factorizes, belongs to the exponential family and has a closed-form maximum. The observed-data likelihood is hard: latent variables must be summed or integrated out, and the logarithm of a sum does not separate. EM replaces the hard problem with a succession of easy ones, guaranteeing that likelihood never decreases.
This lesson builds EM from a single identity, the decomposition of log-likelihood into a lower bound plus KL divergence, and derives everything else: the two steps, monotonicity, the points it converges to, why it is sometimes painfully slow, variants used in practice, and conditions under which EM with missing data is valid.
Recap: Jensen and KL non-negativity
Two inequalities underpin the whole lesson. The first is Jensen’s inequality for the strictly concave logarithm: if is a random variable with finite expectation,
with equality if and only if is constant almost surely. The second is Gibbs’ inequality: for two distributions and on the same space,
with equality if and only if (almost surely). They are the same inequality: apply Jensen to with to obtain .
Complete versus incomplete likelihood
Fix notation for the rest of the lesson. Write for all observed data (the whole dataset, not one point) and for all unobserved variables. The model is a family of joint densities , . Sums over become integrals if is continuous; everything below still holds.
With iid data and one latent variable per observation, , the two are
The difference is the position of the logarithm. In a mixture of Gaussians with ,
which separates by component: if you knew the labels, each would be the mean of its points and each its proportion. By contrast couples all parameters inside the logarithm, is not concave, has at least equivalent maxima from label permutations, and has no closed-form maximum.
Missing data have the same structure. If each row is split into observed and missing parts, , the latent variables are , complete likelihood is the model likelihood for full rows, and incomplete likelihood integrates out what is missing. EM turns the hard problem, maximizing , into a succession of problems like the easy one, maximizing with latent variables “filled in” correctly. The lower bound tells us what that means.
The lower bound
Proof
For every with , the product rule gives , with both factors positive. Take logarithms and subtract :
Take expectations with . The first term on the right does not depend on and comes out unchanged; the second is . This gives . The inequality and equality case follow from Gibbs’ inequality.
∎is called the EM lower bound, evidence lower bound (ELBO), or, with its sign reversed, variational free energy by analogy with statistical physics: acts as energy (with reversed sign) and as entropy. The bound also follows directly from Jensen, , but that route hides the key point: the gap is exactly a KL divergence, and closes by choosing equal to the posterior.
Check the identity numerically in the first interactive’s model: a mixture in which only is unknown, with 36 observations in three groups.
import numpy as np
from scipy.stats import norm
from scipy.special import logsumexp, expit
def grupo(c, s, m):
# m cuantiles exactos de N(c, s^2): datos deterministas, sin muestreo
return c + s * norm.ppf((np.arange(m) + 0.5) / m)
s = 3.0
x = np.concatenate([grupo(-s, 0.6, 10), grupo(0, 0.6, 14), grupo(s, 0.6, 12)])
def log_joint(theta):
# columna 0: componente fija N(0, 1); columna 1: componente móvil N(theta, 1)
return np.log(0.5) + np.stack([norm.logpdf(x), norm.logpdf(x - theta)], axis=1)
def ell(theta):
return logsumexp(log_joint(theta), axis=1).sum()
def cota(r, theta):
# L(q, theta) con q(z_i = 1) = r_i: E_q[log p(x, z)] + H(q)
A = log_joint(theta)
Rq = np.stack([1 - r, r], axis=1)
H = -np.sum(Rq * np.log(np.clip(Rq, 1e-300, None)))
return np.sum(Rq * A) + H
def kl(r, theta):
p = expit(x * theta - theta**2 / 2) # posterior de z_i = 1
Rq, P = np.stack([1 - r, r], 1), np.stack([1 - p, p], 1)
return np.sum(Rq * (np.log(np.clip(Rq, 1e-300, None)) - np.log(P)))
rng = np.random.default_rng(0)
theta = 1.3
for _ in range(3):
r = rng.uniform(size=len(x)) # una q cualquiera
print(f"l = {ell(theta):.6f} L + KL = {cota(r, theta) + kl(r, theta):.6f} KL = {kl(r, theta):.3f}")
post = expit(x * theta - theta**2 / 2)
print(f"con q = posterior: L = {cota(post, theta):.6f}, KL = {kl(post, theta):.1e}")
# el paisaje de l(theta): máximos locales en una rejilla fina
g = np.linspace(-6, 6, 4801)
A = np.log(0.5) + np.logaddexp(norm.logpdf(x)[:, None], norm.logpdf(x[:, None] - g[None, :]))
L = A.sum(axis=0) # l(theta) en toda la rejilla de una vez
loc = [i for i in range(1, len(g) - 1) if L[i] > L[i - 1] and L[i] > L[i + 1]]
mins = [i for i in range(1, len(g) - 1) if L[i] < L[i - 1] and L[i] < L[i + 1]]
print("máximos locales:", [(round(g[i], 3), round(L[i], 3)) for i in loc])
print("mínimo local: ", [(round(g[i], 3), round(L[i], 3)) for i in mins])The first line of each pair agrees to the last decimal regardless of , and with equal to the posterior, KL vanishes. The grid also shows that this has two local maxima, near and , separated by a minimum near : the right-hand maximum is global because the right group has 12 points and the left 10.
Drawing the bound
Fix at the posterior for a value , . In this model , and the part of depending on is . Using the fact that the bound equals at :
This is a parabola in with curvature , touching at and lying below it everywhere else. Its maximum is at the weighted mean .
Three things the figure shows, formalized in the rest of the lesson:
- The bound is tangent. Since is nonnegative and zero at , it has a minimum at , and if everything is differentiable its derivative vanishes there. Thus : the bound not only touches, it has the same slope. Expanded, this is Fisher’s identity, : the observed-likelihood gradient is the posterior expectation of the complete-likelihood gradient.
- The M-step cannot overshoot. Jumping to the parabola’s maximum raises the bound, which lies below , so increases by at least as much. The interactive decomposes each increase into “the increase in the bound” plus “the KL gap that opens.”
- The destination depends on the start. From , EM climbs to the left local maximum and stays there. The bound at that point is tangent to at a maximum of , so the M-step does not move it: nothing in the algorithm gets it out.
The EM algorithm
The decomposition suggests maximizing instead of , alternating the two variables.
The E-step sets to the unique point making the bound exact at ; the M-step maximizes expected complete likelihood. It “fills in” the latent variables, but not with a value: with their entire posterior distribution.
When the complete model belongs to the exponential family, , depends on the data only through . Then:
- the E-step calculates the expected sufficient statistics ;
- the M-step solves the same equations as the complete-data maximum likelihood estimator, with replaced by .
In the Gaussian mixture, comprises counts , sums and products ; their expectations use responsibilities , and the M-step gives exactly the formulas for EM for Gaussian mixtures from the previous lesson. With Gaussian missing data, comprises sums of and , and the E-step needs the conditional mean and covariance of the missing values (as you will see in the missing-data section).
If you also add a prior , the same derivation with gives EM for MAP estimation: the M-step maximizes and the quantity rising monotonically is . This is used to avoid probabilities exactly 0 or 1 in Bernoulli mixtures.
Monotonicity and convergence
Proof
With , decomposition at and gives
because at the KL divergence is zero. Subtract and use : the entropy terms cancel.
∎This result is the robust part of EM monotonicity and convergence. It has an immediate practical consequence: in exact EM, log-likelihood never decreases. If you see it decrease, even in the fifth decimal, there is an implementation error (an E-step that is not the exact posterior, an M-step that does not maximize, or computed differently) or a numerical problem to locate, not noise. The implementation section turns this observation into an automatic check.
If is bounded above, the sequence is monotone and bounded and therefore converges. But that says nothing about where goes, or even whether it converges. That analysis is Wu’s.
The proof of the first point applies Zangwill’s global convergence theorem to the EM map; here we give the part explaining why stationary points arise.
Proof
Let be an EM fixed point in the interior of , meaning , and suppose is differentiable in its first argument. Being an interior maximum, . By tangency of the bound (Fisher’s identity), . EM fixed points are therefore stationary points of .
∎A stationary point may be a local maximum that is not global, a saddle point or, if you start exactly there, even a local minimum. Stationarity is guaranteed, not optimality. Wu gives an additional condition excluding stationary points that are not local maxima (the M-step must be able to strictly increase at those points), but it is rarely checkable. In practice, saddle points and minima are unstable: rounding noise or generic initialization avoids them. Local maxima are not. The clearest example of a saddle from which EM cannot escape is a symmetry preserved by the algorithm. Murray (1977), discussing Dempster, Laird and Rubin’s paper, noted that EM can converge to a saddle; the cell reproduces this with a bivariate normal of known means and twelve pairs, four complete and eight with one coordinate missing.
import numpy as np
completos = np.array([[1, 1], [1, -1], [-1, 1], [-1, -1]], float)
solo_x1 = np.array([2, 2, -2, -2], float) # x2 perdida
solo_x2 = np.array([2, 2, -2, -2], float) # x1 perdida
n = len(completos) + len(solo_x1) + len(solo_x2)
def loglik(S):
# log-verosimilitud observada, salvo constante, con medias conocidas iguales a 0
Si = np.linalg.inv(S)
l = -0.5 * len(completos) * np.log(np.linalg.det(S)) - 0.5 * np.sum((completos @ Si) * completos)
l += -0.5 * len(solo_x1) * np.log(S[0, 0]) - 0.5 * np.sum(solo_x1**2) / S[0, 0]
l += -0.5 * len(solo_x2) * np.log(S[1, 1]) - 0.5 * np.sum(solo_x2**2) / S[1, 1]
return l
def paso_em(S):
T = completos.T @ completos
# filas con x2 perdida: E[x2 | x1] = b x1 y Var[x2 | x1] = v
b, v = S[0, 1] / S[0, 0], S[1, 1] - S[0, 1]**2 / S[0, 0]
a2 = np.sum(solo_x1**2)
T = T + np.array([[a2, b * a2], [b * a2, b * b * a2 + len(solo_x1) * v]])
b, v = S[0, 1] / S[1, 1], S[0, 0] - S[0, 1]**2 / S[1, 1]
a2 = np.sum(solo_x2**2)
T = T + np.array([[b * b * a2 + len(solo_x2) * v, b * a2], [b * a2, a2]])
return T / n
for rho0 in [0.0, 0.01, -0.01]:
S = np.array([[1.0, rho0], [rho0, 1.0]])
for k in range(300):
S = paso_em(S)
rho = S[0, 1] / np.sqrt(S[0, 0] * S[1, 1])
print(f"rho0 = {rho0:+.2f} -> s11 = {S[0, 0]:.4f}, s22 = {S[1, 1]:.4f}, rho = {rho:+.4f}, l = {loglik(S):.4f}")
# naturaleza del punto (s11, s22, rho) = (2.5, 2.5, 0): hessiano numérico de l
def l_par(p):
s11, s22, r = p
c = r * np.sqrt(s11 * s22)
return loglik(np.array([[s11, c], [c, s22]]))
p0, h = np.array([2.5, 2.5, 0.0]), 1e-4
H = np.zeros((3, 3))
for i in range(3):
for j in range(3):
ei, ej = np.eye(3)[i] * h, np.eye(3)[j] * h
H[i, j] = (l_par(p0 + ei + ej) - l_par(p0 + ei - ej) - l_par(p0 - ei + ej) + l_par(p0 - ei - ej)) / (4 * h * h)
print("autovalores del hessiano en (2.5, 2.5, 0):", np.round(np.linalg.eigvalsh(H), 4))From , EM converges to and , and never escapes: with zero covariance the E-step imputes and the M-step returns zero covariance again. The Hessian has two negative eigenvalues and one positive (in the direction): a saddle point. Merely setting makes EM reach one of two global maxima, and , with higher log-likelihood. Mixtures behave the same if two components start identical: the E-step gives them equal responsibilities and the M-step leaves them identical forever.
Speed: linear rate and missing information
Near a maximum , EM behaves like a fixed-point iteration with . If is differentiable,
and error decreases as , where is the spectral radius. Dempster, Laird and Rubin calculated and gave it a statistical interpretation. Define, all evaluated at :
- complete information , the Fisher information you would have if you also observed (averaged over the posterior);
- missing information , what is missing because is unseen;
- observed information .
Since for every , taking the posterior expectation at and differentiating twice gives the missing information principle (Orchard and Woodbury, 1972): . Observed information is complete information minus missing information.
Proof
is similar to the symmetric matrix , so its eigenvalues are real. is positive semidefinite (it is the posterior covariance of the score of , or, without that step, the negative Hessian of a function maximized at ), so they are . And with the last term positive definite, so they are . For linear convergence, apply the fixed-point theorem using a norm adapted to .
∎The interpretation is direct: EM is slower when a larger fraction of information is missing. If latent variables contribute little (well-separated components, few missing entries), and EM converges in a handful of iterations. If almost all information is in what you cannot see (overlapping components, much missing data), and EM crawls.
An explicit example: and , observing only . With complete data, is estimated from the and . With observed data, and . The rate is , and indeed the EM step is exactly . With , . The second interactive, in the next section, uses this same model.
The cell calculates the same table as the interactive so you can check its numbers.
import numpy as np
from scipy.stats import norm
from scipy.optimize import brentq
def datos(delta, w, n=400):
n1 = round(n * w)
q = lambda c, m: c + norm.ppf((np.arange(m) + 0.5) / m)
x = np.concatenate([q(-delta / 2, n1), q(delta / 2, n - n1)])
return norm.pdf(x + delta / 2), norm.pdf(x - delta / 2)
def paso_em(f1, f2, p):
return np.mean(p * f1 / (p * f1 + (1 - p) * f2))
print(" Delta pi* 1 - Iobs/Ic tasa medida iteraciones hasta 1e-8")
for delta in [0.5, 1.0, 1.5, 2.0, 3.0, 4.0]:
f1, f2 = datos(delta, 0.3)
d1 = lambda p: np.sum((f1 - f2) / (p * f1 + (1 - p) * f2)) # l'(pi), decreciente
ps = brentq(d1, 1e-9, 1 - 1e-9, xtol=1e-15)
Iobs = np.sum(((f1 - f2) / (ps * f1 + (1 - ps) * f2))**2)
Ic = len(f1) / (ps * (1 - ps))
p, err = 0.9, [0.4]
while err[-1] > 1e-12 and len(err) < 20000:
p = paso_em(f1, f2, p)
err.append(abs(p - ps))
err = np.array(err)
k8 = int(np.argmax(err < 1e-8))
cocientes = err[1:] / err[:-1]
medida = np.median(cocientes[(err[:-1] < 1e-3) & (err[1:] > 1e-10)])
print(f"{delta:5.1f} {ps:.4f} {1 - Iobs / Ic:.4f} {medida:.4f} {k8:6d}")The missing-information fraction and measured rate agree to all four digits in every row. Moving from to raises the rate from below 0.1 to almost 0.95 and multiplies iterations more than fortyfold. Note that this is the mixture’s easiest parameter: with everything unknown (means, variances and weights), the same separation gives a rate of 0.97 and almost 600 iterations in the second practice.
The stopping criterion can mislead
The linear rate has an often-forgotten practical consequence. If in the scalar case, the geometric series gives
With , remaining error is about 99 times the last step. A criterion like “stop when changes by less than ” is worse: near the maximum , quadratic in error and also small precisely when is small, that is, when EM is slow. If parameters matter (not only likelihood), estimate from the ratio of successive steps and correct or accelerate.
Neal and Hinton’s view: coordinate ascent
Neal and Hinton (1998) read the decomposition differently. Call the bound , viewed as a function of two arguments: a distribution over latent variables and parameters . Then:
- the E-step is , because is maximal when KL is zero;
- the M-step is .
EM is block coordinate ascent on . Neal and Hinton also proved that if is a local (global) maximum of , then is a local (global) maximum of : maximizing over both variables maximizes . This view has three consequences:
- Any step increasing works. Exact maximization of neither coordinate is required. A partial E-step moving closer to the posterior without reaching it, or a partial M-step increasing without maximizing it (generalized EM), maintains monotonicity of .
- Incremental EM. For iid data, and . You can update for one observation (or a minibatch) and immediately perform the M-step with accumulated sufficient statistics , subtracting the old contribution and adding the new. Each update increases , and the M-step uses new information without waiting for a full pass, so it often needs fewer passes than standard EM (Neal and Hinton illustrate this with a Gaussian mixture).
- Sparse EM. In a mixture with many components, most responsibilities for each point are almost zero. Freeze them and update only those of a few plausible components, with a full E-step occasionally.
To see the geometry, must fit on one axis. In the model , , the family , indexed by scalar , contains the posterior for each , and is a function of two real variables. Computing Gaussian expectations, per observation and up to a constant,
Maximizing over gives (the E-step), and maximizing over gives (the M-step). The Hessian of in is : as it is almost singular and contours are elongated ellipses along the diagonal.
The figure shows the previous section’s linear rate from another angle. EM’s staircase between the diagonal and M-step line shrinks by a factor each iteration, because the lines intersect at an ever smaller angle as : the zigzag of block descent in a narrow valley. Joint gradient ascent with a fixed step cannot escape either: with its best rate is 0.896 versus EM’s 0.8, and beyond step it diverges. EM has no learning rate: every move is an exact maximization, which makes it popular despite its slowness.
The move to an online version is natural. Cappé and Moulines (2009) propose, for complete exponential-family models, maintaining an estimate of per-observation sufficient statistics and updating it with each new observation as a Robbins-Monro stochastic approximation:
where is the M-step applied to and are decreasing steps with and . They show convergence to stationary points of the KL divergence between data distribution and model and, with steps , , and iterate averaging, to the same optimal rate as maximum likelihood. This version is used for data streams or datasets too large for memory.
EM as an MM algorithm
An even more general view does not need latent variables.
The ascent property follows in one line:
EM is the case and : decomposition proves it minorizes, and the E-step constructs it. The orange parabola in the first interactive is precisely a minorizer. MM is broader than EM because the minorizer may come from any inequality, not only introducing latent variables. The tutorial by Hunter and Lange (2004) collects common tools: Jensen (giving EM), the arithmetic-geometric mean inequality, a convex function’s tangent bound, or a quadratic bound with uniform Hessian. Two examples worth knowing:
- Logistic regression with a quadratic bound. The logistic log-likelihood Hessian satisfies . The quadratic with this curvature touching at minorizes it, and its maximum gives : a Newton step with a fixed Hessian factored only once (Böhning and Lindsay, 1988).
- Geometric median. Minimizing with the majorizer gives the Weiszfeld iteration, a weighted average with weights .
MM and EM share the guarantee’s structure and its price: monotonicity without a learning rate, in exchange for linear convergence that becomes slower as the minorizer approximates ‘s curvature more poorly. In EM, that curvature difference is precisely versus .
EM variants
Each part of EM can be relaxed, and these relaxations are the EM variants used in practice.
- Generalized EM (GEM). Already in Dempster, Laird and Rubin: it suffices to find with , for example a few gradient or Newton steps on . It preserves monotonicity (the theorem above already covers it).
- ECM (expectation conditional maximization, Meng and Rubin, 1993). When the M-step has no closed form but does by parameter blocks, replace it with conditional maximizations: first with fixed, then with the new . It is a GEM and preserves EM convergence properties.
- Hard EM (or classification EM). The E-step replaces the posterior with its mode: places all mass on . Then and the algorithm is coordinate ascent on complete likelihood over , not on . Lloyd’s algorithm is hard EM for isotropic Gaussian mixtures with equal variance and weight. It is faster and finishes in finitely many steps, but estimates something different: with overlapping components its means are biased outward.
- Stochastic and Monte Carlo EM. When the E-step expectation is intractable, approximate it with posterior samples. Stochastic EM (SEM, Celeux and Diebolt, 1985) imputes one sample per iteration: iterates form a Markov chain that fluctuates around the estimator rather than converging to a point, and is averaged. Monte Carlo EM (Wei and Tanner, 1990) uses samples and increases with iterations. SAEM (Delyon, Lavielle and Moulines, 1999) combines one sample per iteration with stochastic-approximation averaging of , and converges.
- Incremental and online EM. From the previous section: update one observation at a time (Neal and Hinton) or sufficient statistics with decreasing steps (Cappé and Moulines).
| Variant | What changes | Guarantee | When to use |
|---|---|---|---|
| EM | exact E- and M-steps | does not decrease; stationary points | closed-form E- and M-steps |
| GEM, ECM | M-step only increases | does not decrease | no closed-form M-step |
| incremental | E-step on one observation or minibatch | does not decrease | many observations fitting in memory |
| online | statistics with decreasing steps | stationary points in the limit | streams, data too large for memory |
| stochastic, MCEM, SAEM | E-step by sampling | in distribution or with averaging | intractable posterior |
| hard | mode instead of posterior | complete likelihood does not decrease | speed; biases parameters |
The cell compares EM, hard EM and online EM on a two-Gaussian mixture with variance 1 and equal weights, means at (separation 2, substantial overlap), and .
import numpy as np
rng = np.random.default_rng(1)
n, Delta = 20000, 2.0
z = rng.uniform(size=n) < 0.5
x = np.where(z, -Delta / 2, Delta / 2) + rng.normal(size=n)
def resp(x, mu):
a = -0.5 * (x[:, None] - mu)**2 # varianzas 1 y pesos 1/2 conocidos
a -= a.max(axis=1, keepdims=True)
r = np.exp(a)
return r / r.sum(axis=1, keepdims=True)
mu = np.array([-0.3, 0.3])
for k in range(500):
R = resp(x, mu)
nuevo = R.T @ x / R.sum(axis=0)
if np.max(np.abs(nuevo - mu)) < 1e-9:
break
mu = nuevo
print(f"EM ({k + 1:3d} iteraciones): medias {np.round(mu, 3)}")
mu = np.array([-0.3, 0.3])
for k in range(500):
R = resp(x, mu)
D = (R == R.max(axis=1, keepdims=True)).astype(float) # paso E duro
nuevo = D.T @ x / D.sum(axis=0)
if np.max(np.abs(nuevo - mu)) < 1e-12:
break
mu = nuevo
print(f"EM duro ({k + 1:3d} iteraciones): medias {np.round(mu, 3)}")
# EM en línea: s0 = E[r], s1 = E[r x] por componente; una sola pasada por los datos
s0, s1 = np.array([0.5, 0.5]), np.array([-0.15, 0.15])
mu, prom, inicio = s1 / s0, np.zeros(2), n // 10
for i in range(n):
g = (i + 2) ** -0.6
r = resp(x[i:i + 1], mu)[0]
s0 = s0 + g * (r - s0)
s1 = s1 + g * (r * x[i] - s1)
mu = s1 / s0
if i >= inicio:
prom += (mu - prom) / (i - inicio + 1)
print(f"EM en línea (1 pasada): último {np.round(mu, 3)}, promediado {np.round(prom, 3)}")EM recovers means very close to . Hard EM converges in fewer iterations, but to means shifted outward: every point falling on the wrong side is fully assigned to the other component, so each component is estimated from a truncated normal whose mean lies farther from the center. Online EM makes a single pass; its final iterate still fluctuates with step and the average of iterates is much closer to the EM means.
Missing data: when EM is valid
With missing data, the question is not only how to compute the estimator, but whether it estimates what you want. Rubin (1976) formalized this with an indicator of which entries are missing, distributed as :
- MCAR (missing completely at random): . Missingness does not depend on any data.
- MAR (missing at random): . It may depend on observed values, not missing ones.
- MNAR (missing not at random): it also depends on missing values.
Proof
where the second equality is the MAR assumption, allowing the factor outside the integral. The integral is , and the factor does not depend on .
∎This defines EM with missing data: applied to with , it calculates the correct maximum likelihood estimator under MCAR and MAR. Under MNAR, the mechanism factor depends on , cannot leave the integral, and ignoring it biases the estimator; model explicitly (selection or pattern-mixture models) and, because the data cannot distinguish MAR from MNAR, accompany it with sensitivity analysis.
For a multivariate normal with entries missing at arbitrary positions, sufficient statistics are and . In row , with observed indices and missing indices , the E-step uses the conditional normal:
is (observed and imputed values) and , with equal to in the missing block and zero elsewhere. The M-step is the complete-data step:
The term distinguishes EM from impute-and-forget: filling in the conditional mean and estimating covariance of filled data underestimates variances because it treats imputed values as observed without uncertainty.
In the initial state (MAR, 40% of missing, more likely when is larger), complete cases lose mostly high- rows, and since correlates with , their mean is too low. EM uses incomplete rows through : the regression of on estimated from complete rows is valid under MAR because missingness depends only on , and it reconstructs the marginal distribution of . Mean imputation leaves exactly equal to complete cases (it fills with their mean) and also compresses variance and correlation because it adds points with no spread in . Under MNAR (missingness depends on itself), EM reduces mean bias because carries some information about missing values, but does not eliminate it, and the interactive cannot help detect it: observed data alone do not distinguish MAR from MNAR.
Implementation from scratch
What all EM algorithms share fits in a base class: a loop alternating e_step and m_step, evaluating log-likelihood and checking monotonicity every iteration. This check is the safety net separating a correct implementation from one that only looks correct.
import numpy as np
from scipy.special import logsumexp
from sklearn.datasets import load_digits
class EM:
"""Bucle común. Las subclases definen e_step, m_step y objective (log-verosimilitud, más log p(theta) si es MAP)."""
def e_step(self, X): raise NotImplementedError
def m_step(self, X, stats): raise NotImplementedError
def objective(self, X): raise NotImplementedError
def fit(self, X, max_iter=200, rtol=1e-8, check=True):
self.history = [self.objective(X)]
for it in range(1, max_iter + 1):
self.m_step(X, self.e_step(X))
obj = self.objective(X)
prev = self.history[-1]
if check and obj < prev - 1e-10 * abs(prev):
raise RuntimeError(f"el objetivo bajó en la iteración {it}: {prev:.6f} -> {obj:.6f}")
self.history.append(obj)
if obj - prev < rtol * abs(obj):
break
return self
class BernoulliMixture(EM):
"""Mezcla de K productos de Bernoulli, con a priori Beta(1 + a, 1 + a) sobre cada mu_kj (EM para el MAP)."""
def __init__(self, K, seed, a=1e-3):
self.K, self.rng, self.a = K, np.random.default_rng(seed), a
def init(self, X):
self.pi = np.full(self.K, 1 / self.K)
self.mu = self.rng.uniform(0.25, 0.75, size=(self.K, X.shape[1]))
return self
def log_joint(self, X): # n x K: log pi_k + log p(x_i | mu_k)
return np.log(self.pi) + X @ np.log(self.mu).T + (1 - X) @ np.log1p(-self.mu).T
def e_step(self, X):
A = self.log_joint(X)
return np.exp(A - logsumexp(A, axis=1, keepdims=True)) # responsabilidades r_ik
def m_step(self, X, R):
Nk = R.sum(axis=0)
self.pi = Nk / len(X)
self.mu = (R.T @ X + self.a) / (Nk[:, None] + 2 * self.a)
def objective(self, X):
log_prior = self.a * np.sum(np.log(self.mu) + np.log1p(-self.mu))
return logsumexp(self.log_joint(X), axis=1).sum() + log_prior
digits = load_digits()
X = (digits.data > 7).astype(float) # 1797 dígitos de 8 x 8, binarizados
y = digits.target
mejor = None
for seed in range(3):
m = BernoulliMixture(10, seed).init(X).fit(X)
print(f"semilla {seed}: {len(m.history) - 1:3d} iteraciones, objetivo final {m.history[-1]:.1f}, "
f"menor subida {np.min(np.diff(m.history)):.2e}")
if mejor is None or m.history[-1] > mejor.history[-1]:
mejor = m
z = mejor.e_step(X).argmax(axis=1)
pureza = sum(np.bincount(y[z == k]).max() for k in range(10) if np.any(z == k)) / len(y)
print(f"pureza del mejor ajuste respecto a las etiquetas (que EM no ha visto): {pureza:.3f}")The three seeds end at different objectives: different local maxima, with hundreds of log-likelihood units between best and worst. The smallest per-iteration increase is positive in all three, as the theorem requires. Purity measures the fraction of digits in a group whose majority label matches theirs; without seeing labels, the mixture groups most by digit. Look at the ten prototypes :
import matplotlib.pyplot as plt
orden = np.argsort(-mejor.pi)
fig, ejes = plt.subplots(1, 10, figsize=(10, 1.4))
for eje, k in zip(ejes, orden):
eje.imshow(mejor.mu[k].reshape(8, 8), cmap="gray_r", vmin=0, vmax=1)
eje.set_title(f"{mejor.pi[k]:.2f}", fontsize=8)
eje.axis("off")
plt.show()Now use the check. This subclass has a common error: the E-step forgets . Responsibilities still sum to 1 and the result looks reasonable, but they are no longer the posterior.
class BernoulliMixtureConError(BernoulliMixture):
def e_step(self, X):
A = np.log(self.pi) + X @ np.log(self.mu).T # falta (1 - X) @ log(1 - mu).T
return np.exp(A - logsumexp(A, axis=1, keepdims=True))
for seed in range(3):
try:
BernoulliMixtureConError(10, seed).init(X).fit(X)
print(f"semilla {seed}: no ha saltado la comprobación")
except RuntimeError as e:
print(f"semilla {seed}: {e}")For at least one seed the objective decreases after a few iterations and the check catches it. For another it may not trigger during the fit: monotonicity is necessary for correct EM, not sufficient. Therefore combine it with a check that the gradient of is near zero at the endpoint.
The same base class works for a normal with missing data. Here a bivariate example has missing under MAR (more likely as increases); the final coding exercise asks for the general version with arbitrary patterns in dimensions.
from scipy.stats import multivariate_normal
class Gauss2Faltante(EM):
"""x2 puede faltar (NaN); x1 se observa siempre."""
def init(self, X):
obs = ~np.isnan(X[:, 1])
self.mu = np.array([X[:, 0].mean(), X[obs, 1].mean()])
self.S = np.diag([X[:, 0].var(), X[obs, 1].var()])
return self
def e_step(self, X):
falta = np.isnan(X[:, 1])
b = self.S[0, 1] / self.S[0, 0]
v = self.S[1, 1] - self.S[0, 1] * b
Xh = X.copy()
Xh[falta, 1] = self.mu[1] + b * (X[falta, 0] - self.mu[0])
extra = np.zeros(len(X))
extra[falta] = v # Var[x2 | x1]: el término que olvida la imputación simple
return Xh, extra
def m_step(self, X, stats):
Xh, extra = stats
self.mu = Xh.mean(axis=0)
S = Xh.T @ Xh / len(X) - np.outer(self.mu, self.mu)
S[1, 1] += extra.mean()
self.S = S
def objective(self, X):
falta = np.isnan(X[:, 1])
l = multivariate_normal(self.mu, self.S).logpdf(X[~falta]).sum()
return l + multivariate_normal(self.mu[0], self.S[0, 0]).logpdf(X[falta, 0]).sum()
rng = np.random.default_rng(3)
n, rho = 2000, 0.7
Xc = rng.multivariate_normal([0, 0], [[1, rho], [rho, 1]], size=n)
p_falta = 1 / (1 + np.exp(-(2.5 * Xc[:, 0] - 0.5))) # MAR: depende solo de x1
X = Xc.copy()
X[rng.uniform(size=n) < p_falta, 1] = np.nan
cc = X[~np.isnan(X[:, 1])]
m = Gauss2Faltante().init(X).fit(X, max_iter=500, rtol=1e-12)
print(f"falta x2 en {np.isnan(X[:, 1]).mean():.0%} de las filas; EM: {len(m.history) - 1} iteraciones")
print(f"{'':18s}{'mu2':>8s}{'s22':>8s}{'rho':>8s}")
def fila(nombre, mu2, S):
print(f"{nombre:18s}{mu2:8.3f}{S[1, 1]:8.3f}{S[0, 1] / np.sqrt(S[0, 0] * S[1, 1]):8.3f}")
fila("muestra completa", Xc[:, 1].mean(), np.cov(Xc.T, bias=True))
fila("casos completos", cc[:, 1].mean(), np.cov(cc.T, bias=True))
fila("EM", m.mu[1], m.S)With 42% of missing, complete cases clearly underestimate , variance and correlation because they have lost mostly high- rows. EM recovers all three full-sample values with error on the order of sampling error. For this pattern (only one variable missing, the other always observed), the maximum likelihood estimator even has a closed form, and EM converges to it.
EM versus direct optimization
EM is not the only way to maximize . With Fisher’s identity gradient you can use any optimizer, such as L-BFGS, on an unconstrained parameterization (weight logit, log standard deviations). The cell compares, for a two-Gaussian 1D mixture with all five parameters unknown, observations and true weights and :
- EM, with its linear rate measured from iterates;
- L-BFGS-B from
scipy.optimize, with exact gradient; - SQUAREM (Varadhan and Roland, 2008), an extrapolation using two EM steps to estimate the zigzag direction and make a longer jump, with a safeguard falling back to an EM step if the jump reduces .
import numpy as np
from scipy.optimize import minimize
from scipy.special import logsumexp, expit
def log_joint(x, th):
w, m1, m2, s1, s2 = th
return np.stack([np.log(w) - np.log(s1) - (x - m1)**2 / (2 * s1**2),
np.log1p(-w) - np.log(s2) - (x - m2)**2 / (2 * s2**2)], 1) - 0.5 * np.log(2 * np.pi)
def loglik(x, th):
return logsumexp(log_joint(x, th), axis=1).sum()
def paso_em(x, th):
A = log_joint(x, th)
R = np.exp(A - logsumexp(A, axis=1, keepdims=True))
N = R.sum(axis=0)
m = R.T @ x / N
s = np.sqrt((R * (x[:, None] - m)**2).sum(axis=0) / N)
return np.array([N[0] / len(x), m[0], m[1], s[0], s[1]])
def em(x, th, tol=1e-9, kmax=3000):
tray = [th]
for _ in range(kmax):
th = paso_em(x, th)
tray.append(th)
if np.max(np.abs(tray[-1] - tray[-2])) < tol:
break
return th, np.array(tray)
def menos_ll_y_grad(u, x):
# u = (logit w, m1, m2, log s1, log s2); gradiente por la identidad de Fisher
w, m1, m2, s1, s2 = expit(u[0]), u[1], u[2], np.exp(u[3]), np.exp(u[4])
A = log_joint(x, (w, m1, m2, s1, s2))
L = logsumexp(A, axis=1)
R = np.exp(A - L[:, None])
g = np.array([np.sum(R[:, 0] - w),
np.sum(R[:, 0] * (x - m1)) / s1**2, np.sum(R[:, 1] * (x - m2)) / s2**2,
np.sum(R[:, 0] * ((x - m1)**2 / s1**2 - 1)), np.sum(R[:, 1] * ((x - m2)**2 / s2**2 - 1))])
return -L.sum(), -g
def squarem(x, th, tol=1e-9, kmax=2000):
evals = 0
for k in range(1, kmax + 1):
t1 = paso_em(x, th); t2 = paso_em(x, t1); evals += 2
r, v = t1 - th, t2 - 2 * t1 + th
a = min(-np.linalg.norm(r) / max(np.linalg.norm(v), 1e-300), -1.0)
tp = th - 2 * a * r + a * a * v
if not (0 < tp[0] < 1 and tp[3] > 0 and tp[4] > 0) or loglik(x, tp) < loglik(x, th):
tp = t2 # salvaguarda: si el salto no sube l, nos quedamos con EM
nuevo = paso_em(x, tp); evals += 1
if np.max(np.abs(nuevo - th)) < tol:
return nuevo, k, evals
th = nuevo
return th, kmax, evals
rng = np.random.default_rng(0)
print(" Delta | EM: iter tasa | L-BFGS: iter eval | SQUAREM: ciclos pasos EM | max |Delta l|")
resultados = {}
for Delta in [4.0, 3.0, 2.5]:
z = rng.uniform(size=1000) < 0.4
x = np.where(z, -Delta / 2, Delta / 2) + rng.normal(size=1000)
th0 = np.array([0.5, np.quantile(x, 0.25), np.quantile(x, 0.75), x.std(), x.std()])
thE, tray = em(x, th0)
pasos = np.linalg.norm(np.diff(tray, axis=0), axis=1)
cola = pasos[len(pasos) // 2:-1]
tasa = np.median(cola[1:] / cola[:-1])
u0 = np.array([0.0, th0[1], th0[2], np.log(th0[3]), np.log(th0[4])])
res = minimize(menos_ll_y_grad, u0, args=(x,), jac=True, method="L-BFGS-B",
options=dict(maxiter=5000, gtol=1e-8, ftol=1e-15))
thS, kS, eS = squarem(x, th0)
lls = [loglik(x, thE), -res.fun, loglik(x, thS)]
print(f" {Delta:.1f} | {len(tray) - 1:8d} {tasa:.4f} | {res.nit:12d} {res.nfev:4d} | {kS:15d} {eS:8d} | {max(lls) - min(lls):.1e}")
resultados[Delta] = (x, thE, tasa)All three methods reach the same log-likelihood (the last column gives their maximum difference). Cost changes. EM needs tens of iterations with and hundreds with because its rate approaches 1; L-BFGS stays below twenty iterations in all three cases, and SQUAREM, using the same EM step as its only building block, needs 30, 42 and 60 EM steps versus 79, 221 and 580: its advantage grows with the rate. EM’s advantage is not speed: each step is simple, respects constraints (weights on the simplex, positive variances) without reparameterization, has no learning rate and never decreases .
The measured rate should be the largest eigenvalue of . Calculate by numerically differentiating the EM map itself, without writing down Fisher information; this is the idea of Meng and Rubin’s (1991) SEM (supplemented EM) algorithm for obtaining standard errors from EM.
x, thE, tasa = resultados[3.0]
thE, _ = em(x, thE, tol=1e-13) # afinar el punto fijo
h = 1e-6
DM = np.column_stack([(paso_em(x, thE + h * e) - paso_em(x, thE - h * e)) / (2 * h) for e in np.eye(5)])
autovalores = np.sort(np.linalg.eigvals(DM).real)[::-1]
print("autovalores de DM:", np.round(autovalores, 4))
print(f"tasa medida en los iterados: {tasa:.4f}")The largest eigenvalue matches the measured rate, and the others are smaller: after a few iterations error aligns with the dominant eigenvector, the least well-determined parameter direction. The library you normally use, sklearn.mixture.GaussianMixture, implements EM with a stopping criterion on the increase in mean lower bound per observation (tol=1e-3 by default). With overlapping components, this criterion stops far from the parameter optimum, as you have just seen.
Bridge: variational inference and variational autoencoders
EM’s E-step requires calculating the posterior . In a mixture this is a sum of terms per observation; in a model with many coupled latent variables (a topic model, a deep network) it is intractable. The decomposition says what to do: restrict to a tractable family and maximize over . Now the E-step no longer closes the KL gap, the bound is not tangent, and the quantity increasing monotonically is , not . This is variational EM, and its inference part is the variational inference of module 14.
The variational autoencoder goes further: instead of optimizing one per observation, an encoder network produces the posterior approximation for any (amortized inference), and and are optimized jointly by stochastic gradient on the same , the ELBO. The identity you proved at the start is exactly the one used there.
Common mistakes
Exercises
Step 1 of 4. Which identity starts the proof for each with ?
Step 1 of 4. What is ?
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
em_normal_faltantes(X, max_iter=500, tol=1e-10), accepting a matrix X of shape (n, d) with np.nan for missing entries (arbitrary patterns; some rows may have no observed entries) and returning (mu, Sigma), the maximum likelihood estimates of and (divisor ) under MAR. Initialize using column means and variances (ignoring NaNs) and zero covariances, and stop when the largest absolute change in mu and Sigma is less than tol. Do not forget the conditional covariance term in the M-step.import numpy as np
def em_normal_faltantes(X, max_iter=500, tol=1e-10):
X = np.asarray(X, dtype=float)
n, d = X.shape
# tu código: arranque, y repetir paso E (media y covarianza condicionales de cada fila) y paso M
mu = np.nanmean(X, axis=0)
Sigma = np.diag(np.nanvar(X, axis=0))
return mu, SigmaSummary
- Incomplete likelihood has the logarithm outside the sum over latent variables; complete likelihood has it inside. The M-step maximizes expected complete likelihood , which in the exponential family is the MLE with sufficient statistics replaced by posterior expectations.
- Monotonicity: , also for generalized EM and ECM. If decreases, there is an error.
- Wu (1983): under regularity, limit points are stationary. They may be local maxima or saddle points (the bivariate normal with ); restart from several points.
- Speed: linear convergence with rate equal to the largest eigenvalue of , the fraction of missing information. Remaining error at stopping is about times the last step.
- EM is coordinate ascent on (Neal and Hinton) and an MM algorithm. This yields partial steps and incremental and online EM; hard, stochastic and Monte Carlo EM change the E-step.
- With missing data, EM is valid under MCAR and MAR (ignorability), needs conditional covariance as well as mean, and is biased under MNAR.
- Restricting to a tractable family gives variational inference and the VAE ELBO from the same bound.