Autoencoders, maps and clusters
A held-out 7, drawn by a network from two numbers
A 16 by 16 digit is 256 numbers. Last week PCA needed 30 of them for a digit a reader still recognises. A network that bends where PCA can only tilt needs far fewer. How few, and what do the few numbers mean?
By the end you can
About 75 minutes. Parts 1 to 3 are for both courses; then Introduction to ML takes part 4, ML for Science part 5.
Unsupervised learning had a catalytic effect in reviving interest in deep learning, but has since been overshadowed by the successes of purely supervised learning. Although we have not focused on it in this Review, we expect unsupervised learning to become far more important in the longer term. Human and animal learning is largely unsupervised: we discover the structure of the world by observing it, not by being told the name of every object.
LeCun, Bengio and Hinton, Deep learning, Nature 521, 436 to 444, 2015, section "The future of deep learning". doi:10.1038/nature14539
Every method in this deck learns from data without labels: digits, penguins, weather. Labels come back only to check what a method found: the colours on a map, or a reader that says which digit a reconstruction looks like.
The principal components deck rebuilt each digit from the mean digit plus \(k\) eigen-digits. 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.
Same split and reader as there (16,000 digits to fit, every fifth held out), so these are that deck's numbers.
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.
Define a nonlinear feature space, then perform PCA in it
A straight line in \(\phi(x)\) is a curve in \(x\). PCA needs only inner products \(\phi(x)^\top \phi(x')\), which a kernel gives directly, here \(\kappa(x, x') = \exp(-\gamma \lVert x - x' \rVert^2)\).
On concentric circles (the F25 slide's scikit-learn example) it separates the two rings, which PCA cannot. On the digits it does not help: with \(\gamma = \) 0.01, a digit's 5 nearest neighbours on the kernel PCA map share its label 41% of the time, against 40% on PCA's. One fixed kernel bends every direction the same way; the digits need bends learned from them.
2,000 held-out digits on the first two kernel principal components, coloured by label
Independent component analysis (ICA)
The goal of ICA is to express the observed data \(X\) as a linear combination of statistically independent source signals \(S\), with a mixing matrix \(A\):
ICA looks for the unmixing matrix \(W\). Where PCA asks for uncorrelated directions ordered by variance, ICA asks for independent ones, which for sources with heavy tails (two signals mixed into two microphones) recovers the sources that PCA blurs together.
Factor analysis
A continuous latent variable model: each example is generated from an unobserved \(h_i\), plus an offset and Gaussian noise,
which gives \(p(x_i \mid h_i) = \mathcal{N}(W h_i + \mu, \Psi)\) and \(p(x) = \mathcal{N}(\mu, W W^\top + \Psi)\). It is generative, like the mixtures of the last deck; with \(\Psi = \sigma^2 I\) it becomes probabilistic PCA. An autoencoder replaces \(W h\) by a network.
Part 2 of 5
Can a network draw a digit from fewer numbers than PCA?
The target is the input itself, so no labels are needed. The F25 slide writes the encoder as \(\mathbf{W}_1\) followed by \(\sigma\) and the decoder as \(\mathbf{W}_2\) followed by \(\sigma\); here each is a small network with weights \(\phi\) and \(\theta\), 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.
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 20 digits are pca_svd's: the first two of each kind among the held-out digits.
Sixteen numbers. From 16 numbers the network's digits are read right 95.0% of the time, as often as PCA's from 30 (95.1%). With 8 numbers the network gets 92% and PCA 77%; with 2, 74% against 34%.
The reader, a 3-nearest-neighbour classifier on the 16,000 full training digits, recognises 96.6% of the real held-out digits, so no reconstruction can be expected to beat that line. Readability measures what a digit means; error per pixel measures every wobble of the pen.
run A: read right 74%
run B: read right 71%
Equal error (0.0289 and 0.0291 per pixel), different maps: after the best rotation and scaling, 13% of run A's spread is left. The code \(z\) is a latent variable, defined only up to a change of coordinates. In the 40% of run A's box with no held-out digit, the decoder draws something, often not a digit.
Each training digit gets Gaussian noise of standard deviation 0.5 on every pixel (clipped to 0 to 1); the loss compares the output with the clean digit. To remove the noise the network has to know what digits look like.
The error falls by a factor of six, but the reader does not gain: it already sees through the noise, and where the network cleans a digit into the wrong one it loses it. Lower error and more meaning are not the same thing.
The F25 slide showed the same idea on 28 by 28 MNIST with salt-and-pepper noise and a 2-number latent (encoder 500 and 300 units). Vincent and colleagues (2008) introduced denoising as a way to make the code capture structure rather than copy pixels.
Convolutional autoencoders
The encoder is a stack of convolutions and pooling that shrinks the picture (224 by 224 by 64, 112 by 112 by 128, down to 14 by 14 by 512 in the F25 example), the decoder a stack of transposed convolutions that grows it back. Direct connections from encoder to decoder keep detail; trained against a target mask instead of the input, the same shape outputs a saliency map. The CNN deck builds the encoder half.
An autoencoder on music
Najla Sadek's network reads 16 time steps of piano roll (16 by 88 = 1,408 keys), passes them through dense layers of 1,024, 512 and 256 to a latent of 128, and back to 1,408 sigmoid outputs; PCA of the 128 latent numbers then shows the pieces as clouds.
Variational autoencoders
The encoder \(q_\phi(z \mid x)\) outputs a mean \(\mu\) and a spread \(\sigma\); the latent code is sampled, \(z \sim \mathcal{N}(\mu, \sigma^2 I)\), and the decoder \(p_\theta(x \mid z)\) draws from it. The loss adds a term that keeps the codes close to \(\mathcal{N}(0, I)\):
Because the codes fill a known distribution, any sample from \(\mathcal{N}(0, I)\) decodes to something plausible: the holes of the last slide are closed, and compression becomes generation (Kingma and Welling, 2013).
Part 3 of 5
Which picture of the same digits tells the truth?
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).
On PCA's map the same neighbour test gives 40%. At every perplexity t-SNE puts most digits among their own kind, though it has only two numbers per digit, as PCA does.
The F25 slide showed the scikit-learn example: circles, an S-curve and a grid at perplexities 5, 30, 50 and 100. Small perplexities break one shape into many little clumps; large ones keep more of the global layout.
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.
Neighbours: share of digits whose 5 nearest map neighbours share their label. Trust: share of map neighbours that are true neighbours in pixels. Distances: rank correlation between pixel distances and map distances over all pairs.
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 5
Can we find groups without fixing their number or their shape?
Introduction to Machine Learning
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.
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.
A window on the penguins at \(\varepsilon = 0.35\), \(m = 10\): filled dots are core, rings border, crosses noise; dashed circles of radius \(\varepsilon\) around one of each.
Two numbers: a radius \(\varepsilon\) and a count \(m\).
A cluster is everything reachable from a core point through a chain of core points, each within \(\varepsilon\) of the next, plus their borders. The number of clusters comes out of the data; a cluster can have any shape; and outliers are labelled, not forced into a group. What DBSCAN cannot handle is clusters of very different densities: one \(\varepsilon\) is too small for one and too large for another.
At \(\varepsilon = 0.35\), \(m = 10\): 3 clusters, 281 birds with their species and 38 left as noise (18 Adelie, 12 Chinstrap, 8 Gentoo). At \(\varepsilon = 0.40\) a few birds bridge the Adelie and Gentoo crowds and two species become one cluster (139 Adelie, 29 Chinstrap, 118 Gentoo); the Chinstraps stay apart.
DBSCAN answers a different question from k-means: not which of three groups a bird belongs to, but which birds sit in a crowd at all.
In pixels. A digit's nearest other digit is typically 2.3 away, a random one only 5.2: neighbours are not much closer than strangers, so no radius separates crowds from gaps. With \(\varepsilon = 3\) DBSCAN finds 8 clusters and calls 28% of the digits noise, agreeing with the labels hardly at all (adjusted Rand index 0.07); with \(\varepsilon = 4\) everything is one cluster.
On the UMAP map. With \(\varepsilon = 0.3\), \(m = 10\), DBSCAN finds 10 clusters and 6% noise, adjusted Rand index 0.58. Some clusters hold more than one kind: the 3s share one with the 5s, and the 4s, 7s and 9s another.
Clustering the map works because UMAP has already pulled each digit's neighbours together. It also inherits the map's distortions: the gaps it cuts at are gaps in the layout, which part 3 showed are not distances.
The first merges join 4 with 9, then 3 with 5, then 7 with the 4 and 9, then 8 with the 3 and 5. The last merge separates 0 from the other nine digits.
The same groups share DBSCAN clusters on the UMAP map (last slide). The tree is built on averages, so it says which kinds of digit are alike, not which pictures are.
The F25 slide showed scikit-learn's comparison of eleven methods on six toy datasets: rings, moons, blobs of different sizes and spreads, and uniform noise. Each method wins somewhere and fails somewhere, and the penguins say the same.
The mixture's tilted ellipses fit these clusters best. Average linkage is close behind with no shape assumed. DBSCAN matches fewer birds but leaves its doubtful ones as noise, and single linkage, which merges along chains, fails on clusters that touch.
import numpy as np, pandas as pd
from itertools import permutations
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.cluster import DBSCAN
p = pd.read_csv('penguins.csv').dropna(subset=['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g'])
X = p[['bill_length_mm', 'bill_depth_mm']].to_numpy()
Z = (X - X.mean(0)) / X.std(0, ddof=1) # standardize, as in the k-means deck
species = pd.Categorical(p.species).codes # 0 Adelie, 1 Chinstrap, 2 Gentoo
def matched(c): # birds in the cluster matched to their species
M = [[np.sum((c == a) & (species == s)) for s in range(3)] for a in sorted(set(c) - {-1})]
return max(sum(M[a][s] for s, a in enumerate(rows)) for rows in permutations(range(len(M)), 3))
for method in ['ward', 'complete', 'average', 'single']:
print(method, matched(fcluster(linkage(Z, method), 3, 'maxclust')))
c = DBSCAN(eps=0.35, min_samples=10).fit_predict(Z)
print('DBSCAN', len(set(c)) - 1, 'clusters,', (c == -1).sum(), 'noise,', matched(c))
Expected: Ward 300, complete 302, average 323, single 149; DBSCAN 3 clusters, 38 noise, 281 matched.
Four ways to find structure without labels: k-means and mixtures choose \(k\) first, a dendrogram lets you cut afterwards, DBSCAN lets density decide and leaves outliers out, and an autoencoder finds a few numbers from which the data can be drawn again.
Part 5 of 5
Does a network compress the weather better than PCA?
ML for Science
The principal components deck found that one number per day, how warm the whole region is, keeps 95.5% of the variance of the 22 cities. Here PCA is fitted on the 4,383 days of 2010 to 2021 and tested on the 1,461 days of 2022 to 2025:
| numbers per day | PCA, rms error per city on the test days |
|---|---|
| 0 (the mean day) | 6.90 °C |
| 1 | 1.48 °C |
| 2 | 1.24 °C |
| 3 | 1.04 °C |
On the digits the network's error was 34% (\(k = 2\)) to 63% (\(k = 16\)) below PCA's. Will it be on the weather?
Your prediction, for one number per day
Every city is scaled by one number (6.70 °C), so the loss stays in degrees. Adam, learning rate 0.01, batches of 128 days, the same random start every time.
No. With width 16 the network's test error is within 3% of PCA's at one, two and three numbers (from 1.1% below to 2.4% above): one number gives 1.47 °C against PCA's 1.48 °C, two give 1.25 °C against 1.24 °C.
A nonlinear encoder pays only where the data are curved. The digits lie near a bent surface, and the network's error at \(k = 8\) is 56% below PCA's. A day of Levant weather is mostly one number, the warmth of the region, and the cities follow it nearly in a straight line: the flat sheet is already the right shape.
On the training days the network edges ahead (1.40 °C at \(k = 1\)), and on the test days that edge is gone. Before reaching for a network, ask whether your data are curved.
The network's one number is PCA's first number bent a little: correlation −1.000 for one run and +0.999 for another, whose test error is 1.48 °C. The sign and the scale are arbitrary, as on the digits; the meaning, how warm the region is, is the same.
A latent variable is a quantity the data never show directly but from which they can be rebuilt. Whether it means something physical is a question to ask of it, not something the network guarantees.
The encoder \(\varphi\) gives \(z(t) = \varphi(x(t))\), the decoder \(\psi\) draws \(x\) back, and in between \(\dot z = \Theta(z^\top)\Xi\) is a sparse law from a library of candidate terms, as in the SINDy deck. The time derivatives pass through the encoder by the chain rule, \(\dot z_i = \nabla_x \varphi(x_i)\, \dot x_i\) (Champion, Lusch, Kutz and Brunton, 2019).
From partial measurements, a delay SINDy autoencoder recovered a Lorenz-like system from one angular velocity of the Harvard Lorenz waterwheel, extracted from video (Bakarji, Champion, Kutz and Brunton, 2023). The DMD deck fits one linear map to the weather's anomalies; in a learned latent space the map, or the law, can be nonlinear.
This deck stops at the coordinates: it does not fit dynamics in the weather's latent space. Doing so, and checking the law against held-out years, is a project-sized question.
import numpy as np, pandas as pd
df = pd.read_csv('levant_era5_daily_mean_temp_2010_2025.csv', parse_dates=['date'])
X = df.drop(columns='date').to_numpy() # 5844 days by 22 cities, deg C
train = (df.date.dt.year <= 2021).to_numpy() # fit on 2010-2021, test on 2022-2025
mu = X[train].mean(axis=0)
Xc = X - mu # centre with the training mean
_, _, Vt = np.linalg.svd(Xc[train], full_matrices=False)
for k in [0, 1, 2, 3]:
R = Xc[~train] @ Vt[:k].T @ Vt[:k] # rank-k reconstruction of the test days
print(k, round(np.sqrt(((Xc[~train] - R)**2).mean()), 2))
Expected: 6.90 °C, 1.48 °C, 1.24 °C, 1.04 °C. The network of the last slides is in the deck's script (WX.train); scripts/verify_autoencoders.py runs a numpy twin of it and gets the numbers quoted.