Autoencoders, maps and clusters

How Few Numbers Does It Take to Draw a Digit?

A held-out 7, drawn by a network from two numbers

  • PCA, read right at 2 numbers34%
  • autoencoder, at 2 numbers74%
  • the digits themselves96.6%

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

  • train an autoencoder and compare it with PCA by error and by what a reader still recognises
  • say why a linear autoencoder finds PCA's plane, and what the nonlinear one adds
  • read a t-SNE or UMAP map of data for what it keeps (neighbours) and what it does not (sizes, distances)
  • (Intro to ML) cluster without choosing \(k\) first: dendrograms and DBSCAN
  • (ML for Science) test whether a network compresses the weather better than PCA

About 75 minutes. Parts 1 to 3 are for both courses; then Introduction to ML takes part 4, ML for Science part 5.

Five questionsParts 1 to 3 for everyone, then one part for each course

  1. 1PCA's answerHow many numbers does PCA need, and why can it not do with fewer?
  2. 2A network as the encoderCan a network draw a digit from fewer numbers than PCA?
  3. 3Maps of the digitsWhich picture of the same digits tells the truth?
  4. 4Clusters without choosing k (Intro to ML)Can we find groups without fixing their number or their shape?
  5. 5The weather through a bottleneck (ML for Science)Does a network compress the weather better than PCA?

Learning without being toldLeCun, Bengio and Hinton, in their 2015 review of deep learning

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.

PCA's answer: thirty numbersHeld-out digits rebuilt from \(k\) components, then read by a 3-nearest-neighbour reader

\[\hat x = \mu + \sum_{j=1}^{k} z_j\, v_j, \qquad z_j = v_j^\top (x - \mu)\]

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.

The digits lie on a curved surfaceBlend two digits of the same kind pixel by pixel. Pick a pair, then slide from one to the other.

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.

Kernel PCAExtension of PCA which achieves nonlinear dimensionality reduction through the use of kernels

Define a nonlinear feature space, then perform PCA in it

\[\phi(x) = \begin{bmatrix} x_1 & x_2 & x_1^2 & x_1 x_2 & \cdots \end{bmatrix}^\top\]

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

Two more linear models of the same matrixIndependent component analysis and factor analysis: other ways to write the data through a few hidden variables

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\):

\[X_i = \sum_j A_{ij} S_j, \qquad X = AS, \qquad S = WX\]

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,

\[x_i = W h_i + \mu + \epsilon, \quad \epsilon \sim \mathcal{N}(0, \Psi), \quad h \sim \mathcal{N}(0, I)\]

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

A network as the encoder

Can a network draw a digit from fewer numbers than PCA?

Neural networks: autoencodersAn encoder squeezes \(x\) into a low-dimensional latent representation \(z\); a decoder draws \(x\) back from it

\[z = f_\phi(x) \in \mathbb{R}^k, \qquad \hat x = g_\theta(z)\]\[\mathcal{L} = \frac{1}{n}\sum_{i=1}^n \big\lVert x^{(i)} - g_\theta\big(f_\phi(x^{(i)})\big) \big\rVert^2\]

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.

If \(\sigma = I\), the network performs the SVDA linear autoencoder (no activation) trained by gradient descent, against PCA

\[\hat x = \mu + W_2 W_1 (x - \mu), \qquad W_1 \in \mathbb{R}^{k \times d},\ W_2 \in \mathbb{R}^{d \times k}\]

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 same digit from \(k\) numbers, two waysPick a held-out digit, move \(k\). PCA's flat sheet against the network's bent one.

the digit

PCA

autoencoder

all 4,000 held-out digitsPCAautoencoder
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.

How few numbers?The share of held-out digits a reader recognises after the round trip through \(k\) numbers. Point at a \(k\).

The answer

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.

Two runs, two mapsThe same network trained twice, \(k = 2\). Point at a map to see what its decoder draws there.

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.

DenoisingNeural networks: autoencoders. Train on noisy digits, ask for the clean 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.

noisy digits, error per pixel0.116the plain network (\(k = 32\)) given them0.0727the denoising network (\(k = 32\))0.0178read correctly: noisy, then denoised86%, 83%

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 and variational autoencodersThe same bottleneck with an image-shaped encoder, or with a code that is a distribution

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)\):

\[\mathcal{L}(x; \theta, \phi) = \underbrace{-\mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x \mid z)\big]}_{\text{reconstruction loss}}\]\[\qquad + \underbrace{\tfrac{1}{2}\textstyle\sum_i \big(\mu_i^2 + \sigma_i^2 - \log \sigma_i^2 - 1\big)}_{\text{KL divergence 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

Maps of the digits

Which picture of the same digits tells the truth?

t-Distributed Stochastic Neighbor Embedding (t-SNE)Represents high-dimensional data in a lower-dimensional space while preserving the relationships between data points

The similarity between two data points \(x_i\) and \(x_j\) is a conditional probability

\[P(x_j \mid x_i) = \frac{\exp\!\big(-\lVert x_i - x_j\rVert^2 / 2\sigma_i^2\big)}{\sum_{k \ne i} \exp\!\big(-\lVert x_i - x_k\rVert^2 / 2\sigma_i^2\big)}\]

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

\[\mathrm{KL}(P \,\Vert\, Q) = \sum_{i \ne j} P_{ij} \log \frac{P_{ij}}{Q_{ij}}\]

In two dimensions, the joint distribution of the map points \(y_i\) is

\[Q(x_i, x_j) = \frac{\big(1 + \lVert y_i - y_j\rVert^2\big)^{-1}}{\sum_{k \ne l} \big(1 + \lVert y_k - y_l\rVert^2\big)^{-1}}\]

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).

t-SNE of the digits, and the perplexity2,000 held-out digits; t-SNE never sees the labels, which only colour the points. Change the perplexity.

a digit's 5 nearest map neighbours share its labeltrustworthiness (10 neighbours)

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.

UMAPUniform manifold approximation and projection: a graph of neighbours, laid out in two dimensions. Change the number of neighbours.

5 nearest map neighbours share the labeltrustworthiness (10 neighbours)
  1. For each point, connect its \(m\) nearest neighbours with weights that fall off with distance, scaled so every point has the same total.
  2. Symmetrise: two points are linked if either chose the other, \(w_{ij} + w_{ji} - w_{ij} w_{ji}\).
  3. Place points in two dimensions so that linked points sit close and unlinked points apart, minimising a cross-entropy between the two graphs.

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.

Which map lies?The same 2,000 held-out digits under five methods. Teams: defend one map, then find one place where it misleads.

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.

Where the maps misleadHow tightly each digit's points sit, relative to the average digit: in the 256 pixels, and on the t-SNE map

  • Sizes. In pixels the ones are the tightest digit (spread 0.74 of the average); on the t-SNE map they spread 0.93, and the tightest digit there is 0. t-SNE and UMAP even out the density of each cluster, so the size of a cluster says nothing.
  • Distances. No map keeps pixel distances well: the rank correlation is 0.52 for PCA, 0.41 for t-SNE and 0.42 for UMAP. The gap between two clusters is not their distance.
  • Drawing. t-SNE and UMAP give each digit a place but no way back to a picture, and t-SNE has no way to place a new digit without running again. Of these maps, only the autoencoder's comes with a decoder trained to draw.

Wattenberg, Viégas and Johnson, How to use t-SNE effectively (Distill, 2016), shows each of these on small examples you can change.

Two ways onEach course takes one part from here

Part 4 of 5

Clusters without choosing k

Can we find groups without fixing their number or their shape?

Introduction to Machine Learning

Hierarchical clustering: the dendrogramThirty penguins (the first ten of each species), standardized bills. Drag the red line.

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 and divisiveTwo directions through the same tree

Agglomerative: bottom up

  1. Start with \(n\) clusters, one point each.
  2. Merge the two clusters that are closest (by a linkage, next slide).
  3. Record the height of the merge; repeat until one cluster is left.

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's method, and other ways to join clustersAll 342 penguins, the tree cut at three clusters. Choose how the distance between two clusters is measured.

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.

DBSCAN: clusters are dense regionsDensity-based spatial clustering of applications with noise (Ester and colleagues, 1996)

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\).

  • Core point: at least \(m\) points (itself included) lie within \(\varepsilon\) of it.
  • Border point: not core, but within \(\varepsilon\) of a core point.
  • Noise: neither. DBSCAN leaves it in no cluster.

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.

DBSCAN on the penguinsStandardized bill length and depth. Move \(\varepsilon\) and \(m\); the clustering runs here, on all 342 birds.

clustersnoise (grey)birds in the cluster matched to their species

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.

Density in 256 dimensionsDBSCAN on the 2,000 held-out digits: in pixels, and on the UMAP map. Switch the colouring.

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.

A family tree of the ten digitsAverage linkage on the ten mean digits of the 16,000 training digits

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.

A zoo of clustering methodsThe 342 penguins under six methods: birds placed in the cluster that matches their species

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.

Hierarchical clustering and DBSCAN in codeCode: prints the numbers these slides quote

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.

End of the Introduction to ML pathPart 5 is for ML for Science; you are welcome to read it

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.

What to take away

Part 5 of 5

The weather through a bottleneck

Does a network compress the weather better than PCA?

ML for Science

Predict first22 cities, one day at a time, through \(k\) numbers and back. Fit on 2010 to 2021, test on 2022 to 2025.

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 dayPCA, rms error per city on the test days
0 (the mean day)6.90 °C
11.48 °C
21.24 °C
31.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

Train itA network 22, \(h\), \(k\), \(h\), 22 with tanh, trained here in your browser for 30 passes. The dashed lines are PCA.

\(k\)
width \(h\)
network, test daysPCA, test daysnetwork, training days

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.

Why the network cannot win hereThe network's rms test error as a share of PCA's at the same \(k\): digits against weather

The answer

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.

What the bottleneck number meansThe \(k = 1\) network's number through 2024 (two runs) against PCA's first number

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.

Discovering latent dynamicsAutoencoders plus system identification: learn the coordinates and the law in them together

\[\underbrace{\lVert x - \psi(z)\rVert_2^2}_{\text{reconstruction loss}} + \lambda_1 \underbrace{\big\lVert \dot x - (\nabla_z \psi(z))\,\Theta(z^\top)\Xi \big\rVert_2^2}_{\text{SINDy loss in } \dot x} + \lambda_2 \underbrace{\big\lVert (\nabla_x z)\,\dot x - \Theta(z^\top)\Xi \big\rVert_2^2}_{\text{SINDy loss in } \dot z} + \lambda_3 \underbrace{\lVert \Xi \rVert_1}_{\text{SINDy regularization}}\]

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.

PCA of the weather, fitted and testedCode: prints the PCA numbers the network is measured against

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.

Now your project's dataIn the iteration log: PCA and a small autoencoder, fitted on one part, tested on another

✏ exercise · do it now
  1. Split your data the way it will be used: by time for a time series, by site or by run otherwise.
  2. Fit PCA on the training part and report the test error for \(k = 1, 2, 3\).
  3. Train the smallest autoencoder that could beat it (one hidden layer, \(k\) the same) and report its test error next to PCA's.
  4. If the network wins, show where: which examples, which part of the space. If it does not, say what that tells you about the shape of your data.

What to take away

  1. An autoencoder is PCA with bent maps. With no activation it finds PCA's plane; with ReLU layers a digit drawn from 16 numbers is read right as often (95%) as PCA's from 30.
  2. Its numbers are a latent variable, defined only up to a change of coordinates: two runs give two maps of equal quality, and the space between the data decodes to things that are not digits.
  3. t-SNE and UMAP keep neighbours, not sizes or distances, and have no decoder. Read a map for who sits next to whom.
  4. A dendrogram lets you choose the number of clusters after the fact; DBSCAN lets density choose and leaves outliers out, and both fail where clusters touch or densities differ.
  5. A network pays only where the data are curved. On the Levant weather it does no better than PCA.