Explain the two steps of EM algorithm?
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 when observed data depends on unobserved latent variables (making direct optimization of analytically intractable). EM alternates between two steps from an initial guess :
- E-step (Expectation): Using current parameters , compute the posterior distribution over latent variables and construct the -function—the expected complete-data log-likelihood:
- M-step (Maximization): Update parameters by maximizing the -function:
By Jensen’s inequality on the evidence lower bound (ELBO), every EM step guarantees , 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 (): Unobserved variables (such as true mixture component assignments in a GMM or hidden states in an HMM) that explain structure in observed data .
- Complete-Data Log-Likelihood: , which typically factorizes cleanly in exponential-family models once is known.
- -Function: The tight lower-bound surrogate maximized in the M-step, formed by taking expectation over .
- Monotonic Convergence: EM never decreases the marginal log-likelihood , 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 ( Gaussian Mixture Model) with unknown mixing weights , means , and variances :
- E-step: For each student score , compute its soft cluster responsibility .
- M-step: Recompute closed-form Gaussian parameters weighted by these responsibilities: , , , and .
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))
Related Concepts
- Jensen’s Inequality & ELBO: Rewriting shows that the E-step sets 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 () 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.