Skip to content
E
Educatum

Explain the two steps of EM algorithm?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

Expectation-Maximization (EM) is an iterative algorithm for finding maximum likelihood (or MAP) parameter estimates in statistical models with latent variables or missing data. The E-step computes the posterior distribution over latent variables to form the expected complete-data log-likelihood, and the M-step updates parameters to maximize that expectation, monotonically increasing observed log-likelihood toward a local optimum.

Study Card: Two Steps of the Expectation-Maximization (EM) Algorithm

Direct Answer

The Expectation-Maximization (EM) algorithm finds maximum likelihood estimates of parameters θ\theta when observed data XX depends on unobserved latent variables ZZ (making direct optimization of log⁡P(X∣θ)=log⁡∑ZP(X,Z∣θ)\log P(X \mid \theta) = \log \sum_Z P(X, Z \mid \theta) analytically intractable). EM alternates between two steps from an initial guess θ(0)\theta^{(0)}:

  1. E-step (Expectation): Using current parameters θ(t)\theta^{(t)}, compute the posterior distribution P(Z∣X,θ(t))P(Z \mid X, \theta^{(t)}) over latent variables and construct the QQ-function—the expected complete-data log-likelihood: Q(θ∣θ(t))=EZ∼P(Z∣X,θ(t))[log⁡P(X,Z∣θ)]Q(\theta \mid \theta^{(t)}) = \mathbb{E}_{Z \sim P(Z \mid X, \theta^{(t)})}\big[\log P(X, Z \mid \theta)\big]
  2. M-step (Maximization): Update parameters by maximizing the QQ-function: θ(t+1)=arg⁡max⁡θQ(θ∣θ(t))\theta^{(t+1)} = \arg\max_{\theta} Q(\theta \mid \theta^{(t)})

By Jensen’s inequality on the evidence lower bound (ELBO), every EM step guarantees log⁡P(X∣θ(t+1))≥log⁡P(X∣θ(t))\log P(X \mid \theta^{(t+1)}) \ge \log P(X \mid \theta^{(t)}), monotonically driving the observed log-likelihood until convergence to a local maximum or saddle point (which makes initialization or multiple restarts important).

Key Terms

  • Latent Variables (ZZ): Unobserved variables (such as true mixture component assignments in a GMM or hidden states in an HMM) that explain structure in observed data XX.
  • Complete-Data Log-Likelihood: log⁡P(X,Z∣θ)\log P(X, Z \mid \theta), which typically factorizes cleanly in exponential-family models once ZZ is known.
  • QQ-Function: The tight lower-bound surrogate maximized in the M-step, formed by taking expectation over P(Z∣X,θ(t))P(Z \mid X, \theta^{(t)}).
  • Monotonic Convergence: EM never decreases the marginal log-likelihood log⁡P(X∣θ)\log P(X \mid \theta), though it is not guaranteed to find the global maximum on multimodal likelihood surfaces.

Example

Consider modeling exam scores drawn from two hidden student cohorts (K=2K = 2 Gaussian Mixture Model) with unknown mixing weights πk\pi_k, means μk\mu_k, and variances σk2\sigma_k^2:

  • E-step: For each student score xix_i, compute its soft cluster responsibility γik=P(zi=k∣xi,θ(t))=πk(t)N(xi∣μk(t),(σk2)(t))∑j=12πj(t)N(xi∣μj(t),(σj2)(t))\gamma_{ik} = P(z_i = k \mid x_i, \theta^{(t)}) = \frac{\pi_k^{(t)} \mathcal{N}(x_i \mid \mu_k^{(t)}, (\sigma_k^2)^{(t)})}{\sum_{j=1}^2 \pi_j^{(t)} \mathcal{N}(x_i \mid \mu_j^{(t)}, (\sigma_j^2)^{(t)})}.
  • M-step: Recompute closed-form Gaussian parameters weighted by these responsibilities: Nk=∑iγikN_k = \sum_i \gamma_{ik}, πk(t+1)=Nk/N\pi_k^{(t+1)} = N_k / N, μk(t+1)=1Nk∑iγikxi\mu_k^{(t+1)} = \frac{1}{N_k}\sum_i \gamma_{ik} x_i, and (σk2)(t+1)=1Nk∑iγik(xi−μk(t+1))2(\sigma_k^2)^{(t+1)} = \frac{1}{N_k}\sum_i \gamma_{ik}(x_i - \mu_k^{(t+1)})^2.

Repeating both steps refines both the soft cluster assignments and the Gaussian parameters until log-likelihood stabilizes.

Code Implementation

import numpy as np
from sklearn.mixture import GaussianMixture

# Generate 1D data from a 2-component Gaussian mixture (true means: 0.0 and 5.0)
rng = np.random.default_rng(42)
n_samples = 300
X = np.concatenate([
    rng.normal(0.0, 1.0, int(0.3 * n_samples)),
    rng.normal(5.0, 1.2, int(0.7 * n_samples)),
])

def gaussian_pdf(x, mean, var):
    return np.exp(-0.5 * ((x - mean) ** 2) / var) / np.sqrt(2.0 * np.pi * var)

# Manual EM algorithm for a 2-component 1D Gaussian Mixture Model
pi = np.array([0.5, 0.5])
mu = np.array([1.0, 3.5])
var = np.array([1.0, 1.0])

for iteration in range(1, 16):
    # E-step: compute unnormalized likelihoods and posterior responsibilities gamma_ik
    weighted_pdfs = np.column_stack([
        pi[k] * gaussian_pdf(X, mu[k], var[k]) for k in range(2)
    ])
    total_pdf = weighted_pdfs.sum(axis=1, keepdims=True)
    gamma = weighted_pdfs / total_pdf
    log_likelihood = float(np.sum(np.log(total_pdf)))

    # M-step: update mixing weights, means, and variances
    nk = gamma.sum(axis=0)
    pi = nk / len(X)
    mu = (gamma.T @ X) / nk
    var = np.array([np.sum(gamma[:, k] * (X - mu[k]) ** 2) / nk[k] for k in range(2)])

    if iteration in {1, 2, 5, 10, 15}:
        print(f"Iter {iteration:2d} | LogLik = {log_likelihood:8.2f} | Means = {np.round(mu, 3)}")

# Verify against scikit-learn's GaussianMixture (which runs EM under the hood)
gmm = GaussianMixture(n_components=2, random_state=42, n_init=5).fit(X.reshape(-1, 1))
print("\nscikit-learn GMM sorted means:", np.round(np.sort(gmm.means_.ravel()), 3))
  • Jensen’s Inequality & ELBO: Rewriting log⁡P(X∣θ)=ELBO(q,θ)+DKL(q(Z) ∥ P(Z∣X,θ))\log P(X \mid \theta) = \text{ELBO}(q, \theta) + D_{\text{KL}}(q(Z) \,\|\, P(Z \mid X, \theta)) shows that the E-step sets q(Z)=P(Z∣X,θ(t))q(Z) = P(Z \mid X, \theta^{(t)}) to make the KL term zero (tight bound), and the M-step maximizes the ELBO.
  • Gaussian Mixture Models (GMMs): The canonical continuous clustering application of EM, generalizing k-means with soft probabilistic assignments and full covariance shapes.
  • K-Means as Hard EM: K-means corresponds to the small-variance limit (σ2→0\sigma^2 \to 0) of isotropic GMM EM, where E-step responsibilities collapse to hard nearest-centroid assignments.
  • Baum-Welch Algorithm (HMMs): Applies EM via forward-backward dynamic programming to estimate transition and emission parameters in Hidden Markov Models.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.