CS229 EM Algorithm & Gaussian Mixture Model Notes — Complete Derivation

·15 min read
CS229 EM Algorithm & Gaussian Mixture Model Notes — Complete Derivation

Share this article

These are complete CS229 EM algorithm and Gaussian Mixture Model (GMM) notes — the full derivation Andrew Ng works through in the unsupervised-learning block of Stanford's machine learning course. If you came here from search looking for "CS229 EM algorithm notes" or "CS229 Gaussian Mixture Model derivation," you are in the right place: every step from Jensen's inequality to the E-step responsibilities and the M-step closed-form updates is written out below.

If you want the broader overview of every CS229 lecture, see our complete CS229 lecture notes. This page is the deep dive on one specific topic: the EM algorithm and its most common application, the Gaussian Mixture Model.

Quick orientation: what EM is for and why CS229 derives it in general form first

The problem EM solves: you have data that you believe was generated by a mixture of several underlying processes, but you don't know which process generated which point. If you knew the assignments, estimating the parameters of each process would be easy (it's just maximum likelihood on a labeled subset). If you knew the parameters, figuring out the assignments would also be easy (compute which process each point is most likely to have come from). The problem is you know neither, and the two depend on each other circularly.

That's a latent variable problem: the assignment variable z(i)z^{(i)} for each training example is never observed. The Expectation-Maximization algorithm is the general recipe for maximum likelihood estimation when your model has latent variables. CS229 derives it in full generality before applying it to any specific model, because the same two-step structure — guess a distribution over the latent variables, then maximize parameters against that guess — reappears constantly: in Gaussian Mixture Models, in factor analysis, in Gaussian discriminant analysis with missing labels, and in far more advanced settings like hidden Markov models and variational inference.

The problem: maximum likelihood with latent variables

Suppose you have training examples {x(1),,x(m)}\{x^{(1)}, \ldots, x^{(m)}\} and you want to fit a model p(x,z;θ)p(x, z; \theta) where zz is a latent (unobserved) variable. The log-likelihood of the observed data, marginalizing out zz, is:

(θ)=i=1mlogp(x(i);θ)=i=1mlogz(i)p(x(i),z(i);θ)\ell(\theta) = \sum_{i=1}^{m} \log p(x^{(i)}; \theta) = \sum_{i=1}^{m} \log \sum_{z^{(i)}} p(x^{(i)}, z^{(i)}; \theta)

This is the object we want to maximize. The problem is immediately visible in the formula: there's a log of a sum inside the outer sum. If zz were observed, we'd have logp(x(i),z(i);θ)\log p(x^{(i)}, z^{(i)}; \theta) — a log of a product of simple terms, which usually decomposes into a clean closed-form maximization. But the log of a sum over zz does not decompose nicely, and for most models of interest there's no closed-form maximizer of (θ)\ell(\theta) directly.

EM sidesteps this by constructing, at each iteration, a tractable lower bound on (θ)\ell(\theta) that touches the true log-likelihood at the current parameter estimate, then maximizing that lower bound instead. Repeat, and the log-likelihood provably never decreases.

Jensen's inequality: the tool that makes EM work

Jensen's inequality is the single piece of mathematics the whole derivation rests on. For a concave function ff (like log\log) and a random variable XX:

f(E[X])E[f(X)]f(\mathbb{E}[X]) \ge \mathbb{E}[f(X)]

with equality if and only if XX is constant (i.e., X=E[X]X = \mathbb{E}[X] with probability 1). Since log\log is concave, applying Jensen's inequality to a log-of-a-sum lets us pull the log inside, turning it into a sum-of-logs — at the cost of an inequality instead of an equality.

Here's the derivation. Let QiQ_i be some distribution over the latent variable z(i)z^{(i)} (so Qi(z(i))0Q_i(z^{(i)}) \ge 0 and z(i)Qi(z(i))=1\sum_{z^{(i)}} Q_i(z^{(i)}) = 1). Rewrite the log-likelihood by multiplying and dividing by Qi(z(i))Q_i(z^{(i)}) inside the sum:

ilogz(i)p(x(i),z(i);θ)=ilogz(i)Qi(z(i))p(x(i),z(i);θ)Qi(z(i))\sum_i \log \sum_{z^{(i)}} p(x^{(i)}, z^{(i)}; \theta) = \sum_i \log \sum_{z^{(i)}} Q_i(z^{(i)}) \frac{p(x^{(i)}, z^{(i)}; \theta)}{Q_i(z^{(i)})}

The inner sum is now an expectation over z(i)Qiz^{(i)} \sim Q_i of the quantity p(x(i),z(i);θ)Qi(z(i))\frac{p(x^{(i)}, z^{(i)}; \theta)}{Q_i(z^{(i)})}. Applying Jensen's inequality (log is concave, so the inequality points this direction):

iz(i)Qi(z(i))logp(x(i),z(i);θ)Qi(z(i))\ge \sum_i \sum_{z^{(i)}} Q_i(z^{(i)}) \log \frac{p(x^{(i)}, z^{(i)}; \theta)}{Q_i(z^{(i)})}

This right-hand side is a lower bound on (θ)\ell(\theta) for any valid choice of QiQ_i. Call it ELBO(θ,Q)\text{ELBO}(\theta, Q) — the evidence lower bound. EM maximizes this lower bound instead of (θ)\ell(\theta) directly, because it decomposes into a sum of logs rather than a log of a sum.

Making the bound tight: choosing QiQ_i

The bound holds for any QiQ_i, but it's only useful if it's tight at the current parameters θ\theta — otherwise maximizing the bound doesn't guarantee progress on the real objective. Jensen's inequality is tight exactly when the random variable inside is constant, which here means:

p(x(i),z(i);θ)Qi(z(i))=cfor all z(i)\frac{p(x^{(i)}, z^{(i)}; \theta)}{Q_i(z^{(i)})} = c \quad \text{for all } z^{(i)}

for some constant cc (not depending on z(i)z^{(i)}). This means Qi(z(i))p(x(i),z(i);θ)Q_i(z^{(i)}) \propto p(x^{(i)}, z^{(i)}; \theta). Since QiQ_i must sum to 1 over z(i)z^{(i)}, normalizing gives:

Qi(z(i))=p(x(i),z(i);θ)zp(x(i),z;θ)=p(z(i)x(i);θ)Q_i(z^{(i)}) = \frac{p(x^{(i)}, z^{(i)}; \theta)}{\sum_{z} p(x^{(i)}, z; \theta)} = p(z^{(i)} \mid x^{(i)}; \theta)

That's the key result: the tightest possible QiQ_i is just the posterior distribution over the latent variable given the current parameters and the observed data. This single equation is the entire E-step, in general form, for any latent-variable model.

The EM algorithm, stated in general form

Putting the two pieces together, EM alternates:

E-step. For each ii, set:

Qi(z(i)):=p(z(i)x(i);θ)Q_i(z^{(i)}) := p(z^{(i)} \mid x^{(i)}; \theta)

using the current parameters θ\theta.

M-step. Update the parameters:

θ:=argmaxθiz(i)Qi(z(i))logp(x(i),z(i);θ)Qi(z(i))\theta := \arg\max_\theta \sum_i \sum_{z^{(i)}} Q_i(z^{(i)}) \log \frac{p(x^{(i)}, z^{(i)}; \theta)}{Q_i(z^{(i)})}

Repeat until convergence. The E-step computes a tight lower bound at the current θ\theta; the M-step maximizes that bound over θ\theta, which can only move the bound (and therefore the true log-likelihood, since they agree at the old θ\theta) up.

Why EM monotonically increases the log-likelihood

This is the guarantee CS229 spends real time proving, because it's what makes EM trustworthy as an optimization procedure even though it's a heuristic rather than a closed-form solution. The argument has three steps:

  1. After the E-step at iteration tt, the bound is tight: ELBO(θ(t),Q(t))=(θ(t))\text{ELBO}(\theta^{(t)}, Q^{(t)}) = \ell(\theta^{(t)}).
  2. The M-step picks θ(t+1)\theta^{(t+1)} to maximize the ELBO with Q(t)Q^{(t)} fixed, so ELBO(θ(t+1),Q(t))ELBO(θ(t),Q(t))\text{ELBO}(\theta^{(t+1)}, Q^{(t)}) \ge \text{ELBO}(\theta^{(t)}, Q^{(t)}).
  3. The ELBO is always a lower bound on the true log-likelihood for any QQ, so (θ(t+1))ELBO(θ(t+1),Q(t))\ell(\theta^{(t+1)}) \ge \text{ELBO}(\theta^{(t+1)}, Q^{(t)}).

Chaining these:

(θ(t+1))ELBO(θ(t+1),Q(t))ELBO(θ(t),Q(t))=(θ(t))\ell(\theta^{(t+1)}) \ge \text{ELBO}(\theta^{(t+1)}, Q^{(t)}) \ge \text{ELBO}(\theta^{(t)}, Q^{(t)}) = \ell(\theta^{(t)})

So the log-likelihood never decreases across an EM iteration. It's not guaranteed to reach the global maximum — like k-means, EM can and does converge to a local maximum, which is why in practice you run it from several random initializations and keep the best result.

Applying EM to Gaussian Mixture Models

A Gaussian Mixture Model assumes each training example was generated by first picking a latent cluster z(i){1,,k}z^{(i)} \in \{1, \ldots, k\} according to a categorical distribution with parameters ϕj=p(z(i)=j)\phi_j = p(z^{(i)} = j), and then drawing x(i)x^{(i)} from the Gaussian associated with that cluster:

z(i)Multinomial(ϕ),x(i)z(i)=jN(μj,Σj)z^{(i)} \sim \text{Multinomial}(\phi), \qquad x^{(i)} \mid z^{(i)} = j \sim \mathcal{N}(\mu_j, \Sigma_j)

The parameters to estimate are the mixture weights ϕj\phi_j, the means μj\mu_j, and the covariances Σj\Sigma_j for j=1,,kj = 1, \ldots, k. If we knew the true cluster labels z(i)z^{(i)}, this would be ordinary Gaussian discriminant analysis with a closed-form maximum-likelihood solution. Because z(i)z^{(i)} is latent, we apply EM.

E-step for GMM: computing the responsibilities

From the general E-step formula, Qi(z(i)=j)=p(z(i)=jx(i);ϕ,μ,Σ)Q_i(z^{(i)} = j) = p(z^{(i)} = j \mid x^{(i)}; \phi, \mu, \Sigma). By Bayes' rule:

wj(i):=Qi(z(i)=j)=p(x(i)z(i)=j;μ,Σ)p(z(i)=j;ϕ)l=1kp(x(i)z(i)=l;μ,Σ)p(z(i)=l;ϕ)w_j^{(i)} := Q_i(z^{(i)} = j) = \frac{p(x^{(i)} \mid z^{(i)} = j; \mu, \Sigma) \, p(z^{(i)} = j; \phi)}{\sum_{l=1}^{k} p(x^{(i)} \mid z^{(i)} = l; \mu, \Sigma) \, p(z^{(i)} = l; \phi)}

Substituting the Gaussian density for p(x(i)z(i)=j;μ,Σ)p(x^{(i)} \mid z^{(i)} = j; \mu, \Sigma) and ϕj\phi_j for p(z(i)=j;ϕ)p(z^{(i)} = j; \phi):

wj(i)=ϕj1(2π)n/2Σj1/2exp(12(x(i)μj)Σj1(x(i)μj))l=1kϕl1(2π)n/2Σl1/2exp(12(x(i)μl)Σl1(x(i)μl))w_j^{(i)} = \frac{\phi_j \cdot \dfrac{1}{(2\pi)^{n/2} |\Sigma_j|^{1/2}} \exp\left(-\frac{1}{2}(x^{(i)} - \mu_j)^\top \Sigma_j^{-1} (x^{(i)} - \mu_j)\right)}{\sum_{l=1}^{k} \phi_l \cdot \dfrac{1}{(2\pi)^{n/2} |\Sigma_l|^{1/2}} \exp\left(-\frac{1}{2}(x^{(i)} - \mu_l)^\top \Sigma_l^{-1} (x^{(i)} - \mu_l)\right)}

wj(i)w_j^{(i)} is called the responsibility — the posterior probability that cluster jj generated point x(i)x^{(i)}, given the current parameters. Unlike k-means, which assigns each point to exactly one cluster, every point gets a soft responsibility vector across all kk clusters that sums to 1. This is the "soft assignment" property that distinguishes GMM/EM from k-means.

M-step for GMM: closed-form updates

With the responsibilities wj(i)w_j^{(i)} fixed from the E-step, the M-step maximizes ijQi(z(i)=j)logp(x(i),z(i)=j;ϕ,μ,Σ)Qi(z(i)=j)\sum_i \sum_j Q_i(z^{(i)}=j) \log \frac{p(x^{(i)}, z^{(i)}=j; \phi,\mu,\Sigma)}{Q_i(z^{(i)}=j)} over ϕ,μ,Σ\phi, \mu, \Sigma. Because the responsibilities are now fixed numbers rather than variables, this maximization has a closed-form solution — take derivatives with respect to each parameter, set to zero, and solve (using a Lagrange multiplier for ϕ\phi to enforce jϕj=1\sum_j \phi_j = 1). The results are:

Mixture weights:

ϕj:=1mi=1mwj(i)\phi_j := \frac{1}{m} \sum_{i=1}^{m} w_j^{(i)}

The updated weight for cluster jj is simply the average responsibility that cluster jj took across all training points — the "effective number of points" assigned to jj, divided by mm.

Means:

μj:=i=1mwj(i)x(i)i=1mwj(i)\mu_j := \frac{\sum_{i=1}^{m} w_j^{(i)} x^{(i)}}{\sum_{i=1}^{m} w_j^{(i)}}

This is a weighted average of all training points, where each point's contribution to cluster jj's mean is weighted by how responsible cluster jj is for it. Compare this to k-means, where each point contributes fully to exactly one centroid — here every point contributes partially to every mean.

Covariances:

Σj:=i=1mwj(i)(x(i)μj)(x(i)μj)i=1mwj(i)\Sigma_j := \frac{\sum_{i=1}^{m} w_j^{(i)} (x^{(i)} - \mu_j)(x^{(i)} - \mu_j)^\top}{\sum_{i=1}^{m} w_j^{(i)}}

The same weighted-average logic applied to the outer-product term that defines the sample covariance.

Putting it together

The full GMM training loop: initialize ϕj\phi_j, μj\mu_j, Σj\Sigma_j (commonly via k-means, or randomly with kk points from the data as initial means), then alternate:

  1. E-step: compute wj(i)w_j^{(i)} for every point and cluster using the current parameters.
  2. M-step: recompute ϕj\phi_j, μj\mu_j, Σj\Sigma_j using the closed-form updates above, weighted by the responsibilities just computed.

Repeat until the log-likelihood stops improving meaningfully (or you hit a fixed number of iterations). As with any EM application, run from multiple random initializations, since the log-likelihood surface for a GMM is non-convex and has many local maxima — a notoriously bad one being a component's mean collapsing exactly onto a single training point, driving that component's variance toward zero and its likelihood contribution toward infinity (degenerate solutions practical implementations guard against by adding a small regularization term to the covariance).

How EM relates to k-means

CS229 introduces k-means before EM specifically so that the comparison lands cleanly: k-means is the special case of EM-for-GMM where the E-step is forced to be a hard assignment instead of a soft one.

Concretely, if you take the GMM E-step and replace the responsibility wj(i)w_j^{(i)} with a one-hot vector — probability 1 on whichever cluster currently has the highest responsibility, 0 elsewhere — and additionally fix every Σj\Sigma_j to be the identity matrix (so the only thing distinguishing clusters is their mean, and "responsibility" collapses to nearest-mean-by-Euclidean-distance), the GMM M-step updates reduce exactly to the k-means update: the new mean of cluster jj becomes the average of the points currently hard-assigned to jj.

This is why k-means shares EM's convergence property (monotonic decrease of the distortion objective, convergence to a local optimum only) and its practical failure mode (sensitivity to initialization). It's also why k-means is a common initializer for GMM: run k-means first to get a fast, hard-assignment estimate of cluster centers, then use those centers to initialize μj\mu_j for the (slower, but more expressive) GMM/EM fit.

How EM connects to PCA and factor analysis, CS229's other unsupervised topics

EM, k-means, and GMMs are one part of CS229's unsupervised-learning block. The syllabus places two more topics alongside them, and it's worth being precise about how they relate rather than lumping all of unsupervised learning together:

  • Principal Component Analysis (PCA) is not an EM application in the standard CS229 treatment — it has a closed-form solution via eigendecomposition of the covariance matrix (or via the singular value decomposition of the design matrix) and needs no iterative E-step/M-step procedure. PCA finds the directions of maximum variance in the data and projects onto them; CS229 derives it from both the variance-maximization view and the reconstruction-error view, and both arrive at the same eigenvectors.
  • Factor analysis is the model that actually does connect back to EM. It assumes each data point is generated from a low-dimensional latent Gaussian zz via a linear mapping plus independent Gaussian noise: x=Λz+μ+ϵx = \Lambda z + \mu + \epsilon. Because zz is latent and continuous (not a discrete cluster label like in GMM), factor analysis is fit with a continuous-latent-variable version of EM: the E-step computes the posterior over z(i)z^{(i)} given x(i)x^{(i)} (which, because everything is jointly Gaussian, has a closed form), and the M-step updates Λ\Lambda, μ\mu, and the noise covariance.

So the throughline for CS229's unsupervised block is: k-means (hard, no probabilistic model) generalizes to GMM (soft, EM with discrete latent variable), and GMM generalizes conceptually to factor analysis (EM with continuous latent variable), while PCA sits to the side as a separate, closed-form dimensionality-reduction technique that doesn't require EM at all. If you're trying to keep the four topics straight for an exam: ask whether the latent variable is a cluster label (GMM) or a continuous vector (factor analysis), and whether the fitting procedure is iterative (EM, for both GMM and factor analysis) or a single eigendecomposition (PCA).

Common derivation pitfalls

Three places where the EM derivation trips people up on CS229 problem sets:

  1. Forgetting why Jensen's inequality points the direction it does. log\log is concave, so log(E[X])E[logX]\log(\mathbb{E}[X]) \ge \mathbb{E}[\log X] — the inequality gives a lower bound. If you mix this up you'll conclude EM maximizes an upper bound, which would break the monotonic-improvement guarantee entirely.

  2. Treating the E-step as an approximation rather than an exact posterior. The E-step isn't a heuristic guess at QiQ_i — it's the exact, provably tightest choice, derived directly from the equality condition of Jensen's inequality. It's exact given the current parameters; it just doesn't stay exact once the M-step moves the parameters (which is exactly why you have to redo the E-step every iteration).

  3. Assuming EM finds the global maximum. It doesn't, and the derivation doesn't claim it does — only that each iteration doesn't decrease the log-likelihood. For a genuinely non-convex log-likelihood surface (which GMMs have), different initializations can converge to meaningfully different local optima. This is why running EM multiple times with different seeds and keeping the highest final log-likelihood is standard practice, not a workaround for a bug.

What is the EM algorithm used for in CS229?

EM is CS229's general tool for maximum likelihood estimation when the model has a latent (unobserved) variable — most concretely, fitting Gaussian Mixture Models, but the same E-step/M-step structure also applies to factor analysis and to mixtures of other distributions. It alternates between computing a posterior distribution over the latent variable given the current parameters (E-step) and maximizing the parameters against that posterior (M-step).

Why does EM use Jensen's inequality?

Directly maximizing the log-likelihood with a latent variable requires optimizing a log of a sum, which generally has no closed form. Jensen's inequality (applied because log\log is concave) lets you construct a lower bound that turns the log of a sum into a sum of logs — a tractable quantity — and shows that choosing the latent-variable posterior as QiQ_i makes that bound exactly tight at the current parameters. Maximizing the tight bound then provably does not decrease the true log-likelihood.

What's the difference between the E-step and the M-step?

The E-step computes, for each training example, the posterior probability distribution over its latent variable given the current model parameters (for a GMM, this is the "responsibility" of each cluster for that point). The M-step then treats those posteriors as fixed and re-solves for the model parameters that maximize the expected complete-data log-likelihood — for a GMM this has closed-form updates for the mixture weights, means, and covariances.

K-means is EM's hard-assignment special case. Where GMM's E-step computes a soft responsibility for every cluster, k-means forces a one-hot (hard) assignment to the single nearest centroid, and where GMM tracks a full covariance per cluster, k-means implicitly fixes every cluster's covariance to the identity matrix. With those two restrictions, the GMM M-step's weighted-mean update collapses exactly into the k-means centroid update.

Does EM always converge to the best solution?

No. EM guarantees the log-likelihood never decreases from one iteration to the next, and it does converge to a stationary point, but that point can be a local maximum rather than the global one — the same limitation k-means has. For Gaussian Mixture Models, the log-likelihood surface is non-convex, so different random initializations can land on different local optima. Standard practice is to run EM several times from different initializations (often seeded with a k-means run) and keep the fit with the highest final log-likelihood.


Turn any Stanford lecture into notes like these

These notes were synthesized from the CS229 unsupervised-learning lectures. Notiq does the same thing for any YouTube lecture — paste a link, get back structured notes with the derivations written out, flashcards, exam questions, and worked examples. Try the Stanford CS229 lecture library in Notiq or paste your own lecture.

Share this article

Related Articles