Latent Variables, EM, and the ELBO

Dive into Deep Learning · §36.7

Latent Variable Models, EM, and the ELBO
mixture models · marginal log-likelihood · soft responsibilities · evidence lower bound · coordinate ascent · pitfalls

500 Points from Two Populations, Labels Lost

Motivation & Core Problem

  • With observed labels (complete data): Fitting K Gaussian populations takes closed-form per-cluster sample fractions, means, and variances.
  • Without labels (latent variables): Each observation’s probability sums over hidden populations, trapping a sum inside the logarithm of the likelihood.
  • Unifying strategy: Replace missing labels with soft posterior probabilities q(z) and maximize the Evidence Lower Bound (ELBO).

Joint and Marginal Likelihoods with Latent Variables

Generative Structure

p(x, z \mid \boldsymbol{\theta}) = p(z \mid \boldsymbol{\theta})\,p(x \mid z, \boldsymbol{\theta}), \qquad p(x \mid \boldsymbol{\theta}) = \sum_{z} p(x, z \mid \boldsymbol{\theta})

  • Generative story (z \to x): First sample the hidden cause z \sim p(z \mid \boldsymbol{\theta}), then generate the observation x \sim p(x \mid z, \boldsymbol{\theta}).
  • Marginal likelihood (evidence): Because only x is observed, p(x \mid \boldsymbol{\theta}) sums or integrates over every possible latent state z.

Complete-Data Oracle vs. Observed-Data Mixture NLL

Gaussian Mixture Models

\ell(\boldsymbol{\theta}) = -\sum_{i=1}^n \log \Biggl(\sum_{k=1}^K \pi_k\,\mathcal{N}(x_i;\, \mu_k, \sigma_k^2)\Biggr)

  • Complete-data oracle (z_i known): The logarithm hits \mathcal{N}(x_i; \mu_{z_i}, \sigma_{z_i}^2) directly, decoupling into K closed-form quadratics.
  • Observed mixture (z_i hidden): The sum \sum_{k=1}^K sits inside \log(\cdot), coupling all 3K parameters across every data point.

Soft Probabilistic Guesses via Bayes’ Rule

Posterior Responsibilities

P(z = 1 \mid x = 0.5) = \frac{0.5\,e^{-(0.5 + 1)^2 / 2}}{0.5\,e^{-(0.5 + 1)^2 / 2} + 0.5\,e^{-(0.5 - 1)^2 / 2}} = \frac{1}{1 + e} \approx 0.27

  • Fractional responsibility: Under 0.5\,\mathcal{N}(-1, 1) + 0.5\,\mathcal{N}(1, 1), Bayes’ rule assigns x = 0.5 softly (27\% to component 1, 73\% to component 2).
  • Smooth uncertainty: Responsibilities split 50/50 at x = 0 and sharpen to 0.2\% / 99.8\% out at x = 3.

Deriving the Evidence Lower Bound (ELBO)

Jensen’s Inequality

\log p(x \mid \boldsymbol{\theta}) = \log \sum_{z} q(z)\,\frac{p(x, z \mid \boldsymbol{\theta})}{q(z)} \ge \sum_{z} q(z) \log \frac{p(x, z \mid \boldsymbol{\theta})}{q(z)} =: \mathcal{L}(q, \boldsymbol{\theta})

  • Pushing \log inside the sum: For any distribution q(z) over latent states, concavity of \log (\log \mathbb{E}_q[Y] \ge \mathbb{E}_q[\log Y]) yields a global lower bound.
  • Tractable joint log-density: Inside \mathcal{L}(q, \boldsymbol{\theta}), the logarithm acts directly on the complete-data product p(x, z \mid \boldsymbol{\theta}).

Anatomy of the ELBO: Energy Plus Entropy

Decomposing the Lower Bound

\mathcal{L}(q, \boldsymbol{\theta}) = \mathbb{E}_{q(z)}\bigl[\log p(x, z \mid \boldsymbol{\theta})\bigr] + H(q)

  • Expected complete-data log-likelihood (\mathbb{E}_q[\log p(x, z \mid \boldsymbol{\theta})]): The tractable oracle objective weighted by soft probabilities q(z).
  • Shannon entropy bonus (H(q) = -\sum_z q(z)\log q(z)): Rewards spread-out guesses q(z) and drops out when optimizing over \boldsymbol{\theta}.

The Fundamental ELBO–KL Decomposition

Exact Gap Identity

  • Exact identity for the gap: Substituting p(x, z \mid \boldsymbol{\theta}) = p(z \mid x, \boldsymbol{\theta})\,p(x \mid \boldsymbol{\theta}) into \mathcal{L}(q, \boldsymbol{\theta}) proves: \log p(x \mid \boldsymbol{\theta}) = \mathcal{L}(q, \boldsymbol{\theta}) + D_{\mathrm{KL}}\bigl(q(z) \,\|\, p(z \mid x, \boldsymbol{\theta})\bigr)
  • Non-negativity and tightness: Because D_{\mathrm{KL}} \ge 0, \mathcal{L}(q, \boldsymbol{\theta}) \le \log p(x \mid \boldsymbol{\theta}) everywhere, with equality (\mathcal{L} = \log p) if and only if q(z) = p(z \mid x, \boldsymbol{\theta}).
  • Geometric tangency: Setting q to the posterior at \boldsymbol{\theta}^{(t)} makes the lower bound curve touch the true log-likelihood curve tangentially at \boldsymbol{\theta}^{(t)}.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Worked Example: Measuring the ELBO Gap by Hand

Numerical Verification at x = 0.5

  • Exact identity at x = 0.5 (\log p(x) = -1.42): For every guess q(z), \mathcal{L}(q) + D_{\mathrm{KL}}(q \,\|\, p(z \mid x)) = -1.42 nats.
  • Exact posterior q = (0.27, 0.73): Achieves \mathcal{L} = -1.42 with zero KL gap.
  • Why hard assignment (0, 1) loses twice as much as uniform (0.5, 0.5): Setting q = (0, 1) forfeits the entropy bonus (H(q) = 0), incurring a 0.31-nat KL gap vs. 0.12 nats for (0.5, 0.5).

Expectation–Maximization as Coordinate Ascent

The EM Algorithm

  • E-step (Expectation): Fix \boldsymbol{\theta}^{(t)} and set each q_i^{(t)}(z) = p(z \mid x_i, \boldsymbol{\theta}^{(t)}), closing the KL gap to zero so the ELBO touches \log P(X \mid \boldsymbol{\theta}^{(t)}).
  • M-step (Maximization): Fix the responsibilities q_i^{(t)} and maximize the expected complete-data log-likelihood over \boldsymbol{\theta}: \boldsymbol{\theta}^{(t+1)} = \mathop{\mathrm{argmax}}_{\boldsymbol{\theta}} \sum_{i=1}^n \mathbb{E}_{q_i^{(t)}(z)}\bigl[\log p(x_i, z \mid \boldsymbol{\theta})\bigr]

Theorem: EM Monotonically Improves Likelihood

Convergence Guarantee

Why can an EM step never decrease the true observed-data log-likelihood \log P(X \mid \boldsymbol{\theta})? Chaining three relations proves monotonicity in one line:

\log P(X \mid \boldsymbol{\theta}^{(t+1)}) \ge \sum_{i=1}^n \mathcal{L}\bigl(q_i^{(t)}, \boldsymbol{\theta}^{(t+1)}\bigr) \ge \sum_{i=1}^n \mathcal{L}\bigl(q_i^{(t)}, \boldsymbol{\theta}^{(t)}\bigr) = \log P(X \mid \boldsymbol{\theta}^{(t)})

  1. Global lower bound (\ge): The ELBO is a valid lower bound on \log P(X \mid \boldsymbol{\theta}) at the new parameters \boldsymbol{\theta}^{(t+1)} for any q_i^{(t)}.
  2. M-step optimization (\ge): Choosing \boldsymbol{\theta}^{(t+1)} to maximize the bound guarantees \sum_i \mathcal{L}(q_i^{(t)}, \boldsymbol{\theta}^{(t+1)}) \ge \sum_i \mathcal{L}(q_i^{(t)}, \boldsymbol{\theta}^{(t)}).
  3. E-step tightness (=): Because q_i^{(t)} was set to the exact posterior at \boldsymbol{\theta}^{(t)}, the KL gap at \boldsymbol{\theta}^{(t)} is zero.

Why exact posteriors matter: If an algorithm replaces the E-step with hard 0/1 assignments, it still monotonically climbs the ELBO, but because the third step is no longer an equality, the true log-likelihood \log P(X \mid \boldsymbol{\theta}) is no longer guaranteed to increase.

Closed-Form EM Updates for Gaussian Mixtures

Soft Counting and Averaging

Applying the E-step and M-step to a K-component Gaussian mixture model yields simple responsibility-weighted sample statistics:

  • E-step (posterior responsibilities r_{ik} = q_i(z=k)): r_{ik} = \frac{\pi_k\,\mathcal{N}(x_i;\, \mu_k, \sigma_k^2)}{\sum_{j=1}^K \pi_j\,\mathcal{N}(x_i;\, \mu_j, \sigma_j^2)}
  • M-step (weighted counts, means, and variances with n_k = \sum_{i=1}^n r_{ik}): \pi_k \leftarrow \frac{n_k}{n}, \qquad \mu_k \leftarrow \frac{1}{n_k}\sum_{i=1}^n r_{ik}\,x_i, \qquad \sigma_k^2 \leftarrow \frac{1}{n_k}\sum_{i=1}^n r_{ik}(x_i - \mu_k)^2
  • K-means as the zero-variance limit: When \pi_k = 1/K and all components share a fixed variance \sigma^2 \to 0, the softmax responsibilities r_{ik} \propto \exp\bigl(-(x_i-\mu_k)^2/(2\sigma^2)\bigr) harden into 0/1 indicators for the nearest centroid.

Implementing 1D Gaussian Mixture EM in NumPy

Code Implementation

In vectorized NumPy, the entire EM loop for n = 500 observations from 0.6\,\mathcal{N}(-2.0, 0.8^2) + 0.4\,\mathcal{N}(1.5, 0.6^2) takes a dozen lines:

rng = np.random.default_rng()
x = np.concatenate([rng.normal(-2.0, 0.8, 300), rng.normal(1.5, 0.6, 200)])

def gauss(x, mu, sigma):
    return np.exp(-0.5 * ((x - mu) / sigma)**2) / (sigma * np.sqrt(2 * np.pi))

def em(x, pi, mu, sigma, steps):
    """EM for a 1-D Gaussian mixture: log-likelihood trace and final fit."""
    pi, mu, sigma = (np.array(v, dtype=float) for v in (pi, mu, sigma))
    lls = []
    for _ in range(steps):
        joint = pi * gauss(x[:, None], mu, sigma)  # (n, K)
        lls.append(np.log(joint.sum(axis=1)).sum())
        r = joint / joint.sum(axis=1, keepdims=True)  # E-step
        n_k = r.sum(axis=0)  # M-step
        pi, mu = n_k / len(x), (r * x[:, None]).sum(axis=0) / n_k
        sigma = np.sqrt((r * (x[:, None] - mu)**2).sum(axis=0) / n_k)
    return np.array(lls), pi, mu, sigma

Implementing 1D Gaussian Mixture EM in NumPy (cont.)

Code Implementation

Broadcasting x[:, None] of shape (n, 1) against parameter arrays of shape (K,) evaluates the (n, K) joint density matrix joint in one step; normalizing across rows gives r (E-step), and summing down columns gives n_k (M-step).

Rapid Convergence from an Asymmetric Initialization

Empirical Trajectory

Starting from two heavily overlapping unit-variance components centered at \mu = (-0.5, 0.5) with equal weights \pi = (0.5, 0.5), we run 30 EM iterations:

steps 0-5: [-1298.1  -989.9  -942.   -871.   -848.6  -847. ]  step 29: -846.8
pi = [0.59 0.41], mu = [-2.04  1.54], sigma = [0.74 0.6 ]
  • Monotonic climb: The log-likelihood climbs by roughly 400 nats (from \approx -1{,}280 to \approx -860), with nearly the entire gain achieved in the first 6 steps.
  • Missing information governs speed: Near a fixed point, the linear convergence rate of EM equals 1 - I_{\mathrm{obs}}/I_{\mathrm{com}}—the fraction of Fisher information hidden by the missing labels. Well-separated clusters (I_{\mathrm{obs}} \approx I_{\mathrm{com}}) converge in a few steps.

Pitfall 1: Label Switching and Symmetry Traps

Non-Identifiability & Saddle Points

Permuting the K component indices produces K! identical global maxima (label switching). Far more dangerous is initializing two components identically at \mu = (0, 0) and \sigma = (1, 1):

log-likelihood -1438.7 -> -1027.5, 180.7 below the previous fit
pi = [0.5 0.5], mu = [-0.59 -0.59], sigma = [1.89 1.89]
mean of x = -0.59, standard deviation of x = 1.89
  • Locked responsibilities: Because both components start identical, they receive identical responsibilities r_{i1} = r_{i2} = 0.5 on every observation x_i, so the M-step updates them to the exact same overall mean and standard deviation forever.
  • Stationary point, not a maximum: EM is trapped at a single-Gaussian saddle point more than 100 nats below the two-cluster fit—the exact same symmetry trap that occurs if hidden units in a neural network layer are initialized with identical weights.

Pitfall 2: Unbounded Likelihood and Variance Spikes

Degenerate Global Maxima

\ell(\boldsymbol{\theta}) \le \log\bigl(n\sqrt{2\pi}\bigr) + \log\epsilon + \mathrm{const} \xrightarrow{\epsilon \to 0} -\infty

  • Mechanism of a variance spike: Centering component 2 on a single point (\mu_2 = x_1) and shrinking \sigma_2 = \epsilon \to 0 drives its density \frac{1}{\sqrt{2\pi}\epsilon} \to \infty (just like heteroscedastic regression NLL when \hat{y}_i = y_i and \hat{\sigma}_i \to 0).
  • Practical fix: Enforce a variance floor \sigma_k^2 \ge \sigma_{\min}^2 > 0 or place an inverse-gamma prior on \sigma_k^2.

From Exact EM to Variational Autoencoders (VAEs)

Amortized Variational Inference

  • Intractable deep posterior: When continuous latent codes z \in \mathbb{R}^d pass through a deep nonlinear decoder p_{\boldsymbol{\theta}}(x \mid z), the exact posterior p(z \mid x, \boldsymbol{\theta}) has no closed form.
  • Amortized encoder q_{\boldsymbol{\phi}}(z \mid x): A neural network predicts (\boldsymbol{\mu}_{\boldsymbol{\phi}}(x), \log\boldsymbol{\sigma}_{\boldsymbol{\phi}}(x)) directly from x.
  • Joint SGD on the ELBO: Reparameterizing z = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon} trains (\boldsymbol{\theta}, \boldsymbol{\phi}) jointly by backpropagating through \sum_i \mathcal{L}(q_{\boldsymbol{\phi}}(\cdot \mid x_i), \boldsymbol{\theta}).

Unifying EM, VAEs, and Bayesian Variational Inference

Three Instances of One Bound

The decomposition \log \text{Evidence} = \mathrm{ELBO}(q) + D_{\mathrm{KL}}(q \,\|\, \text{Posterior}) unifies three major algorithms across statistical learning and deep generative modeling:

Method Unobserved Variable Variational Distribution q How \mathrm{ELBO} Is Maximized Does KL Gap Close to 0?
EM Algorithm Per-example discrete cluster z_i \in \{1,\dots,K\} Exact tabular distribution q_i(z_i) per point Coordinate ascent (closed-form E & M steps) Yes (q_i = p(z_i \mid x_i, \boldsymbol{\theta}^{(t)}) after every E-step)
Variational Autoencoder Per-example continuous code \mathbf{z}_i \in \mathbb{R}^d Amortized encoder network q_{\boldsymbol{\phi}}(\mathbf{z}_i \mid \mathbf{x}_i) Joint SGD over (\boldsymbol{\theta}, \boldsymbol{\phi}) via reparameterization No (bounded by encoder family capacity)
Bayesian VI (§36.8) Global model parameters \boldsymbol{\theta} \in \mathbb{R}^p Parametric family q_{\boldsymbol{\psi}}(\boldsymbol{\theta}) (e.g., Gaussian) Gradient ascent on \mathcal{L}(\boldsymbol{\psi}) over variational \boldsymbol{\psi} No (minimizes reverse KL D_{\mathrm{KL}}(q_{\boldsymbol{\psi}} \,\|\, p(\boldsymbol{\theta}\mid\mathcal{D})))

Concept Check: Latent Variables, EM, and the ELBO

Check Your Understanding

  1. Entropy bonus in the ELBO: At x = 0.5 where the true posterior is (0.27, 0.73), why does a hard guess q = (0, 1) have a larger ELBO gap (0.31 nats) than an undecided 50/50 guess (0.12 nats)?
  2. Temperature limit of GMM EM: If all K Gaussian components have equal mixing weights \pi_k = 1/K and a shared fixed variance \sigma^2, what happens to the E-step responsibilities r_{ik} and M-step means \mu_k as \sigma^2 \to 0?
  3. Why hard EM can decrease likelihood: If an algorithm replaces the E-step with hard assignments q_i(z) = \mathbf{1}\{z = k^*(x_i)\}, it still monotonically increases the ELBO. Why can the true log-likelihood \log P(X \mid \boldsymbol{\theta}) decrease?

Answers:

  1. The hard guess puts zero mass on component 1 (H(q) = 0) and incurs D_{\mathrm{KL}} = 1 \cdot \log\frac{1}{0.73} = 0.31 nats, whereas the 50/50 guess retains H(q) = \log 2 = 0.69 nats of entropy and sits closer in KL divergence to (0.27, 0.73).
  2. The responsibilities r_{ik} = \frac{\exp(-(x_i-\mu_k)^2/(2\sigma^2))}{\sum_j \exp(-(x_i-\mu_j)^2/(2\sigma^2))} form a softmax with temperature 2\sigma^2; as \sigma^2 \to 0, r_{ik} \to 1 for the nearest centroid \mu_k, reducing EM directly to K-means.
  3. Because a hard distribution q_i never equals the soft posterior p(z \mid x_i, \boldsymbol{\theta}^{(t)}), the KL gap D_{\mathrm{KL}}(q_i \,\|\, p) > 0 does not vanish at \boldsymbol{\theta}^{(t)}, breaking the tangency equality \mathcal{L}(q^{(t)}, \boldsymbol{\theta}^{(t)}) = \log P(X \mid \boldsymbol{\theta}^{(t)}).

Summary: Latent Variables, EM, and the ELBO

Key Takeaways

Concept Mathematical Form Statistical & Deep Learning Role
Marginal Log-Likelihood \log p(x \mid \boldsymbol{\theta}) = \log \sum_z p(z \mid \boldsymbol{\theta})\,p(x \mid z, \boldsymbol{\theta}) Sum inside \log couples all parameters and blocks closed-form MLE
Evidence Lower Bound \mathcal{L}(q, \boldsymbol{\theta}) = \mathbb{E}_q[\log p(x, z \mid \boldsymbol{\theta})] + H(q) Moves \log back onto the joint density via Jensen’s inequality
Exact KL Gap Identity \log p(x \mid \boldsymbol{\theta}) = \mathcal{L}(q, \boldsymbol{\theta}) + D_{\mathrm{KL}}\bigl(q(z) \,\|\, p(z \mid x, \boldsymbol{\theta})\bigr) Shows \mathcal{L} \le \log p everywhere, with equality iff q is the true posterior
EM Coordinate Ascent E-step: q_i^{(t)} = p(z \mid x_i, \boldsymbol{\theta}^{(t)}); M-step: \operatorname{argmax}_{\boldsymbol{\theta}} \sum_i \mathcal{L} Monotonically increases \log P(X \mid \boldsymbol{\theta}) at every iteration
GMM Soft Counting r_{ik} \propto \pi_k \mathcal{N}(x_i; \mu_k, \sigma_k^2); \mu_k = \frac{1}{n_k}\sum_i r_{ik}x_i Softens oracle estimators; reduces to K-means as shared \sigma^2 \to 0
EM Pitfalls Symmetry trap (\mu_1 = \mu_2) & variance spikes (\sigma_k \to 0) Requires random restarts and variance floors or priors on \sigma_k^2