Introduction to Machine Learning · Tuesday, October 27
PCA and the SVD, Gaussian mixtures and EM, autoencoders, t-SNE and UMAP, hierarchical clustering.
In pairs, signed in, scored live. The teaching assistants run the room today. Answers close at 12:20 pm.
The full decks, to read alongside: PCA and the SVD (Part 1), Gaussian mixtures and EM (Part 2), autoencoders, t-SNE, UMAP and clustering (Parts 3 and 4). Each opens in a new tab.
Part 1 of 4
How do we find the directions, and how many numbers does a point need?
The full deck: PCA and the SVD
The next slide is the interactive picture behind steps 2 and 4. Problem 1 comes right after it.
Each point is one day: the temperatures of Beirut and Damascus, centered. Pythagoras holds for every day (for a unit vector \(v\), the length along the line is \(v^\top x\)). Averaged over the days, the left side is fixed, 103.8 °C² (the total variance), so the line with the most variance along it is the line with the smallest mean squared distance to it. Along \(v_1\) that mean squared distance is 1.7 °C²: a typical distance of 1.3 °C, its square root.
What you are given
For a unit vector \(v\), \(\lambda = v^\top \Sigma v\) is the variance of the data along \(v\).
What you are asked
\(U^\top U = I\) and \(V^\top V = I\): orthonormal columns
\(\Xi\) (capital xi) holds the singular values \(\sigma_1 \ge \sigma_2 \ge \dots\) on its diagonal. The next slide reads each piece of the formula.
Vt), so \(v_1\) is the first row of Vt, Vt[0]. In the code, Xc is the centered \(X\).For the weather of 22 cities over 5,844 days, \(\sigma_1 = \) 2366, so \(\lambda_1 = \sigma_1^2/n = \) 957.8 °C², the largest eigenvalue. Forming \(X^\top X\) first loses digits of accuracy on a computer; the SVD works on \(X\) itself, which is why it is the standard route (Brunton and Kutz, 2022).
What you are given
What you are asked
import numpy as np, pandas as pd
df = pd.read_csv('levant_era5_daily_mean_temp_2010_2025.csv')
Xc = df.drop(columns='date').to_numpy(); Xc = Xc - Xc.mean(axis=0) # 5844 by 22, centred
U, s, Vt = np.linalg.svd(Xc, full_matrices=False) # economy: U is 5844 by 22, s has 22 values, Vt is 22 by 22
for k in [1, 2, 3, 22]:
Xk = (U[:, :k] * s[:k]) @ Vt[:k] # k columns of U, k singular values, k rows of Vt
print(k, round(((Xc - Xk)**2).sum()), round((s[k:]**2).sum())) # the two numbers agree
Eckart and Young (1936): among all matrices of rank \(k\), \(X_k = U_k \Xi_k V_k^\top\) is the closest to \(X\) in squared error, and the error left is \(\|X - X_k\|_F^2 = \sum_{j > k} \sigma_j^2\), where \(\|\cdot\|_F^2\) (F for Frobenius) is the sum of the squares of all entries. The PCA reconstruction with \(k\) components is exactly \(X_k\); dividing by \(n\) turns the dropped \(\sigma_j^2\) into the dropped eigenvalues. In the code, U[:, :k] * s[:k] multiplies column \(j\) of \(U\) by \(\sigma_j\): it is \(U_k \Xi_k\) without building the diagonal matrix. The three forms, in the shape of \(U\): full \(n \times n\), economy \(n \times d\) (full_matrices=False), truncated \(n \times k\).
Here \(n\) = 20,000 digits and \(d\) = 256 pixels, each from 0 (black) to 1 (white). The economy SVD has \(U\) of \(n \times d\) and \(\Xi\), \(V^\top\) of \(d \times d\). Each direction \(v_j\) has 256 entries, one per pixel, so it can be drawn as a 16 by 16 picture: an eigen-digit. These are MNIST digits (LeCun and colleagues, 1998), shrunk to 16 by 16 pixels.
Pixels are all in the same unit, so the digits are centered but not divided by their standard deviation; 14 border pixels are black on every digit, have no spread, and could not be divided by it anyway. The first direction keeps 11.3% of the variance, far less than the 95.5% of a day of weather (last lecture): a digit has more independent parts than a day.
the digit, 256 numbers
Here each \(v_j\) is an eigen-digit, a picture of 256 numbers, and \(z_j = v_j^\top (x - \mu)\) is one number: how much of eigen-digit \(j\) this digit contains.
\(\hat x = \mu + \sum_{j=1}^k z_j v_j\): the mean digit plus \(k\) eigen-digits, each weighted by this digit's own score: the reconstruction of the recap, with \(d = 256\). These 20 digits were held out from the reader that judges the rebuilt digits; the eigen-digits themselves were found from all 20,000.
Zeros gather at one end of \(z_1\) (their mean is +2.0) and ones at the other (−2.0); the other eight digits overlap in the middle, every mean within 0.4 of zero. Two numbers are enough to see some structure and too few to separate ten digits.
PCA keeps the directions of largest spread, which is not the same as the directions that separate classes. Methods that bend the map, such as t-SNE and UMAP, come with autoencoders.
What you are given
What you are asked
What you are given
What you are asked
What you are given
What you are asked
Part 2 of 4
What if every point belongs to every cluster, a little?
The full deck: Gaussian mixtures and EM
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.
What you are given
What you are asked
Dataset
| \(x_1\) | \(x_2\) |
|---|---|
| -0.5 | -0.4 |
| 0.6 | 0.1 |
| -0.7 | 0.8 |
| … | … |
How to find \(\mu_1, \mu_2, \Sigma_1, \Sigma_2\)?
Dataset
| \(x\) |
|---|
| 181 |
| 186 |
| 195 |
| 193 |
| … |
Assume:
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.
\(\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.
What you are given
What you are asked
Observations: \(x^{(i)} \in \mathbb{R}\). Number of clusters: \(k > 0\).
The hidden cluster of point \(i\): \(z^{(i)} \in \{1, \dots, k\}\).
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.
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.
What you are given
What you are asked
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.
What you are given
| component \(j\) | 1 | 2 | 3 |
|---|---|---|---|
| \(\phi_j\, \mathcal{N}(x; \mu_j, \Sigma_j)\) | 0.004 | 0.012 | 0.002 |
What you are asked
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
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, which tilts the ellipses.
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.
What you are given
| point \(i\) | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| \(x^{(i)}\) | 0 | 1 | 4 | 5 |
| \(w_1^{(i)}\), cluster 1 | 0.9 | 0.8 | 0.2 | 0.1 |
| \(w_2^{(i)} = 1 - w_1^{(i)}\) | 0.1 | 0.2 | 0.8 | 0.9 |
What you are asked
From this start \(\ell\) climbs from −1069 to −822.0 (dashed) in 46 iterations, never falling; from k-means' clusters it takes 39.
What you are given
\(\ell\) is the log-likelihood: how probable the data are under the current mixture. Higher is better.
What you are asked
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.
What you are given
What you are asked
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.
Part 3 of 4
What if the data lie near a curved surface, not a flat one?
The full deck: autoencoders, t-SNE and UMAP
The PCA slides rebuilt each digit from the mean digit plus \(k\) eigen-digits. To judge them, a reader (a 3-nearest-neighbour classifier: it names a digit by the majority label of the 3 closest training digits) reads the rebuilt pictures. A reader that recognises 96.6% of the real held-out digits recognises 34% of them rebuilt from 2 numbers, 82% from 10, and 95% from 30, where the components keep 81% of the variance.
The split: 16,000 digits to fit, and every fifth digit (4,000 in all) held out to test.
digit A
halfway
digit B
The picture halfway, \((1-t)\,x_A + t\,x_B\), is a point on the straight line between two digits in the space of 256 pixels. It is two faint strokes, not a digit: the straight line leaves the set of digits.
PCA represents every digit as a point of a flat sheet through the mean, \(\mu + z_1 v_1 + \dots + z_k v_k\). If the digits lie near a curved surface, a flat sheet has to be wide (many \(k\)) to pass close to all of it.
That the data lie near a surface of far fewer dimensions than the space, curved rather than flat, is called the manifold hypothesis. Moving a stroke a little, thickening it, slanting it: each is one direction along the surface, and none is a straight line in pixels.
The target is the input itself, so no labels are needed. The simplest version is one layer each: the encoder is a matrix \(\mathbf{W}_1\) followed by an activation function, the decoder a matrix \(\mathbf{W}_2\) followed by an activation. Here each is a small network (its weights are the \(\phi\) and \(\theta\) of the formula above), as in the architectures deck.
This deck's network: 256 pixels, then 256 and 128 units with ReLU, then \(k\) numbers; the decoder mirrors it and ends in a sigmoid, so pixels stay between 0 and 1. For \(k = 2\) it has 198,146 weights, trained for 60 passes over the 16,000 training digits. The error is reported per pixel: \(\mathcal{L}\) divided by 256.
What you are given
Linear(256, 64), ReLU, Linear(64, 16). Decoder: Linear(16, 64), ReLU, Linear(64, 256). It is trained to make its output \(\hat x\) close to its input \(x\), measured by the squared error.Linear(n_in, n_out) has \(n_{out} \times n_{in}\) weights and \(n_{out}\) biases.What you are asked
Its error falls to PCA's and stops there. The best rank-\(k\) map is the truncated SVD (Eckart and Young), and a linear network can do no better (Baldi and Hornik, 1989).
Same plane, different axes: the columns are not the eigen-digits and come in no order of variance. Replacing \(W_1\) by \(A W_1\) and \(W_2\) by \(W_2 A^{-1}\), for any invertible \(A\), gives the same output.
the digit
PCA
autoencoder
| all 4,000 held-out digits | PCA | autoencoder |
|---|---|---|
| error per pixel | ||
| read correctly |
At every \(k\) the network loses less: at \(k = 2\) its error is 34% below PCA's, at \(k = 8\) 56% below. These are the 20 held-out digits of the PCA slides: the first two of each kind.
The similarity between two data points \(x_i\) and \(x_j\) is a conditional probability
Then a joint distribution is created by the mean, \(P(x_i, x_j) = \big[P(x_i \mid x_j) + P(x_j \mid x_i)\big] / 2n\). Each \(\sigma_i\) is set so that point \(i\) has about as many effective neighbours as the perplexity.
The "distance" between them is minimised by gradient descent
In two dimensions, the joint distribution of the map points \(y_i\) is
which is a Student's t-distribution with one degree of freedom. Its heavy tails let moderately distant points sit far apart on the map, which opens gaps between groups.
The Kullback-Leibler divergence is often used to measure how far one distribution is from another. It is large when close pairs (large \(P_{ij}\)) are placed far apart, and nearly indifferent to where far pairs go (van der Maaten and Hinton, 2008).
UMAP keeps neighbours about as well as t-SNE, runs faster, and with more neighbours keeps more of the large-scale arrangement (McInnes, Healy and Melville, 2018). Like t-SNE it gives a map, not a way to draw a digit.
What you are given
What you are asked
Wattenberg, Viégas and Johnson, How to use t-SNE effectively (Distill, 2016), shows each of these on small examples you can change.
Part 4 of 4
Can one method cluster at every scale at once?
The full deck: hierarchical clustering, in the autoencoders deck
Merge the two closest clusters, again and again. A cut at any height is a clustering: the number of clusters is read off the tree, not chosen first.
Agglomerative: bottom up
Divisive: top down
Start with one cluster and split it, for example by 2-means, then split each part, and so on. Divisive methods see the whole data at the first split but are rarely used: there are far more ways to split a cluster than to merge two.
A hierarchy is a description at every scale at once: cats and dogs at the top; cats with big ears or calm behaviour, dogs small or big below. Read from the top, the tree is divisive; built from the leaves, agglomerative. Biologists' trees of species are a familiar example.
What you are given
What you are asked
\(A\) and \(B\) are the two clusters being compared: \(|A|\) is the number of points in \(A\), \(\mu_A\) is the mean of its points, and \(a\), \(b\) stand for points of \(A\) and \(B\). Single linkage uses the closest pair, complete the farthest pair, average the mean distance over all pairs, and Ward the merge that raises the k-means distortion \(J\) the least.
Ward merges the pair that raises the k-means distortion \(J\), the sum of squared distances to the cluster means, the least. At three clusters its \(J\) is 201.6, above k-means' 186.9: a greedy merge is never undone. Single linkage chains: one bird close to the next joins clusters through a bridge, and all but two birds end in one cluster. For comparison, k-means puts 317 of 342 birds with their species and the Gaussian mixture 330.
The full decks, for reference: PCA and the SVD, Gaussian mixtures and EM, autoencoders, maps and clustering.