---
title: "Clustering project: EM and principal components"
heading: Fitting a Gaussian mixture by expectation-maximization and watching its log-likelihood climb, computing principal components and checking that reconstruction error equals the discarded eigenvalues, then combining the two to find clusters in ten-dimensional data without labels
eyebrow: S14 · Lesson 51 · Clustering project
xp: 80
---

::: hook
Unlabeled data is the common case in practice: logged sensor readings, test measurements from a production line, signals from an unknown number of sources. This project builds a small unsupervised pipeline from lessons 36 and 40. You'll write EM for a one-dimensional Gaussian mixture and confirm its key guarantee, a log-likelihood that never decreases. You'll write PCA and confirm an exact identity relating reconstruction error to eigenvalues. Then you'll use PCA to find the one direction that matters in ten-dimensional data and EM to separate the two populations along it.
:::

::: predict
## Two clusters in 10 dimensions have centers 6 units apart along one direction and unit-variance noise in every direction. What's the largest eigenvalue of the data's covariance?

- [ ] About 1
- [ ] About 6
- [x] About 10
- [ ] About 36

::: reveal
Along the line joining the centers, each point sits at ±3 plus unit noise, so the variance there is about 3² + 1 = 10 (a little less with unequal cluster sizes: 0.4 × 0.6 × 6² + 1 = 9.6). Every perpendicular direction has only the noise variance, 1. PCA finds that one direction immediately, and in the test data its eigenvalue comes out at 9.8.
:::
:::

::: nameit
## Step 1: EM

`em_gmm_1d` alternates lesson 36's E step, $\gamma_{nk} \propto \pi_k\mathcal{N}(x_n|\mu_k, \sigma_k^2)$, and M step, $\mu_k = \sum_n\gamma_{nk}x_n/N_k$, $\sigma_k^2 = \sum_n\gamma_{nk}(x_n - \mu_k)^2/N_k$, $\pi_k = N_k/N$. Record $\sum_n\ln p(x_n)$ before each update; the tests check it never decreases and that 2000 samples from 0.3 N(−2, 0.5²) + 0.7 N(1.5, 1) give back those parameters.

## Step 2: PCA

`pca` returns the mean, the top M eigenvectors of the covariance (with 1/N normalization) as rows, and all eigenvalues, largest first. `reconstruct` maps each point onto the components and back. The tests build data whose covariance is exactly lesson 40's [[3, 1], [1, 2]], and check that the mean squared reconstruction error equals the sum of the discarded eigenvalues.

## Step 3: clustering

`cluster` projects ten-dimensional data onto its first principal component and fits a two-component mixture there, starting the means at the 25th and 75th percentiles so the components start on opposite sides. Each point gets the label of the component with the larger responsibility.
:::

::: example
## What does one EM step give for the points 0, 1 and 4, starting from means 0 and 4, unit variances and equal weights?

::: solution
1. **E step.** The first component takes responsibilities 0.99966, 0.98201 and 0.00034, so
   $$\begin{aligned} N_1 &= 1.982 \\ \pi_1 &= 0.661 \end{aligned}$$
2. **First component's M step.** Its new mean is 0.496 and its variance 0.252.
3. **Second component's M step.** It moves to mean 3.946 with variance 0.161.
4. **Log-likelihood.** Before the step it is −5.317.

**Answer:** after one step $\pi_1$ = 0.661, the means are 0.496 and 3.946, and the variances 0.252 and 0.161; the log-likelihood before the step is −5.317.
:::
:::

::: example
## What should the finished pipeline report on the test data?

::: solution
1. **Step 1's fit.** Means −1.983 and 1.459, widths 0.493 and 1.026 and weights 0.305 and 0.695, close to the generating values.
2. **Log-likelihood.** It climbs from −4174 to −3605 and never falls.
3. **Step 3's components.** The first eigenvalue is 9.82 against about 1.2 for the next, and the first component lines up with the true direction to within 4° (cosine 0.998).
4. **Labels.** They match the truth for all 400 points.

**Answer:** means −1.983 and 1.459, widths 0.493 and 1.026, weights 0.305 and 0.695, a log-likelihood that climbs from −4174 to −3605, a first eigenvalue of 9.82 with its component within 4° of the true direction, and correct labels for all 400 points.
:::
:::

::: check
kind: python

## Step 1. Write `em_gmm_1d`: expectation-maximization for a Gaussian mixture.

```python starter
import numpy as np

def gauss(x, mu, var):
    return np.exp(-(x - mu)**2/(2*var))/np.sqrt(2*np.pi*var)

def em_gmm_1d(x, mu, var, pi, iters=100):
    # EM for a one-dimensional Gaussian mixture. mu, var and pi are arrays of length K.
    # Each iteration: E step (responsibilities), then M step (new mu, var, pi).
    # Return (mu, var, pi, lls), where lls lists the log-likelihood sum(ln p(x_n))
    # computed with the parameters at the start of each iteration.
    return np.asarray(mu, float), np.asarray(var, float), np.asarray(pi, float), []

x = np.array([0.0, 1.0, 4.0])
print(em_gmm_1d(x, [0.0, 4.0], [1.0, 1.0], [0.5, 0.5], iters=1))
```

```python solution
import numpy as np

def gauss(x, mu, var):
    return np.exp(-(x - mu)**2/(2*var))/np.sqrt(2*np.pi*var)

def em_gmm_1d(x, mu, var, pi, iters=100):
    mu, var, pi = (np.array(a, dtype=float) for a in (mu, var, pi))
    lls = []
    for _ in range(iters):
        P = pi*gauss(x[:, None], mu, var)
        lls.append(np.sum(np.log(P.sum(axis=1))))
        g = P/P.sum(axis=1, keepdims=True)
        Nk = g.sum(axis=0)
        mu = (g*x[:, None]).sum(axis=0)/Nk
        var = (g*(x[:, None] - mu)**2).sum(axis=0)/Nk
        pi = Nk/len(x)
    return mu, var, pi, lls

x = np.array([0.0, 1.0, 4.0])
print(em_gmm_1d(x, [0.0, 4.0], [1.0, 1.0], [0.5, 0.5], iters=1))
```

```python tests
x = np.array([0.0, 1.0, 4.0])
mu, var, pi, lls = em_gmm_1d(x, [0.0, 4.0], [1.0, 1.0], [0.5, 0.5], iters=1)
P = 0.5*np.exp(-(x[:, None] - np.array([0.0, 4.0]))**2/2)
g = P/P.sum(axis=1, keepdims=True)
m1 = (g[:, 0]*x).sum()/g[:, 0].sum()
assert abs(mu[0] - m1) < 1e-12 and abs(pi[0] - g[:, 0].sum()/3) < 1e-12, f"One EM step on 0, 1, 4 from means 0 and 4 should give μ1 = {m1:.6f}, π1 = {g[:, 0].sum()/3:.6f}; got {mu[0]:.6f}, {pi[0]:.6f}."
assert len(lls) == 1 and abs(lls[0] - np.sum(np.log((P/np.sqrt(2*np.pi)).sum(axis=1)))) < 1e-12, "lls should hold one log-likelihood per iteration, computed before that iteration's update."
rng = np.random.default_rng(5)
z = rng.random(2000) < 0.3
data = np.where(z, rng.normal(-2.0, 0.5, 2000), rng.normal(1.5, 1.0, 2000))
mu, var, pi, lls = em_gmm_1d(data, [-1.0, 1.0], [1.0, 1.0], [0.5, 0.5], iters=200)
d = np.diff(lls)
assert np.all(d > -1e-9), f"The log-likelihood must never decrease; it fell by {-d.min():.3e} at one step."
o = np.argsort(mu); mu, var, pi = mu[o], var[o], pi[o]
assert abs(mu[0] + 2) < 0.08 and abs(mu[1] - 1.5) < 0.08 and abs(pi[0] - 0.3) < 0.03 and abs(np.sqrt(var[0]) - 0.5) < 0.05 and abs(np.sqrt(var[1]) - 1) < 0.06, f"The fit should recover means near -2 and 1.5, weights near 0.3 and 0.7 and widths near 0.5 and 1; got μ = {np.round(mu, 3)}, σ = {np.round(np.sqrt(var), 3)}, π = {np.round(pi, 3)}."
```

::: right
Right. Your EM never lowers the log-likelihood and recovers the mixture that generated the data, to within its sampling error.
:::
:::

::: check
kind: python

## Step 2. Write `pca` and `reconstruct`: principal components from the covariance.

```python starter
import numpy as np

def pca(X, M):
    # X is N x D. Return (mean, comps, lam): the mean (D), the top M principal directions as
    # rows of an M x D array (unit length), and ALL D eigenvalues of the covariance
    # (1/N normalization), largest first.
    D = X.shape[1]
    return np.zeros(D), np.zeros((M, D)), np.zeros(D)

def reconstruct(X, mean, comps):
    # Project each row of X onto the components and map back: mean + (X - mean) C^T C.
    return X

rng = np.random.default_rng(0)
Z = rng.standard_normal((500, 2))
print(pca(Z, 1))
```

```python solution
import numpy as np

def pca(X, M):
    mean = X.mean(axis=0)
    S = (X - mean).T @ (X - mean)/len(X)
    lam, U = np.linalg.eigh(S)
    o = np.argsort(lam)[::-1]
    lam, U = lam[o], U[:, o]
    return mean, U[:, :M].T, lam

def reconstruct(X, mean, comps):
    return mean + (X - mean) @ comps.T @ comps

rng = np.random.default_rng(0)
Z = rng.standard_normal((500, 2))
print(pca(Z, 1))
```

```python tests
rng = np.random.default_rng(0)
Z = rng.standard_normal((500, 2))
Z = Z - Z.mean(axis=0)
L0 = np.linalg.cholesky(Z.T @ Z/len(Z))
W = Z @ np.linalg.inv(L0).T
X = W @ np.linalg.cholesky(np.array([[3.0, 1.0], [1.0, 2.0]])).T + np.array([5.0, -1.0])
mean, comps, lam = pca(X, 1)
assert np.allclose(mean, [5.0, -1.0], atol=1e-10), f"The mean should be (5, -1); got {mean}."
assert np.allclose(lam, [(5 + np.sqrt(5))/2, (5 - np.sqrt(5))/2], atol=1e-10), f"The covariance [[3, 1], [1, 2]] has eigenvalues 3.618 and 1.382; got {lam}."
ang = np.degrees(np.arctan2(comps[0, 1], comps[0, 0])) % 180
assert abs(ang - 31.7174744115) < 1e-7, f"The first component should point at 31.717° (lesson 40); got {ang:.6f}°."
Y = rng.standard_normal((300, 6)) @ rng.standard_normal((6, 6))
mean, comps, lam = pca(Y, 2)
assert np.allclose(comps @ comps.T, np.eye(2), atol=1e-10), "The components must be orthonormal rows."
mse = np.sum((Y - reconstruct(Y, mean, comps))**2)/len(Y)
assert abs(mse - lam[2:].sum()) < 1e-9*lam.sum(), f"The reconstruction error per sample should equal the discarded eigenvalues, {lam[2:].sum():.6f}; got {mse:.6f}."
```

::: right
Right. Your components reproduce lesson 40's eigenvalues and 31.7° angle exactly, and the reconstruction error equals the discarded eigenvalues.
:::
:::

::: check
kind: python

## Step 3. Write `cluster`: find two populations in ten dimensions without labels.

```python starter
import numpy as np

# From steps 1 and 2:
def gauss(x, mu, var):
    return np.exp(-(x - mu)**2/(2*var))/np.sqrt(2*np.pi*var)

def em_gmm_1d(x, mu, var, pi, iters=100):
    mu, var, pi = (np.array(a, dtype=float) for a in (mu, var, pi))
    lls = []
    for _ in range(iters):
        P = pi*gauss(x[:, None], mu, var)
        lls.append(np.sum(np.log(P.sum(axis=1))))
        g = P/P.sum(axis=1, keepdims=True)
        Nk = g.sum(axis=0)
        mu = (g*x[:, None]).sum(axis=0)/Nk
        var = (g*(x[:, None] - mu)**2).sum(axis=0)/Nk
        pi = Nk/len(x)
    return mu, var, pi, lls

def pca(X, M):
    mean = X.mean(axis=0)
    S = (X - mean).T @ (X - mean)/len(X)
    lam, U = np.linalg.eigh(S)
    o = np.argsort(lam)[::-1]
    lam, U = lam[o], U[:, o]
    return mean, U[:, :M].T, lam

def cluster(X):
    # X is N x D with two clusters but no labels. Project onto the first principal
    # component, fit a two-component mixture with em_gmm_1d (start the means at the
    # 25th and 75th percentiles of the projections), and return an array of 0/1
    # labels: 1 where the second component's responsibility is larger.
    return np.zeros(len(X), dtype=int)

rng = np.random.default_rng(1)
print(cluster(rng.standard_normal((10, 4)))[:10])
```

```python solution
import numpy as np

# From steps 1 and 2:
def gauss(x, mu, var):
    return np.exp(-(x - mu)**2/(2*var))/np.sqrt(2*np.pi*var)

def em_gmm_1d(x, mu, var, pi, iters=100):
    mu, var, pi = (np.array(a, dtype=float) for a in (mu, var, pi))
    lls = []
    for _ in range(iters):
        P = pi*gauss(x[:, None], mu, var)
        lls.append(np.sum(np.log(P.sum(axis=1))))
        g = P/P.sum(axis=1, keepdims=True)
        Nk = g.sum(axis=0)
        mu = (g*x[:, None]).sum(axis=0)/Nk
        var = (g*(x[:, None] - mu)**2).sum(axis=0)/Nk
        pi = Nk/len(x)
    return mu, var, pi, lls

def pca(X, M):
    mean = X.mean(axis=0)
    S = (X - mean).T @ (X - mean)/len(X)
    lam, U = np.linalg.eigh(S)
    o = np.argsort(lam)[::-1]
    lam, U = lam[o], U[:, o]
    return mean, U[:, :M].T, lam

def cluster(X):
    mean, comps, lam = pca(X, 1)
    p = (X - mean) @ comps[0]
    v = np.var(p)
    mu, var, pi, _ = em_gmm_1d(p, np.percentile(p, [25, 75]), [v, v], [0.5, 0.5])
    P = pi*gauss(p[:, None], mu, var)
    return (P[:, 1] > P[:, 0]).astype(int)

rng = np.random.default_rng(1)
print(cluster(rng.standard_normal((10, 4)))[:10])
```

```python tests
rng = np.random.default_rng(42)
u = rng.standard_normal(10); u /= np.linalg.norm(u)
lab = (rng.random(400) < 0.4).astype(int)
X = rng.standard_normal((400, 10)) + np.outer(np.where(lab == 1, 3.0, -3.0), u) + 2.0
y = cluster(X)
assert y.shape == (400,) and set(np.unique(y)) <= {0, 1}, "cluster should return 400 labels, each 0 or 1."
acc = max(np.mean(y == lab), np.mean(y != lab))
assert acc >= 0.98, f"Two clusters 6 standard deviations apart in 10 dimensions should be separated almost perfectly; your labels agree with the truth {100*acc:.1f}% of the time."
```

::: right
Right. One principal component and a two-component mixture separate the populations, with no labels needed.
:::
:::

::: explain
## Why reduce the data with PCA before clustering, instead of fitting a mixture in all ten dimensions?

::: model
A full-covariance Gaussian mixture in ten dimensions needs ten means and 55 covariance entries per component, and with a few hundred points those estimates are noisy and EM can wander into poor local maxima. Here the two populations differ along a single direction, and that direction carries far more variance than any other, so the first principal component captures nearly all the information that separates them. Projecting onto it reduces the problem to fitting five numbers in one dimension, where EM is fast and reliable. The risk is that PCA keeps directions of high variance, which aren't always the directions that separate clusters, so it works when the cluster separation dominates the spread, as it does here.
:::
:::

::: practice

::: check
given: a = -2 | 0; b = 2 | 4; P = 0.2 | 0.7; x = 0 | 1.5
answer: P*exp(-(x - a)^2/2)/(P*exp(-(x - a)^2/2) + (1 - P)*exp(-(x - b)^2/2))
tolerance: 0.5%

## Responsibility: unit-variance components at {a} and {b}, weight {P}, point {x}?

::: misses
- [any] $\pi_1\mathcal{N}_1/\sum\pi\mathcal{N}$.
:::
:::

::: check
given: p = 5 | 12; q = 1 | 3; r = 0.2 | 0.8
answer: q + r
tolerance: 0.5%

## Reconstruction error keeping one component: eigenvalues {p}, {q}, {r}?

::: misses
- [any] Sum of the discarded eigenvalues.
:::
:::

::: check
given: d = 2 | 8; f = 0.3 | 0.5; s = 0.5 | 2
answer: f*(1 - f)*d^2 + s^2
tolerance: 0.5%

## Two clusters with centers {d} apart, a fraction {f} in one, noise σ = {s}: variance along the line joining the centers?

::: misses
- [any] $f(1 - f)d^2 + \sigma^2$.
:::
:::
:::
