Skip to content
BIASED

Mixtures and the EM algorithm

Clustering as a probability model — the Gaussian mixture, latent variables and responsibilities, a lower bound on the log-likelihood and the EM algorithm as coordinate ascent on it, the updates for a Gaussian mixture, k-means as the hard limit, local optima, collapsing components and choosing the number of components with BIC.

From k-means to a mixture

The topic Clustering ended with k-means and its two blind spots. Every point goes to exactly one cluster, and nothing says how sure that assignment is. And the objective J=∑i∥xi−μci∥2J = \sum_i \lVert x_i - \mu_{c_i} \rVert^2 counts plain distances, so k-means behaves as if every cluster were a round ball of the same width. This topic turns clustering into a probability model and fits it by maximum likelihood.

A Gaussian mixture describes the data by a two-step story. First pick a component zz with probabilities π1,…,πK\pi_1, \dots, \pi_K. Then draw x∈Rdx \in \mathbb R^d from that component's Gaussian:

z∼Categorical(π1,…,πK),x∣z=k  ∼  N(μk,Σk).z \sim \text{Categorical}(\pi_1, \dots, \pi_K), \qquad x \mid z = k \;\sim\; \mathcal N(\mu_k, \Sigma_k) .

Here KK is the number of components, the clusters of the previous topic. The weights satisfy πk≥0\pi_k \ge 0 and ∑kπk=1\sum_k \pi_k = 1. Each component has its own mean μk\mu_k and covariance Σk\Sigma_k, and θ\theta collects all the parameters. The second argument of N(x∣μ,Σ)\mathcal N(x \mid \mu, \Sigma) is a covariance, a variance in one dimension.

The component zz is a latent variable: the model uses it, the data never show it. So the density of xx alone sums the joint p(x,z=k)=πk N(x∣μk,Σk)p(x, z = k) = \pi_k\, \mathcal N(x \mid \mu_k, \Sigma_k) over kk, by the law of total probability:

p(x∣θ)=∑k=1Kπk N(x∣μk,Σk).p(x \mid \theta) = \sum_{k=1}^K \pi_k\, \mathcal N(x \mid \mu_k, \Sigma_k) .

Each component is a multivariate Gaussian with elliptical contours set by Σk\Sigma_k (the topic The multivariate Gaussian in Probability Theory). So a cluster may be tilted, elongated, small or wide, and each has its own weight.

Example. In one dimension take π=(0.3,0.7)\pi = (0.3, 0.7), μ=(0,4)\mu = (0, 4) and standard deviations 11 and 22. At x=2x = 2 the component densities are N(2∣0,1)=0.0540\mathcal N(2 \mid 0, 1) = 0.0540 and N(2∣4,4)=0.1210\mathcal N(2 \mid 4, 4) = 0.1210, so

p(2)=0.3⋅0.0540+0.7⋅0.1210=0.0162+0.0847=0.1009.p(2) = 0.3 \cdot 0.0540 + 0.7 \cdot 0.1210 = 0.0162 + 0.0847 = 0.1009 .

Responsibilities

Given the parameters, which component produced the point xix_i? Bayes' formula answers it (the topic Conditional probability and Bayes' formula). The prior is πk\pi_k, the likelihood is N(xi∣μk,Σk)\mathcal N(x_i \mid \mu_k, \Sigma_k), and the evidence is p(xi∣θ)p(x_i \mid \theta):

rik=p(zi=k∣xi,θ)=πk N(xi∣μk,Σk)∑j=1Kπj N(xi∣μj,Σj).r_{ik} = p(z_i = k \mid x_i, \theta) = \frac{\pi_k\, \mathcal N(x_i \mid \mu_k, \Sigma_k)}{\sum_{j=1}^K \pi_j\, \mathcal N(x_i \mid \mu_j, \Sigma_j)} .

These numbers are the responsibilities. Each row is a distribution over components: rik≥0r_{ik} \ge 0 and ∑krik=1\sum_k r_{ik} = 1. They are the soft version of the k-means assignment cic_i.

In the example above, the point x=2x = 2 belongs to the first component with probability 0.0162/0.1009=0.160.0162 / 0.1009 = 0.16 and to the second with 0.840.84. k-means with centres 00 and 44 would put the same point exactly on the boundary, because it compares distances only. The mixture also weighs how wide each component is and how often it occurs.

Why the likelihood is hard

For nn independent points the log-likelihood is

ℓ(θ)=∑i=1nlog⁡∑k=1Kπk N(xi∣μk,Σk).\ell(\theta) = \sum_{i=1}^n \log \sum_{k=1}^K \pi_k\, \mathcal N(x_i \mid \mu_k, \Sigma_k) .

The logarithm of a sum does not split. Setting the gradient to zero couples every parameter with every other, and there is no closed-form solution.

Now pretend the components ziz_i were observed. The complete-data log-likelihood is

log⁡p(x,z∣θ)=∑i=1n(log⁡πzi+log⁡N(xi∣μzi,Σzi)).\log p(x, z \mid \theta) = \sum_{i=1}^n \Big( \log \pi_{z_i} + \log \mathcal N(x_i \mid \mu_{z_i}, \Sigma_{z_i}) \Big) .

This is a sum of logarithms. It splits into one Gaussian fit per component, on the points with that label, and one fit of the weights. Each has the closed form from the topic Maximum likelihood: the share of points, the mean, and the covariance with the factor 1/nk1/n_k. All the difficulty is in not knowing zz.

Three properties of ℓ\ell matter before we fit it.

  • It is not concave and has several local maxima.
  • Relabelling the components does not change it, so every maximum comes in K!K! copies.
  • It is unbounded. Centre a component on one data point and shrink its variance to zero: the density at that point, and with it ℓ\ell, grows without limit. The topic Maximum likelihood met this case in its block on where the method breaks.

So the global maximum of a Gaussian mixture likelihood does not exist. What we look for is a good local maximum away from such collapses.

The lower bound

The trick is a lower bound on log⁡p(x∣θ)\log p(x \mid \theta) that is easy to maximize. Take one point xx with latent zz (for a dataset, sum over points). Let q(z)q(z) be any distribution over the KK values of zz, positive wherever the posterior is. The product rule gives p(x,z∣θ)=p(z∣x,θ) p(x∣θ)p(x, z \mid \theta) = p(z \mid x, \theta)\, p(x \mid \theta), so for every zz

log⁡p(x∣θ)=log⁡p(x,z∣θ)q(z)−log⁡p(z∣x,θ)q(z).\log p(x \mid \theta) = \log \frac{p(x, z \mid \theta)}{q(z)} - \log \frac{p(z \mid x, \theta)}{q(z)} .

The left side does not depend on zz. Averaging both sides over z∼qz \sim q leaves it unchanged:

log⁡p(x∣θ)=∑zq(z)log⁡p(x,z∣θ)q(z)⏟L(q,θ)+∑zq(z)log⁡q(z)p(z∣x,θ)⏟DKL(q ∥ p(z∣x,θ)).\log p(x \mid \theta) = \underbrace{\sum_z q(z) \log \frac{p(x, z \mid \theta)}{q(z)}}_{\mathcal L(q, \theta)} + \underbrace{\sum_z q(z) \log \frac{q(z)}{p(z \mid x, \theta)}}_{D_{\mathrm{KL}}(q \,\|\, p(z \mid x, \theta))} .

The second term is the Kullback–Leibler divergence from qq to the posterior. As the topic Maximum likelihood recalled, it is never negative and is zero only when the two distributions coincide. Hence

log⁡p(x∣θ)  ≥  L(q,θ)=Eq[log⁡p(x,z∣θ)]+H(q),H(q)=−∑zq(z)log⁡q(z),\log p(x \mid \theta) \;\ge\; \mathcal L(q, \theta) = \mathbb E_q \big[ \log p(x, z \mid \theta) \big] + H(q), \qquad H(q) = -\sum_z q(z) \log q(z) ,

with equality exactly when qq is the posterior p(z∣x,θ)p(z \mid x, \theta). L\mathcal L is the evidence lower bound, the ELBO. Jensen's inequality for the concave logarithm gives the same bound in one line (the topic Expectation and variance). The identity says more: the gap is exactly a KL divergence, so we know when the bound is tight.

Why is this bound useful? Its first term is the complete-data log-likelihood averaged over guessed labels, a sum of logarithms again. Its second term does not involve θ\theta at all.

EM: coordinate ascent

L(q,θ)\mathcal L(q, \theta) has two blocks of variables: the distributions qiq_i, one per point, and the parameters θ\theta. The EM algorithm maximizes it over one block at a time, from a start θ0\theta^0.

  1. E-step. Fix θt\theta^t and maximize over qq. The left side log⁡p(x∣θt)\log p(x \mid \theta^t) does not depend on qq, so this means making the KL term zero: qit+1(z)=p(z∣xi,θt)q_i^{t+1}(z) = p(z \mid x_i, \theta^t). For a mixture these are the responsibilities rikr_{ik}. After the E-step the bound touches ℓ\ell at θt\theta^t.
  2. M-step. Fix qt+1q^{t+1} and maximize over θ\theta. The entropy is now a constant, so we maximize the expected complete-data log-likelihood:
θt+1=arg⁡max⁡θ∑i=1nEqit+1[log⁡p(xi,zi∣θ)].\theta^{t+1} = \arg\max_\theta \sum_{i=1}^n \mathbb E_{q_i^{t+1}} \big[ \log p(x_i, z_i \mid \theta) \big] .

Why the log-likelihood never decreases takes one line. The bound holds at any θ\theta; the M-step does not lower L\mathcal L; the E-step made the bound tight at θt\theta^t:

ℓ(θt+1)  ≥  L(qt+1,θt+1)  ≥  L(qt+1,θt)  =  ℓ(θt).\ell(\theta^{t+1}) \;\ge\; \mathcal L(q^{t+1}, \theta^{t+1}) \;\ge\; \mathcal L(q^{t+1}, \theta^{t}) \;=\; \ell(\theta^{t}) .

This is coordinate ascent, the mirror image of Lloyd's coordinate descent on JJ. Where the bound touches ℓ\ell the two also share a gradient, so EM stops only at stationary points of ℓ\ell. That can be a local maximum or a saddle, and which one depends on the start.

A toy run. Seven points −1.0,−0.3,0.4,1.2,2.5,3.1,3.8-1.0, -0.3, 0.4, 1.2, 2.5, 3.1, 3.8 and the model 0.5 N(0,1)+0.5 N(θ,1)0.5\, \mathcal N(0, 1) + 0.5\, \mathcal N(\theta, 1), where only the mean θ\theta of the second component is unknown. At θ0=1\theta^0 = 1 the responsibilities of the second component are

xix_i −1.0-1.0 −0.3-0.3 0.40.4 1.21.2 2.52.5 3.13.1 3.83.8
rir_i 0.1820.182 0.3100.310 0.4750.475 0.6680.668 0.8810.881 0.9310.931 0.9640.964

The M-step for one mean is a weighted average, θ1=∑irixi/∑iri=9.469/4.412=2.146\theta^1 = \sum_i r_i x_i / \sum_i r_i = 9.469 / 4.412 = 2.146. Then θ2=2.652\theta^2 = 2.652, and EM converges to θ=2.910\theta = 2.910. The log-likelihood goes −17.32-17.32, −13.34-13.34, −12.71-12.71, −12.64-12.64 and settles at −12.63-12.63. Soon each step is about 0.30.3 of the previous one: EM converges linearly, fast at first and slowly at the end.

The updates for a Gaussian mixture

For a full Gaussian mixture the M-step objective is

Q(θ)=∑i=1n∑k=1Krik(log⁡πk+log⁡N(xi∣μk,Σk)).Q(\theta) = \sum_{i=1}^n \sum_{k=1}^K r_{ik} \Big( \log \pi_k + \log \mathcal N(x_i \mid \mu_k, \Sigma_k) \Big) .

It is the complete-data log-likelihood with each indicator [zi=k][z_i = k] replaced by its probability rikr_{ik}. It splits by parameter. Write Nk=∑irikN_k = \sum_i r_{ik} for the effective number of points in component kk.

  • Weights. Maximize ∑kNklog⁡πk\sum_k N_k \log \pi_k subject to ∑kπk=1\sum_k \pi_k = 1. A Lagrange multiplier gives πk∝Nk\pi_k \propto N_k (the topic Lagrange multipliers and KKT conditions).
  • Means. The gradient in μk\mu_k is Σk−1∑irik(xi−μk)\Sigma_k^{-1} \sum_i r_{ik} (x_i - \mu_k). It vanishes at the weighted mean.
  • Covariances. The derivatives of log⁡det⁡\log \det and of a trace (the topic Matrix calculus) give the weighted covariance.

Together the M-step is

πk=Nkn,μk=1Nk∑i=1nrik xi,Σk=1Nk∑i=1nrik (xi−μk)(xi−μk)⊤.\pi_k = \frac{N_k}{n}, \qquad \mu_k = \frac{1}{N_k} \sum_{i=1}^n r_{ik}\, x_i, \qquad \Sigma_k = \frac{1}{N_k} \sum_{i=1}^n r_{ik}\, (x_i - \mu_k)(x_i - \mu_k)^\top .

These are the Gaussian maximum likelihood estimates with every point counted with weight rikr_{ik}, and Σk\Sigma_k uses the new μk\mu_k. One iteration costs O(nKd2)O(nKd^2) for the responsibilities plus O(Kd3)O(Kd^3) for the inverses and determinants. The E-step is computed in logarithms, with log⁡∑kexp⁡(⋅)\log \sum_k \exp(\cdot) evaluated stably, because densities underflow in high dimension.

On 300 points. Take 300 points in the plane from three Gaussians: one tilted and elongated, one small, one wide. Start EM badly on purpose, with all three means at points of the first cloud. The average log-likelihood is −8.600-8.600 at the start, −4.070-4.070 after one iteration, −3.803-3.803 after five, −3.383-3.383 after 25 and −3.259-3.259 after 50, and it never falls. scikit-learn's GaussianMixture from the same start reaches the same −3.259-3.259. Against the true clusters, the fitted mixture scores an adjusted Rand index (ARI, the topic Clustering) of 0.9910.991, k-means only 0.9130.913. k-means draws straight boundaries halfway between centres and hands 8 points of the elongated tilted cloud to the small cluster.

k-means as the hard limit

Where is k-means in all this? Fix every covariance at Σk=s2I\Sigma_k = s^2 I with a known ss and update only the means. The responsibilities become

rik=πkexp⁡(−∥xi−μk∥2/2s2)∑jπjexp⁡(−∥xi−μj∥2/2s2).r_{ik} = \frac{\pi_k \exp\big( -\lVert x_i - \mu_k \rVert^2 / 2s^2 \big)}{\sum_j \pi_j \exp\big( -\lVert x_i - \mu_j \rVert^2 / 2s^2 \big)} .

As s→0s \to 0, the term of the nearest mean beats every other by a factor that grows without bound. So rik→1r_{ik} \to 1 for the nearest centre and 00 for the rest: the E-step becomes the assignment step of k-means. The M-step for the means becomes the mean of the assigned points, the update step. And QQ becomes −J/2s2-J / 2s^2 plus terms that do not involve the means. Lloyd's algorithm is EM for identical spherical Gaussians in the limit of vanishing variance. On the 300 points with s=0.01s = 0.01, every responsibility is 00 or 11, and the means coincide with the k-means centres from the same start.

Replacing the posterior by its most probable value is called hard EM. It no longer maximizes the likelihood. A point in the overlap of two clusters goes entirely to one of them, and that pushes the means apart. In the toy run, hard EM from θ0=1\theta^0 = 1 ends at θ=3.133\theta = 3.133, the mean of 2.5,3.1,3.82.5, 3.1, 3.8. Soft EM ends at 2.9102.910, the maximum of the likelihood: there ℓ=−12.63\ell = -12.63, at the hard answer −12.69-12.69.

Starts, collapses and the number of components

Starts. Monotonicity promises progress, not the destination. On the 300 points, 30 runs started from random data points end at six different values of the average log-likelihood, from −3.703-3.703 to −3.259-3.259, and 83% reach the best one. All 30 runs started from k-means++ centres reach it. Hence the recipe: start from k-means or k-means++ (scikit-learn runs k-means first by default), make several starts, keep the highest likelihood. EM is also slow when components overlap heavily, because the responsibilities, and with them the steps, change little.

Collapses. A component that captures one or two points can shrink its covariance towards a singular matrix while ℓ\ell grows. Three defences: add a small constant to the diagonal of every Σk\Sigma_k (reg_covar in scikit-learn, 10−610^{-6} by default); put a prior on the covariances and fit the MAP estimate, a regularized M-step in the sense of the topic Regularization; or restrict the covariances to be shared, diagonal or spherical, which also cuts the parameter count.

How many components. The likelihood cannot choose KK, for the same reason JJ cannot. On the 300 points it is −1244.0-1244.0, −1102.8-1102.8, −977.7-977.7, −975.5-975.5, −973.0-973.0, −966.4-966.4 for K=1,…,6K = 1, \dots, 6, and it keeps rising. The Bayesian information criterion penalizes the number of free parameters pp:

BIC=−2 ℓ(θ^)+plog⁡n,p=(K−1)+Kd+Kd(d+1)2,\text{BIC} = -2\, \ell(\hat\theta) + p \log n , \qquad p = (K - 1) + Kd + K \frac{d(d + 1)}{2} ,

and smaller is better. The three parts of pp are the weights minus one constraint, the means, and the symmetric covariances. For d=2d = 2 and K=3K = 3, p=2+6+9=17p = 2 + 6 + 9 = 17. On the 300 points the BIC is 2516.52516.5, 2268.42268.4, 2052.52052.5, 2082.22082.2, 2111.52111.5, 2132.42132.4, smallest at K=3K = 3. BIC is a large-sample approximation. The alternative without asymptotics is the log-likelihood on held-out data, as in the topic Validation and overfitting.

Further. Nothing in the derivation used Gaussians. EM works whenever the complete-data likelihood is easy and the posterior of the latent variables is computable: missing values, mixtures of other distributions, hidden Markov models. Bayesian Methods in Machine Learning, in the topic EM and Bayesian PCA, treats EM in general and what to do when the exact E-step is out of reach. Generative Models, in the topic Latent variables and the ELBO, keeps the same bound for a continuous zz and a neural decoder: the posterior is no longer computable, so an encoder learns to approximate it, and that is the variational autoencoder.

A mixture explains each point by a discrete latent variable, the cluster it came from. Clusters summarize objects. The next topic, Dimensionality reduction, summarizes features instead: it finds a few continuous directions along which the data vary. Its probabilistic version, probabilistic PCA, is again a latent-variable model fitted by maximum likelihood, this time with a continuous zz.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.