Gaussian mixtures and the EM algorithm

Why Does K-Means Split the Penguins Wrong?

K-means on the penguins' bills: the 25 ringed birds are in another species' cluster

Last time k-means sorted 342 penguins by their bills, with nobody telling it the species, and got 93% of them right. The 25 it got wrong are not random: they sit where the species' clouds, which are tilted ellipses, cross the straight borders k-means draws. Today we replace each round cluster by a Gaussian with a shape of its own, fit it with the EM algorithm, and see how many birds it gives back.

By the end you can

  • write a Gaussian mixture as a model that generates data, and its likelihood
  • run EM by hand: responsibilities in the E-step, weighted means and covariances in the M-step
  • explain k-means as EM with round clusters that shrink to points
  • choose k with BIC, and spot collapsing components and poor local optima

About 75 minutes, with a duel between k-means and the mixture, and EM by hand on six points.

It builds on k-means and on Gaussian discriminant analysis.

Five questionsEach answer raises the next one

  1. 1Round clustersWhy does k-means split the penguins wrong?
  2. 2A model that makes penguinsWhat process could have produced these birds?
  3. 3Expectation-MaximizationHow do you fit a model whose labels are hidden?
  4. 4The penguins, fittedWhat does the mixture see that k-means did not?
  5. 5Choosing k, and failingHow many components, and when does EM go wrong?

K-means against a mixtureIn teams: predict which one puts more birds with their species, then check

method
colour

Both see only the standardized bill length and depth, k = 3. K-means' circles are the round, equal clusters it assumes; the mixture's ellipses are fitted, one shape per cluster.

Over all birds, longer bills are shallower (correlation −0.24); inside each species they are deeper (+0.39, +0.65, +0.64). That is what tilts the three clouds.

Modeling data as a Mixture of GaussiansEach group is a Gaussian with its own centre and its own shape

Dataset

\(x_1\)\(x_2\)
-0.5-0.4
0.60.1
-0.70.8
……

How to find \(\mu_1, \mu_2, \Sigma_1, \Sigma_2\)?

Part 2 of 5

A model that makes penguins

What process could have produced these birds?

Modeling data as a Mixture of GaussiansOne measurement first: the flipper lengths of the 342 penguins

Dataset

\(x\)
181
186
195
193
…

Assume:

  • Data is modeled by a mixture of Gaussians: \(\mathcal{N}(\mu_j, \sigma_j^2)\)
  • We know how many Gaussians we need (here 2)
Find \(\mu_1, \mu_2, \sigma_1, \sigma_2\)

Observations \(x^{(i)} \in \mathbb{R}\). Each dot is a bird; flippers are measured in whole millimetres, so birds stack. The curves are the two Gaussians EM finds, \(\mu = 191, 216\) mm and \(\sigma = 6.5, 7.3\) mm: Adelie and Chinstrap together, then Gentoo.

Modeling data as a Mixture of GaussiansGiven \(x^{(1)}, \ldots, x^{(n)}\) and \(k > 0\), the number of clusters. Drag \(x\) along the axis

Soft assignment: find \(P(z^{(i)} = j \mid x^{(i)})\)

the probability that point \(i\) belongs to cluster \(j\), once we have seen the point \(x^{(i)}\)

\(z^{(i)}\), the cluster of point \(i\), is never observed: it is a latent (hidden) variable

K-means gave each point one cluster, \(c^{(i)}\). A mixture gives each a probability for every cluster. A bird with a 204 mm flipper is about as likely to be in either.

Gaussian Mixture ModelThe joint distribution of a point and its hidden cluster

Observations: \(x^{(i)} \in \mathbb{R}\). Number of clusters: \(k > 0\).
The hidden cluster of point \(i\): \(z^{(i)} \in \{1, \dots, k\}\).

$$\begin{aligned} P(x^{(i)}, z^{(i)}) &= P(x^{(i)} \mid z^{(i)})\, P(z^{(i)}) \\ P(z^{(i)}) &= \text{Multinomial}(\phi) \\ P(x^{(i)} \mid z^{(i)} = j) &= \mathcal{N}(\mu_j, \sigma_j^2) \end{aligned}$$

The parameters are \(\phi \in \mathbb{R}^k\) with \(\sum_{j=1}^k \phi_j = 1\) (how common each cluster is), and for each cluster a mean and a variance. In \(d\) dimensions \(\mu_j \in \mathbb{R}^d\) and \(\sigma_j^2\) becomes a covariance matrix \(\Sigma_j \in \mathbb{R}^{d \times d}\).

This is the model of Gaussian discriminant analysis (GDA), from the classification lectures, with one difference: there \(z\) was the species, written in the data. Here it is hidden.

Gaussian Mixture ModelIntuition: if one were to 'create' the data

\(\phi_1 =\) 0.30 \(\xrightarrow{\text{sample}} \mathcal{N}(\mu_1, \sigma_1^2) \xrightarrow{} x^{(i)}\)

\(\phi_2 =\) 0.70 \(\xrightarrow{\text{sample}} \mathcal{N}(\mu_2, \sigma_2^2) \xrightarrow{} x^{(i)}\)

With \(\mu_1 = 1\), \(\sigma_1 = 1.3\), \(\mu_2 = 3\), \(\sigma_2 = 1.6\). First choose a cluster with probability \(\phi_j\), then draw \(x\) from its Gaussian.

Each bar shows the samples from one cluster (cluster 1 in teal, cluster 2 in red), under that cluster's dashed curve; the white curve is their sum, the density of the data. In real data the colors are gone: we see only the total, and EM's job is to guess the colors back.

Penguins made by the modelThe same recipe in two dimensions, with the mixture EM fits to the bills

show

Each made bird: a component \(j\) with probability \(\phi_j\) (0.46, 0.18, 0.35), then a bill from \(\mathcal{N}(\mu_j, \Sigma_j)\). The species' true shares are 0.44, 0.20, 0.36.

A generative model is judged by whether what it makes looks like the data. These look like penguins' bills: three tilted clouds, overlapping where the real ones do.

The notationContinued from k-means; it does not change for the rest of the lecture

\(x^{(i)} \in \mathbb{R}^d\)point \(i\), for \(i = 1, \ldots, n\) (here \(d = 2\): bill length and depth, standardized)
\(k\)the number of clusters (components), chosen by us
\(z^{(i)} \in \{1, \ldots, k\}\)the hidden cluster of point \(i\); k-means guessed it as \(c^{(i)}\)
\(\phi_j = P(z = j)\)how common cluster \(j\) is; \(\phi \in \mathbb{R}^k\), \(\sum_j \phi_j = 1\)
\(\mu_j \in \mathbb{R}^d,\ \Sigma_j \in \mathbb{R}^{d \times d}\)the mean and covariance of cluster \(j\)
\(w_j^{(i)} = P(z^{(i)} = j \mid x^{(i)})\)the responsibility of cluster \(j\) for point \(i\); \(W \in \mathbb{R}^{n \times k}\), rows sum to 1
\(\ell(\phi, \mu, \Sigma)\)the log-likelihood of the data, next slide
\(J(c, \mu)\)k-means' distortion, as before

The likelihoodHow probable the data are under the parameters. Drag a mean (a cross) and watch it fall

$$\ell(\phi, \mu, \Sigma) = \sum_{i=1}^n \log \sum_{j=1}^k \phi_j\, \mathcal{N}(x^{(i)}; \mu_j, \Sigma_j)$$

We want the parameters that make \(\ell\) largest. For GDA this had a closed form, because each point's cluster was known. Here each term is the log of a sum over the unknown cluster, and setting the gradient to zero ties every \(\mu_j\) to all the others. EM is a way around that.

Part 3 of 5

Expectation-Maximization

How do you fit a model whose labels are hidden?

Expectation-Maximization (EM) AlgorithmTwo guesses, each easy when the other is known

E-Step: Guess \(z^{(i)}\) given \(\phi, \mu, \sigma\). Compute \(P(z^{(i)} \mid x^{(i)}; \phi, \mu, \sigma)\)

M-Step: Estimate \(\phi, \mu, \sigma\) using Maximum Likelihood Estimation

The E-step, one step at a time (1 of 2)The soft assignment \(w_j^{(i)}\) of point \(i\) to cluster \(j\), derived with Bayes' rule

Step 1: what we want\[w_j^{(i)} \;=\; P(z^{(i)} = j \mid x^{(i)})\] The probability that point \(i\) came from cluster \(j\), now that we have seen the point. The bar \(\mid\) reads "given": first the event we ask about, then what we know. This \(w_j^{(i)}\) is the soft assignment, also called the responsibility of cluster \(j\) for point \(i\).
Step 2: a conditional probability is a joint probability divided by a marginal one\[P(z^{(i)} = j \mid x^{(i)}) \;=\; \frac{P(z^{(i)} = j,\ x^{(i)})}{P(x^{(i)})}\] Top: the probability that the model chooses cluster \(j\) and makes this point. Bottom: the probability that it makes this point at all, through any cluster (called the marginal probability of the point). The ratio is the share of the ways to make \(x^{(i)}\) that go through cluster \(j\).

The E-step, one step at a time (2 of 2)Write the top and the bottom with the parameters of the mixture

Step 3: the top, the way the model makes a point\[P(z^{(i)} = j,\ x^{(i)}) \;=\; P(z^{(i)} = j)\; p(x^{(i)} \mid z^{(i)} = j) \;=\; \phi_j\; \mathcal{N}(x^{(i)}; \mu_j, \sigma_j^2)\] First the cluster, with probability \(\phi_j\); then the point, from that cluster's Gaussian.
Step 4: the bottom adds every way to make the point\[P(x^{(i)}) \;=\; \sum_{s=1}^{k} \phi_s\; \mathcal{N}(x^{(i)}; \mu_s, \sigma_s^2)\] The point came from one of the \(k\) clusters, so its probability is the sum of the \(k\) ways.
The E-step\[w_j^{(i)} \;=\; \frac{\phi_j\, \mathcal{N}(x^{(i)}; \mu_j, \sigma_j^2)}{\sum_{s=1}^{k} \phi_s\, \mathcal{N}(x^{(i)}; \mu_s, \sigma_s^2)}\] Every piece is a parameter we already have, so the E-step is a little arithmetic per point and cluster. It is Bayes' rule, the same rule that turned GDA (Gaussian discriminant analysis) into a classifier.

Expectation StepE-Step: Guess \(z^{(i)}\) given \(\phi, \mu, \sigma\). Every piece is a parameter we have

$$w_j^{(i)} = P(z^{(i)} = j \mid x^{(i)}; \phi, \mu, \sigma) = \dfrac{\overbrace{\colorbox{#1e6b2c}{$P(x^{(i)} \mid z^{(i)} = j)$}}^{\mathcal{N}(\mu_j,\, \sigma_j^2)}\ \overbrace{\colorbox{#6b1650}{$P(z^{(i)} = j)$}}^{\phi_j}}{\sum_{s=1}^k \underbrace{\colorbox{#1e6b2c}{$P(x^{(i)} \mid z^{(i)} = s)$}}_{\mathcal{N}(\mu_s,\, \sigma_s^2)}\ \underbrace{\colorbox{#6b1650}{$P(z^{(i)} = s)$}}_{\phi_s}}$$

The green factor is the Gaussian density of cluster \(j\) at the point, the purple one how common cluster \(j\) is. Their product, divided by the same product summed over all clusters, is a number between 0 and 1, and the \(k\) of them for one point add up to 1.

Expectation Step · one birdThe formula with numbers, for the fitted mixture. Click any bird

The penguin highlighted in the k-means lecture, a Chinstrap, was 1.09 standard deviations from the Gentoo center and 1.11 from the Chinstrap one, so k-means gave it to the Gentoo. The Chinstrap Gaussian is tilted towards it, and its responsibility is 0.97.

Maximization StepM-Step: Given \(P(z^{(i)} = j) \equiv w_j^{(i)}\), estimate \(\phi, \mu, \sigma\)

Maximum Likelihood Estimation

  • The log-likelihood of the data, one term per point. \( \ell(\phi, \mu, \Sigma) = \sum_{i=1}^n \log P(x^{(i)}; \phi, \mu, \sigma) \)
  • Each point's probability is a sum over the cluster it might have come from. \( = \sum_{i=1}^n \log \sum_{z^{(i)}=1}^k P(x^{(i)} \mid z^{(i)}; \mu, \sigma)\, P(z^{(i)}; \phi) \)
  • If \(z^{(i)}\) is known, the sum disappears and the log splits into two easy pieces. \( = \sum_{i=1}^n \log p(x^{(i)} \mid z^{(i)}; \mu, \sigma) + \log p(z^{(i)}; \phi) \)

Maximization StepIf \(z^{(i)}\) were known: Gaussian Discriminant Analysis, each Gaussian fitted to its own birds

$$\begin{aligned} \phi_j &= \frac{1}{n} \sum_{i=1}^n 1\{z^{(i)} = j\} \\[4pt] \mu_j &= \frac{\sum_{i=1}^n 1\{z^{(i)} = j\}\, x^{(i)}}{\sum_{i=1}^n 1\{z^{(i)} = j\}} \\[4pt] \Sigma_j &= \frac{\sum_{i=1}^n 1\{z^{(i)} = j\}\, (x^{(i)} - \mu_j)(x^{(i)} - \mu_j)^T}{\sum_{i=1}^n 1\{z^{(i)} = j\}} \end{aligned}$$

This is Gaussian discriminant analysis (GDA), from the classification lectures. When every bird's species \(z^{(i)}\) is known, each Gaussian is fitted to its own birds. The indicator \(1\{z^{(i)} = j\}\) is 1 if bird \(i\) is in cluster \(j\) and 0 otherwise, so each sum runs over the birds of cluster \(j\) only. Inside each species longer bills are deeper (correlations +0.39, +0.65, +0.64), which tilts the ellipses.

Maximization StepEM does not know \(z^{(i)}\): it uses GDA's formulas with the soft assignments in place of the indicators

$$\begin{aligned} \phi_j &= \frac{1}{n} \sum_{i=1}^n w_j^{(i)} \\[4pt] \mu_j &= \frac{\sum_{i=1}^n w_j^{(i)} x^{(i)}}{\sum_{i=1}^n w_j^{(i)}} \\[4pt] \Sigma_j &= \frac{\sum_{i=1}^n w_j^{(i)} (x^{(i)} - \mu_j)(x^{(i)} - \mu_j)^T}{\sum_{i=1}^n w_j^{(i)}} \end{aligned}$$
assignments

Compare with GDA on the previous slide: the formulas are the same, with the responsibility \(w_j^{(i)}\) where GDA had the indicator \(1\{z^{(i)} = j\}\). In GDA each bird counts fully in one cluster (weight 1) and not at all in the others (weight 0); here it counts with weight \(w_j^{(i)}\) in every cluster. Found without the species, EM's ellipses come out close to the species' own, with a higher \(\ell\).

EM Algorithm SummaryStart from a guess of \(\phi, \mu, \Sigma\), then repeat until the log-likelihood \(\ell\) (how probable the data are under the mixture) stops rising

E-Step: Estimate \(w_j^{(i)}\)
$$w_j^{(i)} = \dfrac{\overbrace{\colorbox{#1e6b2c}{$P(x^{(i)} \mid z^{(i)} = j)$}}^{\mathcal{N}(\mu_j,\, \Sigma_j)}\ \overbrace{\colorbox{#6b1650}{$P(z^{(i)} = j)$}}^{\phi_j}}{\sum_{s=1}^k \underbrace{\colorbox{#1e6b2c}{$P(x^{(i)} \mid z^{(i)} = s)$}}_{\mathcal{N}(\mu_s,\, \Sigma_s)}\ \underbrace{\colorbox{#6b1650}{$P(z^{(i)} = s)$}}_{\phi_s}}$$
Iterate
M-Step: Estimate \(\phi, \mu, \Sigma\)
$$\phi_j = \frac{1}{n} \sum_{i=1}^n w_j^{(i)}$$ $$\mu_j = \frac{\sum_{i=1}^n w_j^{(i)} x^{(i)}}{\sum_{i=1}^n w_j^{(i)}}$$ $$\Sigma_j = \frac{\sum_{i=1}^n w_j^{(i)} (x^{(i)} - \mu_j)(x^{(i)} - \mu_j)^T}{\sum_{i=1}^n w_j^{(i)}}$$

EM on the penguinsOne half-step per click. Watch the colours change in the E-step and the ellipses in the M-step

start

From this start \(\ell\) climbs from −1069 to −822.0 (dashed) in 46 iterations, never falling; from k-means' clusters it takes 39.

Why the log-likelihood never fallsEM climbs a lower bound that touches \(\ell\) after every E-step

  • For any weights \(w_j^{(i)} \ge 0\) that sum to 1 over \(j\), multiply and divide inside the log, then use that the log of an average is at least the average of the logs (Jensen). \( \ell(\theta) = \sum_i \log \sum_j w_j^{(i)} \frac{\phi_j \mathcal{N}(x^{(i)}; \mu_j, \Sigma_j)}{w_j^{(i)}} \ \ge\ \sum_i \sum_j w_j^{(i)} \log \frac{\phi_j \mathcal{N}(x^{(i)}; \mu_j, \Sigma_j)}{w_j^{(i)}} = B(w, \theta) \)
  • E-step. With \(w_j^{(i)} = P(z^{(i)} = j \mid x^{(i)}; \theta_t)\) the ratio inside the log is the same for every \(j\), so the inequality is an equality: \(B(w, \theta_t) = \ell(\theta_t)\).
  • M-step. With \(w\) fixed, \(B\) is a weighted GDA likelihood, and the M-step formulas maximize it, so \(B(w, \theta_{t+1}) \ge B(w, \theta_t)\). \( \ell(\theta_{t+1}) \ \ge\ B(w, \theta_{t+1}) \ \ge\ B(w, \theta_t) = \ell(\theta_t) \)

So \(\ell\) rises or stays, and stops at a stationary point: a local maximum, not always the highest one. The CS229 notes on EM (cs229.stanford.edu) give the general argument.

EM by handThe six points of the k-means exercise, two Gaussians with \(\sigma = 1\)

✏ exercise · do it now

The points are \(1, 2, 3, 7, 8, 12\). Start with \(\mu_1 = 2\), \(\mu_2 = 3\), \(\phi_1 = \phi_2 = \tfrac12\), and keep \(\sigma_1 = \sigma_2 = 1\) fixed.

  1. E-step: compute \(w_1^{(i)}\) and \(w_2^{(i)} = 1 - w_1^{(i)}\) for each point.
  2. M-step: compute the new \(\phi_1, \phi_2\) and \(\mu_1, \mu_2\).
  3. Compare with k-means' first update from the same start, \(\mu = (1.5,\ 7.5)\). Which centre moved further, and why?

Hint: with equal \(\phi\) and \(\sigma\), \(w_1 = \dfrac{1}{1 + e^{x - 2.5}}\) (work it out from the E-step formula). A phone calculator is enough.

EM by hand · answerOne E-step and one M-step, and where EM stops

\(x\)\(w_1\)\(w_2\)
10.820.18
20.620.38
30.380.62
70.010.99
80.001.00
120.001.00

\(\phi = (0.30,\ 0.69), \quad \mu_1 = 1.80, \quad \mu_2 = 7.13\)

\(\mu_1\) is a weighted mean that leans on 1, 2 and 3 (weights 0.82, 0.62, 0.38) and barely on the rest. \(\mu_2\) takes 3 at weight 0.62 and the right group almost fully, so it jumps to 7.13, close to k-means' 7.5: with \(\sigma = 1\) the points far from the start are already nearly hard.

Repeated, EM stops after 4 iterations at \(\mu = (2,\ 9)\) with \(\phi = (0.5,\ 0.5)\), where k-means stopped too: the groups are far apart compared with \(\sigma\).

K-means is EM with round clusters that shrinkFix every \(\Sigma_j = \sigma^2 I\) and every \(\phi_j = 1/k\), start where k-means started, and shrink \(\sigma\)

\(\sigma\)

With equal round Gaussians the E-step compares only distances:

$$w_j^{(i)} = \frac{e^{-\lVert x^{(i)} - \mu_j \rVert^2 / 2\sigma^2}}{\sum_s e^{-\lVert x^{(i)} - \mu_s \rVert^2 / 2\sigma^2}}$$

As \(\sigma\) shrinks the nearest center takes all the weight: \(w\) becomes \(1\{c^{(i)} = j\}\) (1 if k-means puts point \(i\) in cluster \(j\), 0 otherwise) and the M-step is k-means' update. From \(\sigma = 0.2\) down, every bird is assigned as k-means does.

Part 4 of 5

The penguins, fitted

What does the mixture see that k-means did not?

Soft assignments on the penguinsA colour mixed from the three components is a bird EM is unsure about. Click one

colour

The mixture misplaces 12 birds, k-means 25. It also says where it might be wrong: 25 birds have no responsibility above 0.9, and 7 of the 12 mistakes are among them. K-means' \(c^{(i)}\) is equally confident about every bird.

The shape of a clusterWhat each covariance allows: round, stretched along the axes, one shared tilt, or a tilt each

covariance
data
with their speciesbillsall four
k-means93%92%
spherical92%94%
diag84%64%
tied96%99%
full96%99%

Round clusters do no better than k-means, and clusters stretched only along the axes do worse: the species are tilted. The gain comes from the tilt. On all four measurements a full mixture misplaces 5 of 342 birds.

Generate Synthetic DataThree round Gaussians, 100 points each: the code from the original slides and notebook

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal

# Seed for reproducibility
np.random.seed(42)

# Generate synthetic data from 3 Gaussian distributions
mean1, cov1 = [5, 5], [[1, 0], [0, 1]]
mean2, cov2 = [0, 0], [[1, 0], [0, 1]]
mean3, cov3 = [8, 1], [[1, 0], [0, 1]]

data1 = np.random.multivariate_normal(mean1, cov1, 100)
data2 = np.random.multivariate_normal(mean2, cov2, 100)
data3 = np.random.multivariate_normal(mean3, cov3, 100)

# Combine all data
data = np.vstack((data1, data2, data3))

# Number of clusters
k = 3
n, d = data.shape
print(n, 'points in', d, 'dimensions')

It prints 300 points in 2 dimensions. Run this block, then the next two.

Initialize ParametersEqual weights, random means, identity covariances

# Initialize parameters
phi = np.ones(k) / k                                # equal mixing weights
mu = np.random.rand(k, d) * 10                      # random means in the square [0, 10]^2
Sigma = np.array([np.eye(d) for _ in range(k)])     # identity covariance matrices

# EM algorithm parameters
max_iter = 100
tol = 1e-6
log_likelihoods = []
print('starting means:', np.round(mu, 2).tolist())

It prints the three starting means: [[2.29, 7.22], [7.2, 6.41], [6.94, 5.43]].

Expectation-Maximization UpdatesThe E-step, the M-step and the log-likelihood, until it stops rising

for iteration in range(max_iter):
    # E-step: compute responsibilities w_j^(i)
    p = np.zeros((n, k))
    for j in range(k):
        p[:, j] = phi[j] * multivariate_normal.pdf(data, mean=mu[j], cov=Sigma[j])
    log_likelihood = np.sum(np.log(p.sum(axis=1)))   # l(phi, mu, Sigma) before this update
    w = p / p.sum(axis=1, keepdims=True)

    # M-step: update phi (mixing weights), mu (means) and Sigma (covariances)
    Nk = w.sum(axis=0)
    phi = Nk / n
    mu = (w.T @ data) / Nk[:, np.newaxis]
    for j in range(k):
        diff = data - mu[j]
        Sigma[j] = (w[:, j, np.newaxis] * diff).T @ diff / Nk[j]

    log_likelihoods.append(log_likelihood)
    # Check for convergence
    if iteration > 0 and abs(log_likelihood - log_likelihoods[-2]) < tol:
        print(f'Converged at iteration {iteration}')
        break

print('log-likelihood:', ' '.join(f'{v:.1f}' for v in log_likelihoods[:6]), '...', f'{log_likelihoods[-1]:.2f}')
print('means:', np.round(mu, 2).tolist())

fig, ax = plt.subplots(1, 2, figsize=(9, 4))
ax[0].scatter(data[:, 0], data[:, 1], c=w.argmax(axis=1), s=10)
ax[0].plot(mu[:, 0], mu[:, 1], 'kx', markersize=12)
ax[1].plot(log_likelihoods, 'o-')
ax[1].set_xlabel('iteration'); ax[1].set_ylabel('log-likelihood')
plt.show()

It prints Converged at iteration 17; log-likelihood: -5185.3 -1315.4 -1266.9 -1233.7 -1203.9 -1198.6 ... -1157.42; means: [[0.13, 0.04], [4.89, 5.03], [7.95, 0.87]].

The penguins in numpyEM in vectors, the sums done in logs, ten starts, then the species

import numpy as np
import pandas as pd

d = pd.read_csv('penguins.csv').dropna(subset=['bill_length_mm', 'bill_depth_mm'])
X = d[['bill_length_mm', 'bill_depth_mm']].values
X = (X - X.mean(axis=0)) / X.std(axis=0)          # standardize, as for k-means
n, dim = X.shape

def log_gauss(X, mu, S):                          # log N(x; mu, S) for every row of X
    diff = X - mu
    q = np.sum(diff @ np.linalg.inv(S) * diff, axis=1)
    return -0.5 * (dim * np.log(2 * np.pi) + np.log(np.linalg.det(S)) + q)

def em(X, k, rng, iters=500):
    phi = np.ones(k) / k
    mu = X[rng.choice(n, k, replace=False)]       # k random birds as the first means
    S = np.array([np.eye(dim)] * k)
    for _ in range(iters):
        lp = np.stack([np.log(phi[j]) + log_gauss(X, mu[j], S[j]) for j in range(k)], axis=1)
        ll = np.logaddexp.reduce(lp, axis=1)      # log p(x(i)), summed in logs
        w = np.exp(lp - ll[:, None])              # E-step: responsibilities, n by k
        Nk = w.sum(axis=0)                        # M-step
        phi, mu = Nk / n, (w.T @ X) / Nk[:, None]
        S = np.array([((w[:, j, None] * (X - mu[j])).T @ (X - mu[j])) / Nk[j] + 1e-6 * np.eye(dim) for j in range(k)])
    return w, ll.sum()

rng = np.random.default_rng(0)
runs = [em(X, 3, rng) for _ in range(10)]          # 10 starts, keep the highest log-likelihood
w, ll = max(runs, key=lambda r: r[1])
print(f'log-likelihood = {ll:.1f}')
print(pd.crosstab(w.argmax(axis=1), d.species))    # the species were never used above
print('birds with no responsibility above 0.9:', int((w.max(axis=1) < 0.9).sum()))

It prints log-likelihood = -822.0, a table with 330 of 342 birds on the matched diagonal, and birds with no responsibility above 0.9: 25.

Part 5 of 5

Choosing k, and failing

How many components, and when does EM go wrong?

How many components? BICThe likelihood always prefers more. BIC charges for every parameter. Click a k

data
k

\(\text{BIC} = -2\,\ell + p \log n\)

\(p\) counts \(k - 1\) weights, \(k d\) means and \(k\, d(d+1)/2\) covariances. BIC is lowest at k = 3 on the bills (1951, 1795, 1743, 1761, 1786, 1801, 1809 for k = 1 to 7) and on all four measurements. The notebook's AIC, \(-2\ell + 2p\), charges less per parameter.

Where you start matters200 random starts, k = 3 on the bills: every run climbs, not every run reaches the top

159 of 200 end at \(\ell = −822.0\). The others stop at \(\ell = −862.1, −858.2\): Chinstrap and Gentoo share one component and the spare one goes elsewhere, mostly to part of the Adelie (205 to 278 birds with their species). The notebook's fixes: start from k-means' clusters, or run several starts and keep the highest \(\ell\).

A component that collapsesFlipper lengths are whole millimetres: 55 values for 342 birds. A Gaussian can sit on one of them

k added to \(\sigma^2\)

At its own mean a Gaussian's density is \(1/(\sigma_j\sqrt{2\pi})\), so as \(\sigma_j\) shrinks onto a shared value, \(\ell\) grows without bound.

Out of 100 random starts it happens 0, 0, 4, 22, 32, 59 times for k = 2, 3, 4, 5, 6, 8. The notebook's fixes: add a small number to every variance (scikit-learn adds \(10^{-6}\)), use fewer components, restart.

Takeaways

  • A Gaussian mixture is a generative model: choose a cluster \(z\) with probability \(\phi_j\), then a point from \(\mathcal{N}(\mu_j, \Sigma_j)\). Clustering is guessing \(z\) back.
  • EM alternates two easy steps: the E-step computes each point's responsibilities by Bayes' rule, the M-step refits \(\phi, \mu, \Sigma\) as GDA would, with fractional counts. The log-likelihood never falls.
  • K-means is EM with equal round clusters that shrink to points. The penguins' species are tilted, so a full mixture does better: 93% to 96% on the bills, 92% to 99% on all four measurements.
  • BIC picks k = 3 here. EM still needs several starts and a floor under every variance.