Introduction to Machine Learning

Why are there so many
neural networks?

One recipe for learning, and many assumptions about the data.

Six questions for today

  1. 1One recipeWhat is an architecture?
  2. 2ImagesWhat do images share, and how can a layer build it in?
  3. 3SequencesHow can a network remember?
  4. 4Without labelsWhat can a network learn from the data alone?
  5. 5RelationsWhat if any part may matter to any other?
  6. 6The mapWhich assumption for which data?

Three kinds of real data come back all session: the 20,000 handwritten digits of last lecture, Beirut's daily temperature since 2010, and one digit, a 4 from the held-out set, that we follow through every network.

Last lecture's network, two pixels later256 inputs, 32 hidden units, 10 outputs, trained on 16,000 digits. Move the 2,000 held-out digits.

Held-out digits it reads correctly

...
where they were drawn
...
moved
Why it breaks A fully connected layer gives every pixel its own weight. Nothing in it says that two pixels are neighbours, so the same stroke one pixel over meets different weights: a shifted digit is new data.

We could show it shifted copies of every digit. Or we could build the fact that a stroke is a stroke anywhere into the function itself. That second move is what an architecture is.

A network is a composition of functionsAny differentiable pieces, in any arrangement, are trained by the same backward pass

\( f(x) = f_L\big(\cdots f_2\big(f_1(x;\, \theta_1);\, \theta_2\big)\cdots;\, \theta_L\big) \)

Backpropagation does not care what the pieces are. It needs the derivative of each one, and the chain rule does the rest. So inventing an architecture means choosing pieces and how they connect, not inventing a new way to train.

An architecture is an assumption about the dataBuild in the structure you know; let gradient descent find the rest

1. AskWhat structure does this kind of data have?
2. Build it inChoose pieces that cannot ignore that structure.
3. Let it learnGradient descent finds every number the structure leaves open.

A right assumption is information the network gets for free, so it needs less data. A wrong one is a cage no amount of data opens. The name for it is inductive bias.

Part 2 of 6

Images

What do images share, and how can a layer build it in?

From one hidden unit to a detectorTwo facts about images, applied to a real unit of last lecture's network

The first fact is locality, the second is translation. Built in together, they are a convolutional layer: many small sets of weights like this one, each slid over the whole image.

A convolution, by handA 3 by 3 kernel slid over our 4. Pick a kernel, point at the digit, move it.

our 4, moved
the kernel \(K\)
the feature map \(K * X\)
\( (K * X)_{ij} = \sum_{a,b} K_{ab}\, X_{i+a,\, j+b} \)
the outlined window: each weight times the pixel under it

Move the digit and the map moves with it, otherwise unchanged. Shift in, shift out: the layer is equivariant to translation, because the same 9 weights are used everywhere.

From moving with the digit to not caring where it isPooling, then an average over the whole image, turns maps that move into numbers that stay

Two stepsMax pooling keeps the largest value in each 2 by 2 block, so a feature that moves inside its block goes unnoticed. The last layer averages each map over the whole image: how much a feature fired still counts, where it fired no longer does.

What the layers seeA digit through the whole network: three convolutions, two poolings, one average, one dense layer. Pick another digit.

The first layer finds strokes and edges. The second combines them on a coarser grid, the third combines those. Each layer sees more of the image than the last: one cell of the third layer depends on an 18 by 18 window, more than the whole digit. That is the feature hierarchy, and nobody designed its features.

The same hierarchy in a large network: Zeiler and Fergus, ECCV 2014, arXiv:1311.2901. Notes: Stanford CS231n.

The two-pixel shift, againBoth networks on the 2,000 held-out digits, for every shift up to three pixels in each direction. Click a square.

Vertical shifts hurt both more than horizontal ones: these digits nearly fill the height of the frame, so moving them up or down pushes ink off the edge. And the convolutional network has 14,378 weights against 8,554: the saving is not in the total, it is that each weight is reused at every position.

What a convolution does not knowRotate the held-out digits instead of moving them

The limitTranslation was built in; rotation was not. A network knows what it was built to know or shown, nothing else. The fixes are the two from before: show it rotated digits (data augmentation), or build rotation into the layer, as group-equivariant convolutions do.

And at 180 degrees a 6 is a 9. Some invariances would be wrong: choosing the bias is a decision about the data, not a free upgrade.

Cohen and Welling, Group equivariant convolutional networks, ICML 2016, arXiv:1602.07576.

Part 3 of 6

Sequences

How can a network remember?

Beirut, one day at a timeDaily mean temperature, 2010 to 2025. The task: tomorrow, from the last 30 days.

Loading the temperatures...

A fully connected network could read the 30 days as 30 separate inputs, as the linear model does. It would not know that day 29 comes after day 28, and it could not read 31 days without new weights. A sequence has an order, and no fixed length.

Data: ERA5 reanalysis through the Open-Meteo archive API (CC BY 4.0), the grid cell at Beirut; trained on 2010 to 2021, tested on 2022 to 2025.

A recurrent network: one cell, reused at every stepThe hidden state \(h_t\) is the network's memory of everything it has read

\( h_t = \tanh\!\big( W_h\, h_{t-1} + W_x\, x_t + b \big) \)
\( \hat y = w_y^\top h_T + c \)

\(x_t\) is the temperature on day \(t\). The same \(W_h, W_x, b\) are used on every day.

A convolution shares its weights across space; a recurrent network shares them across time. Unrolled over 30 days it is a 30-layer network in which every layer is the same, so it reads a sequence of any length.

Elman, Finding structure in time, Cognitive Science 14(2), 179 to 211, 1990. doi:10.1207/s15516709cog1402_1

Watch it readA recurrent network with 8 hidden units, trained on 2010 to 2021, reading 30 days of the test years. Pick the day.

Why it forgets: vanishing gradientsIf day \(T-k\) had been different, how much would today's hidden state change?

\( \dfrac{\partial h_T}{\partial h_{T-k}} = \prod_{s=T-k+1}^{T} \operatorname{diag}\!\big(1 - h_s^2\big)\, W_h \)

A product of \(k\) matrices: if they shrink vectors, it vanishes; if they stretch them, it explodes. Gradient descent cannot learn to use day \(T-30\) when its gradient has all but disappeared.

Bengio, Simard and Frasconi, Learning long-term dependencies with gradient descent is difficult, IEEE Transactions on Neural Networks 5(2), 157 to 166, 1994. doi:10.1109/72.279181

The LSTM: a gate that lets memory throughA second state \(c_t\), the cell, updated by addition and guarded by learned gates

\( c_t = f_t \odot c_{t-1} + i_t \odot g_t \)
\( h_t = o_t \odot \tanh(c_t) \)

The forget gate \(f_t\), input gate \(i_t\) and output gate \(o_t\) are sigmoids of \(h_{t-1}\) and \(x_t\), numbers between 0 and 1; \(g_t\) is the new content. Along the cell the gradient is multiplied only by \(f_t\). Where the network learns \(f_t \approx 1\), memory and gradient pass through many steps.

Hochreiter and Schmidhuber, Long short-term memory, Neural Computation 9(8), 1735 to 1780, 1997. doi:10.1162/neco.1997.9.8.1735

Did memory help?Error on 2022 to 2025 in degrees Celsius, and how far back each model looks

Barely.

Part 4 of 6

Without labels

What can a network learn from the data alone?

An autoencoder: copy the input through a bottleneckNo labels: the target is the input itself

\( z = f_\phi(x) \in \mathbb{R}^d, \qquad \hat x = g_\theta(z) \)
\( \mathcal{L} = \lVert x - \hat x \rVert^2 \)

To push 256 pixels through \(d = 2\) numbers and back, the encoder \(f\) must keep what varies between digits and drop what does not. The assumption built in: the data lie near a surface of far fewer dimensions than the space of all images.

Hinton and Salakhutdinov, Reducing the dimensionality of data with neural networks, Science 313(5786), 504 to 507, 2006. doi:10.1126/science.1127647

Two numbers per digitThe 2,000 held-out digits at their codes \(z\). Colours are the labels, which training never saw. Point anywhere to decode.

Digits of the same kind gather although nobody said which was which. Between two clusters the decoder draws something in between, a 4 on its way to a 9: the code space is continuous, and every point in it is a drawing.

How much does the bottleneck lose?Eight held-out digits through a bottleneck of \(d\) numbers: the autoencoder against PCA, the best linear compression

Kingma and Welling, Auto-encoding variational Bayes, 2013, arXiv:1312.6114.

A GAN: two networks in a gameOne draws, one judges, and each trains against the other

\( \min_G \max_D \;\; \mathbb{E}_{x \sim \text{data}} \big[ \log D(x) \big] + \mathbb{E}_{z} \big[ \log\big(1 - D(G(z))\big) \big] \)

The discriminator \(D\) is a classifier, trained to tell real from generated. The generator \(G\) turns random numbers \(z\) into samples, and is trained through \(D\)'s gradient to make \(D\) call them real. Neither ever sees a formula for the data. The assumption is in the training, not in a layer: plausible means whatever a learned critic cannot tell from the data.

Goodfellow, Pouget-Abadie, Mirza, Xu, Warde-Farley, Ozair, Courville and Bengio, Generative adversarial nets, NeurIPS 2014, arXiv:1406.2661.

A GAN learns Beirut's weatherDaily highs, 2015 to 2025. A generator with 2 random inputs against a discriminator, both trained here, now.

real daysgenerated\(D(x)\): probability real

Watch the generator chase the two peaks, and the discriminator's curve rise wherever real days outnumber generated ones. It rarely settles: each player's improvement changes the other's problem, so the game oscillates instead of descending a fixed loss.

A GAN on digits, and what it leaves outA small convolutional GAN trained on the 16,000 digits. Our convolutional network reads 2,000 of its samples.

Radford, Metz and Chintala, Unsupervised representation learning with deep convolutional generative adversarial networks, 2015, arXiv:1511.06434.

Part 5 of 6

Relations

What if any part may matter to any other?

Attention: a learned lookupEvery token asks a question; every token offers a key and an answer

\( q_i = W_Q x_i, \quad k_j = W_K x_j, \quad v_j = W_V x_j \)
\( \alpha_{ij} = \operatorname{softmax}_j\!\big( q_i^\top k_j / \sqrt{d} \big) \)
\( y_i = \sum_j \alpha_{ij}\, v_j \)

A dictionary returns the value whose key matches exactly. Attention returns a blend of all the values, weighted by how well each key matches the query. The weights \(\alpha_{ij}\) are computed from the input, afresh for every input: the network decides which parts relate.

Here the tokens are the 16 patches of our 4, each 4 by 4 pixels. The lines show how much one patch draws from every other in a trained network.

Where the patches lookA small transformer reads 16 patches plus one summary token, and classifies the digit from the summary. Click a patch.

Nothing about neighbours was built in: patch 1 can attend to patch 16 as easily as to patch 2, and position is only a learned vector added to each patch. Whatever structure you see, the network found in the data.

Why attention took overVaswani and colleagues, Attention is all you need, 2017

Any distance, one stepIn a recurrent network word 1 reaches word 50 through 49 steps of the same cell, and its gradient shrinks at each. In attention it is one step away, like every other word.
All positions at onceA recurrent network must finish step \(t\) before step \(t+1\). Attention computes every position in parallel, which is what graphics cards do best.
A weak assumptionIt assumes little about its input, so the same block reads words, image patches, sound and proteins, and keeps improving with more data.

The price: \(n\) tokens make \(n^2\) pairs, and an assumption you did not build in has to be learned from data.

Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser and Polosukhin, Attention is all you need, NeurIPS 2017, arXiv:1706.03762.

An assumption is worth dataOur three digit readers, each trained on 250 to 16,000 digits and tested on the same 2,000

On 14 million to 300 million images the order flips: the vision transformer matched or beat the best convolutional networks only after training at that scale. With little data, build in what you know. With a great deal, assume less.

Dosovitskiy et al., An image is worth 16x16 words: transformers for image recognition at scale, ICLR 2021, arXiv:2010.11929.

Part 6 of 6

The map

Which assumption for which data?

The mapThe structure of the data, how an architecture builds it in, and what it did on our data today

DataStructure it hasBuilt in byArchitectureToday, on real data
Any list of numbersnone assumeda weight for every input of every unitFully connected96.5% of held-out digits; 32.8% moved 2 pixels right
Imagesnearby pixels belong together; a stroke is a stroke anywheresmall kernels shared across positions; poolingConvolutional97.4%; 94.8% moved 2 pixels right; 38.1% rotated 45°
Sequencesorder; the past shapes the presentone cell reused at every step; gates on a memoryRecurrent, LSTM1.38 and 1.35 °C, against 1.46 °C for tomorrow equals today
Data without labelsthe data lie near a surface of few dimensionsa bottleneckAutoencodererror 0.035 per pixel at d = 2, PCA 0.045
Examples to imitatea new sample should be impossible to tell from a real onea critic network trained against the generatorGANafter 30 epochs: 305 sevens, 150 fours in 2,000
Parts that relateany part may matter to any otherattention over all pairsTransformer96% from 16,000 digits; 50% moved up to 2 pixels (convolutional: 80%)
Things and linkslisting them in another order changes nothingmessages along the linksGraph networknot run today: see the weather lecture

In every row the recipe is the same: a composition of differentiable pieces, a loss, and gradient descent. Only the assumption changes.

What to take away

  1. A network is a composition of differentiable functions. Backpropagation trains any composition, so a new architecture is a choice of pieces, not a new way to learn.
  2. An architecture is an assumption about the data, an inductive bias. A right one saves data; a wrong one cannot be learned away.
  3. Images: a convolution slides one small kernel over the whole image, building in locality and translation, and pooling with a global average makes the output nearly ignore where the digit is. Moved 2 pixels right, our digits fell from 96.5% to 32.8% for the fully connected network and stayed at 94.8% for the convolutional one. Rotation was not built in: at 45 degrees both fail.
  4. Sequences: a recurrent network reuses one cell at every step and carries a hidden state. Its gradient through time is a product of matrices and vanishes; the LSTM's gated cell lets memory through. On Beirut's temperature memory buys about a tenth of a degree, because tomorrow is mostly in today.
  5. Without labels: an autoencoder squeezes the data through a bottleneck and draws a map of the digits that nobody labelled. A GAN learns to generate by playing against a critic, and over-produces whatever fools it.
  6. Attention lets every part weigh every other part, in one step and in parallel. It assumes the least, so it needs the most data: on centred digits it ties the convolutional network, on moved digits it falls far behind.

Reference: a convolutional layer works on volumesA 32 by 32 colour image, as in the land deck, is a block of numbers 3 deep: one sheet per colour

Every filter reaches through the full depth of its input. A layer with \(C_\text{out}\) filters of size \(k \times k\) on \(C_\text{in}\) maps has \(k \cdot k \cdot C_\text{in} \cdot C_\text{out} + C_\text{out}\) weights: here \(5 \cdot 5 \cdot 3 \cdot 6 + 6 = 456\), whatever the size of the image.

Reference: how big is the next map?A \(k\) by \(k\) kernel on an \(n\) by \(n\) input, padded with \(p\) zeros on each side, moved \(s\) cells at a time

\( n_\text{out} = \dfrac{n - k + 2p}{s} + 1 \)
input size \(n\) kernel \(k\) padding \(p\) stride \(s\) input maps \(C_\text{in}\) filters \(C_\text{out}\)

The drawing shows the first row of windows: grey cells are padding, outlined squares are where the kernel lands. A 2 by 2 max pooling with stride 2 is the same formula with \(k = 2, p = 0, s = 2\), and has no weights.

Reference: max pooling, by hand2 by 2 blocks, stride 2: each block becomes one number

one 4 by 4 map
max pooling: the largest of each block
average pooling: the mean of each block
What pooling does, and does not doEach map is pooled on its own, so the depth stays: 16 maps of 16 by 16 become 16 maps of 8 by 8. It has no weights to learn. It halves the size, so the next 3 by 3 kernel covers twice as much of the image, and a feature that moves by one pixel inside its block gives the same output.

Reference: our network, every shape and every weightThe convolutional network of this lecture, on a 16 by 16 digit

LayerOutput shapeWeightsOne cell sees
Input16 × 16 × 11 × 1
Convolution 1: 16 filters, 3 × 3, padding 1, ReLU16 × 16 × 163·3·1·16 + 16 = 1603 × 3
Max pooling, 2 × 28 × 8 × 1604 × 4
Convolution 2: 32 filters, 3 × 3, padding 1, ReLU8 × 8 × 323·3·16·32 + 32 = 4,6408 × 8
Max pooling, 2 × 24 × 4 × 32010 × 10
Convolution 3: 32 filters, 3 × 3, padding 1, ReLU4 × 4 × 323·3·32·32 + 32 = 9,24818 × 18
Average over each map320all
Dense, softmax1032·10 + 10 = 330
Total14,378
import torch.nn as nn

net = nn.Sequential(
    nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Conv2d(32, 32, 3, padding=1), nn.ReLU(),
    nn.AdaptiveAvgPool2d(1), nn.Flatten(),
    nn.Linear(32, 10),
)
print(sum(p.numel() for p in net.parameters()))
# 14378

Most weights sit in the deep layers, where many maps meet many maps. The fully connected network of last lecture has 8,554 weights, and they buy no shift invariance.

Explore further

Homework dare Pick a kind of data you care about: music, a city's traffic, a chess game, a protein. Write down what structure it has, and which pieces you would compose to build that structure in. Then look up what people actually use, and compare.