Computed: 10 noisy samples of a sine curve, after Bishop (2006), Fig. 1.4
Computed: the same curve and noise, after Bishop (2006), Fig. 1.6

Computed: the curve fit's 10 points, after Bishop (2006), Fig. 1.7

Computed: one monkey IT site (Bao et al. 2020), 1,224 object images, 512 late-layer units of ResNet-18; a random fifth held out
RidgeCV); on held-out images
Optional: a few research-trail entries over the semester. Any paper mentioned in any lecture qualifies.
Submit on Canvas → Minute papers → Minute Paper 11 (access code read out in class).
Write three brief points in your own words:
Credit for a thoughtful attempt, not for being correct.
Computed: the polynomial example; 20 fits shown, numbers from 2,000 training sets
Computed: 2,000 training sets


best_acc = -float("inf") # best validation accuracy so far
for epoch in range(num_epochs): # one epoch = one pass over the training set
model.train() # training mode (dropout on)
for X, y in train_loader: # one minibatch at a time
optimizer.zero_grad() # clear last step's gradients
loss_fn(model(X), y).backward() # loss on this batch, then backprop
optimizer.step() # update every weight
model.eval() # evaluation mode (dropout off)
with torch.no_grad(): # no gradients needed to score
correct = sum((model(X).argmax(1) == y).sum().item()
for X, y in val_loader) # count right answers
val_acc = correct / len(val_loader.dataset)
if val_acc > best_acc: # better than every earlier epoch?
best_acc = val_acc
torch.save(model.state_dict(), "best.pt") # save the weights: a checkpoint
model.load_state_dict(torch.load("best.pt")) # end: reload the best weights
- Last lecture ended with a network that learns by gradient descent, with the gradient from backpropagation and autograd - One step means one update of every weight, using the gradient of the loss averaged over the examples it was computed on. In last lecture's loop that was the whole training set, every time. That works for a few hundred examples, not for the million images a vision network is trained on - And a low training loss was the only goal. Today asks whether that is the right goal
- The three questions follow one network from training, to testing, to opening it up - The assignment due Sunday uses all three: a readout trained on minibatches with Adam and a weight penalty, its train and test accuracy, and tuning curves, Gabor fits and selectivity of AlexNet units and IT neurons
- Three examples recur through the lecture, so their details are given once, here. They are deliberately different models: a single linear neuron, a polynomial of one input, a readout of recorded IT responses. Learning rates, momentum, overfitting, splits and penalties apply to all three in the same way, and to deep networks: the last section looks inside AlexNet - The two-weight neuron: ŷ = w1 x1 + w2 x2, fit by squared error to 24 examples simulated from weights (1, −0.3) plus a little noise; the contour plot is its loss, from last lecture's slide "Learning the weights: start anywhere, walk downhill". Used for minibatches, the learning-rate schedule, momentum and Adam - The curve fit: y = sin(2πx) plus noise, 10 training points, polynomials of degree 0 to 9 (Bishop 2006). Used for underfitting, overfitting, early stopping and the weight penalty - The IT readout: trial-averaged responses of 100 randomly chosen IT sites to the 1,224 object images of Bao et al. (2020): 51 objects, 24 views each, in six categories (animal, vehicle, face, vegetable or fruit, house, man-made object). A readout names the category; chance is 1 in 6. Used for the learning rate, learning curves, the precision of a test accuracy and the weight penalty
- Bao, She, McGill & Tsao (2020) recorded neurons in macaque IT while the monkeys viewed 51 objects, each rendered from 24 viewpoints, 1,224 images in all. The first two assignments used these recordings - A site is one recording channel. Its response to an image is the firing rate averaged over the repeated presentations of that image - We keep 100 of the recorded sites, chosen at random once (seed 0), and use the same 100 throughout the lecture - The readout's task: from the 100 numbers an image evokes, name its category (animal, vehicle, face, vegetable or fruit, house, man-made object). Readouts differ only in how they map the 100 numbers to the category: a logistic regression (a weighted sum per category, then softmax) or a small network with one hidden layer
- Two changes make training on large data sets possible: compute each step from a small batch of examples, and shrink the step size as training goes - Then Adam, the optimizer the assignment uses, and a measurement of how much the learning rate matters
- Why one example gives a noisy gradient: the gradient of one example's loss points the way that fits that example best. Two images of cats may pull a weight in opposite directions (one is dark, one is light), and an image with an unusual label pulls it somewhere no other image would. The average over all examples is the direction that helps most of them; one example, or a few, give a noisy estimate of it - Three ways to compute a step's gradient. The perceptron and the delta rule updated after every example (online). Last lecture's loop averaged over every training example (full batch). Practice sits in between - Why not full batch: one update per pass through a million images is slow, and the activations of every image must be held at once to compute the gradient, far more than a graphics card's memory. Why not online: one image at a time wastes the graphics card, which processes a batch of images in parallel as fast as one, and each step follows a single example's noisy gradient - Why minibatches converge in fewer epochs: one pass through the data costs the same computation either way, since every example is processed once. Full batch spends that pass on a single update. Minibatches of B spend it on N/B updates: with 50,000 images and B = 50, a thousand small steps instead of one. Each step is noisier, but the many steps usually reach a low loss in a small fraction of the epochs - One step is also called an iteration or an update. With B = 1 the method is the original stochastic gradient descent; PyTorch's optim.SGD takes this step at any batch size - Does the noise of small batches help? Several studies found that small batches reach better test accuracy than very large ones (Keskar et al. 2017; Masters & Luschi 2018). Shallue et al. (2019) found that the difference largely disappears when the learning rate and other settings are tuned separately for each batch size. Small batches are at least as good, and often what fits in memory - In PyTorch: `train_set = TensorDataset(X_train, y_train)`, then `for xb, yb in DataLoader(train_set, batch_size=64, shuffle=True):` - This DataLoader loop goes inside the epoch loop, so one epoch is now many steps. The five lines of the training loop go inside the DataLoader loop, with xb and yb in place of X_train and y_train; the loss is the average over the batch - Parameters are what training learns (weights and biases). Hyperparameters are what we choose before training: the learning rate η, the batch size B, the number of epochs, the width and depth - The assignment trains its hidden-layer probe on minibatches of 64 images (32 when the network learns new objects) - Robbins & Monro (1951) showed that noisy gradient steps converge if the step size shrinks at the right rate, under assumptions about the loss and the noise. The next slide shows schedules that shrink it
- Minibatches make each step cheap but noisy. The next slides are three things practitioners do about that, each shown on a small problem where you can see it work - All three are a line or two of PyTorch: a scheduler, the choice of optimizer, and a loop over learning rates
- The neuron and data are last lecture's (the slide "Learning the weights: start anywhere, walk downhill"): 24 simulated examples made by a linear neuron with weights (1, −0.3) plus a little noise, and the mean squared error as the loss. The contours are that loss; the star is its lowest point, which sits almost exactly on the weights that made the data - Both runs start from the same random weights (off the plotted area, top left) and use the same sequence of minibatches, each 2 examples drawn at random. Only the step size differs: 0.8 throughout (left), or 0.8/(1 + t/20), which halves after 20 steps (right) - Each minibatch gradient points roughly toward the star but with noise, because two examples are a poor sample of 24. The size of a step is the learning rate times the gradient. With a constant learning rate, the last steps are as large as the first ones, so each noisy gradient still throws the weights a long way and they keep jumping around the lowest point: on average 0.12 from it over the last 300 steps. With a shrinking learning rate each jump gets smaller, and the weights settle within 0.01 of it - A network's loss has many regions where it is low and rises all around (valleys, in the picture of the loss as a landscape over the weights). The same idea applies: large noisy steps early move the weights far, small steps late let them settle in one of those regions
- What changed from the previous slide: the data are the same 24 examples, but the second input x2 is multiplied by 5, as if it were recorded in other units. The neuron fits the same outputs with w2 five times smaller, so the lowest loss moves from (1, −0.3) to about (1, −0.06). Nothing else changes; the axes are drawn on equal scales, as before - Why a valley: multiplying an input by 5 makes the loss 5 × 5 = 25 times steeper along its weight. Because the two inputs are also correlated, the loss rises about 50 times faster across the valley than along it. Inputs on very different scales make such valleys, which is one reason inputs are standardized before training - Why the zigzag: the gradient points straight downhill, across the contour lines, so here it points mostly across the valley. With one learning rate for both weights, a step that makes useful progress along the valley is far too large across it and lands on the other side, and the next step comes back - Both runs use the same learning rate, 0.089, the best for plain gradient descent; the only difference is the running average m (β = 0.9). The up-and-down pushes alternate in sign from step to step and largely cancel in the average; the pushes along the valley all agree and add up. Up-and-down travel over the 40 steps falls from 4.4 to 0.8 - Why momentum's path is still wavy: the fast zigzag flips sign every step, so an average over about 10 steps (β = 0.9) cancels it. The slow swing that remains is momentum's own inertia: the averaged velocity carries the weights past the valley floor before turning them back, like a ball rolling in a bowl with friction. A larger β means more inertia and longer, slower swings - Momentum works without Adam: plain gradient descent with momentum, torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9), is the classic recipe; the standard ResNet training on ImageNet uses exactly that - Full batches, so no minibatch noise: this isolates what the averaging does
- Adam = the running average of the gradient (m, momentum) + a separate scale for each weight (√v, the running size of that weight's gradient). The next slide writes the update - Here Adam uses the largest learning rate for which it does not overshoot the lowest loss along the valley (0.076), to show its path; up-and-down travel 0.6 - The step counts on the slide come from separate runs, each method at the learning rate that reaches 1% of the starting loss fastest: plain descent does not reach it within 40 steps (its rate must stay small or it blows up across the valley), momentum 8, Adam 6. At those fast rates momentum and Adam overshoot once before settling, which is why the figure shows gentler runs - Real network losses have such narrow valleys in many of their millions of directions, which is one reason Adam often needs fewer steps. It still needs a learning rate: two slides on
- Why m over √v works: if a weight's recent gradients all point the same way, m is about as large as √v and the step is about η. If they flip sign from step to step, m averages to near zero while v stays large, so the step is small. The ratio acts like a signal-to-noise ratio for each weight - The name: Adam stands for adaptive moment estimation, from the two running averages. m estimates the mean of the gradient (its first moment), v the mean of its square (its second moment) - Adam usually reaches a low loss in fewer steps than plain gradient descent, but it still needs a learning rate (the next slide) - A schedule changes the step size over time, the same for every weight. Adam changes it for each weight separately and smooths the noisy minibatch gradients. The assignment uses Adam in every training loop you write - ∇ℒ is the gradient of the loss on the current minibatch, one entry per weight. Plain stochastic gradient descent uses it directly, θ ← θ − η∇ℒ. Adam changes only what is done with it, in PyTorch the opt.step() line - Operations on vectors are element by element: (∇ℒ)² squares each weight's gradient, and the division is weight by weight - The update shown omits Adam's start-up correction. m and v start at zero, so they are too small during the first steps. Adam divides them by 1 − β₁ᵗ and 1 − β₂ᵗ, where t counts steps, which matters only early in training - Adam is cheap: two running averages per weight, and no second derivatives (how fast a slope itself changes), which some slower optimizers use - AdamW, Loshchilov & Hutter (2019), with a separate weight decay, is the usual choice for large language models - Adam is not always best. On some image datasets, well-tuned gradient descent with momentum generalizes as well or better, Wilson et al. (2017). Its advantage is that it works with little tuning
- The network: the 100 IT responses to an image go into a hidden layer of 64 units, each a weighted sum followed by a ReLU, then into 6 output units, one per category, with a softmax. Training lowers the cross-entropy between the softmax output and the true category, as in last lecture's training loop - Training set: 918 images; test set: the other 306. Minibatches of 32, 30 epochs, plain gradient steps (no momentum, no Adam), four learning rates - Results, final training loss and test accuracy: 10⁻⁵, the loss barely moves, test 0.18; 10⁻³, slow, test 0.62; 10⁻¹, loss 0.015, test 0.91; 3, the loss passes 10²⁰ in the first epoch and the run is lost - The working range spans orders of magnitude, so try learning rates 10 times apart (10⁻⁴, 10⁻³, 10⁻², …) before fine-tuning. Do it first, because every other setting depends on it - Adam needs a learning rate too. Because it divides each step by the typical size of the gradient, it tolerates larger rates than plain steps do; plain steps show the failure more clearly here
- Generalization: how well what a model learned from its training data holds for new data from the same source. The baselines lecture asked this for readouts of IT; today it is the same question for any trained network, and what to do when the answer is no - Training lowers the loss on the training images, but what we care about is the performance on new images. The next sections measure that performance, show where a good test score can still mislead, and improve it. The last section opens a trained network up
- A reminder of the baselines lecture before going further. The readout is the logistic-regression probe of that lecture; the data are the monkey IT recordings of the first two assignments - Shuffling breaks every link between the images and the labels, so nothing about animacy is left to learn. Ask yourself what the training accuracy and the test accuracy will be before the next slide
- The figure is from the baselines lecture: the animate vs inanimate readout of monkey IT (Bao et al. 2020 recordings), 102 training images, 306 test images, 1,000 shuffles of the training labels - With true labels the generalization gap is 0.04 (1.00 − 0.96); with shuffled labels it is 0.44 (1.00 − 0.56) - Zhang et al. (2017), Table 2: Inception v3 trained on ImageNet (1.2 million photos, 1,000 categories) with no regularization. With the true labels: 99.5% correct on the training photos, 59.8% on new ones. With labels drawn at random: 95.2% on the training photos, 0.1% on new ones, which is chance for 1,000 categories. A network with enough capacity, the number of different labelings it can fit, can memorize any labels; the same network generalizes when the labels are real - Training accuracy alone cannot tell a network that learned the categories from one that memorized the images - Minute paper 11 asks about this slide - The assignment measures the train–test gap of a readout and refits it with shuffled labels - The previous lecture trained networks by backpropagation. Whatever the learning rule, brain or network, the test of what it learned is the same: performance on new data
- Every model of the course so far is such a function. The perceptron and the delta rule map two inputs to one output. The probe of the baselines lecture maps 480 IT responses to "animate" or "inanimate". Last lecture's network maps two inputs to XOR through a hidden layer - Training adjusts θ, the weights and biases, to lower the loss on the training pairs. Nothing in training looks at new inputs, which is why generalization has to be measured separately - The next slides use a function of a single input x, a curve, because then the whole function can be drawn and compared with the points it was fit to
- Computed: y = sin(2πx) plus noise with standard deviation 0.3, at 10 evenly spaced x between 0 and 1. Least-squares polynomials of degree 0, 1, 3 and 9 - Errors are root-mean-square errors (RMSE): the square root of the mean squared error, the loss of the delta rule and of linear regression. Taking the square root puts the error back in the units of y, so 0.3 means the fit misses a typical point by about 0.3 - A polynomial of degree d has at most d − 1 turning points (peaks and troughs) and at most d places where it crosses zero. Degree 1 is a line, degree 3 can bend twice, degree 9 up to eight times - Error on new points: 2,000 new noisy samples from the same curve, not used in the fit - A polynomial of degree 9 has 10 coefficients, one per training point, so it can pass through all 10 points exactly. It fits the noise too, and swings far off between and beyond the points - The best degree here is 3, with error 0.33 on new points. The noise alone gives 0.30, so no curve can do much better - Why a curve? The readouts of the assignments are fitted functions too, with hundreds of weights and a few hundred images, but they cannot be drawn. The polynomial is the smallest case where the whole function, its flexibility (number of coefficients) and its errors can all be seen - The same trade-off decides how strong a penalty the ridge readouts of the next assignment need, and the shuffled-label probe of the last slide is the degree-9 polynomial of a readout: flexible enough to fit any labels - This example and the next follow Bishop (2006), Figs 1.4 and 1.6, the standard textbook illustration
- The previous slide changed the model and kept the data. This one keeps the model and adds data - Computed as before. Error on new points 0.86 with N = 10, 0.34 with 15, 0.35 with 30, 0.31 with 100. Training error rises from 0.00 to 0.28, toward the noise level of 0.30: with many points the curve can no longer fit the noise - A network's flexibility is harder to count than 10 coefficients, but the same trade holds: more training images make the same network overfit less
- Every choice we make while looking at a score (the degree, the number of epochs, the learning rate) can fit that score's particular images - So the images used to choose must be kept apart from the images used to report
- Held-out data has been with us since the early lectures. With choices to make, it now comes in two parts: validation for choosing, test for reporting - Parameters are what training learns (weights and biases). Hyperparameters are what we choose: learning rate, batch size, number of epochs, width, depth, penalty strength - Any step that learns from data, such as PCA or z-scoring, is fit on the training images only. The current assignment fits PCA this way - A train and test curve plotted side by side to look at the gap, as in the current assignment, is exploration: nothing is chosen on it. A curve used to choose an epoch or a penalty must be a validation curve. The next assignment uses all three splits
- The baselines lecture scored readouts of IT this way. Here it chooses a setting: for each candidate (a learning rate, a penalty λ, a degree), run all k folds and average the k validation scores; keep the candidate with the best mean - Every training example is used for validation exactly once and for training k − 1 times, so no example is wasted. The price is k fits per candidate - k = 5 or 10 is common. Leave-one-out sets k to the number of examples: N fits, each on all examples but one. For ridge regression it has a closed form, which is why RidgeCV (the ridge slide, end of the next section) uses it at no extra cost - After choosing, refit once on all the training data with the chosen setting; the test set then scores that one model, once - Anything fit to data inside the loop, such as z-scoring or PCA, is fit on the k − 1 training parts of each fold only
- Computed: the IT recordings of the first two assignments (Bao et al. 2020). A network with one hidden layer of 256 ReLU units, trained with Adam, learning rate 10⁻³, minibatches of 32, reads out the six categories from 100 randomly chosen IT sites. 58 of the 300 training labels were redrawn at random (46 ended up wrong), as happens when images are labelled quickly; the 400 validation images keep their true labels - Validation loss is lowest at epoch 20 (0.561) and is 0.972 at epoch 400. Validation accuracy is highest at epoch 8 (0.820) and is 0.775 at epoch 400. Training accuracy reaches 1.000: the network has memorized the wrong labels too - With all 482 sites the curves barely turn: in so many dimensions the network can memorize the wrong labels without disturbing its answers on other images (the many-dimensions slide, in the appendix). With 100 sites, memorizing them costs accuracy on new images - Loss and accuracy need not agree on the best epoch. The loss also punishes confident wrong answers, so it can rise while the accuracy holds steady. Pick one validation score in advance and keep the checkpoint where it is best - Early stopping is a form of regularization: any change to training that gives up some fit to the training data to do better on new data. Fewer steps leave the weights less time to fit the noise. Regularization is the subject of the next section - The next assignment plots learning curves and keeps the best checkpoint
- Computed: the 10 points of "Too rigid, or too flexible", a degree-9 polynomial, full-batch gradient descent on the mean squared error from all coefficients at 0, learning rate 0.64. Test RMSE on the same 2,000 new points - Gradient descent fits the directions in which the loss is steep first: the broad shape of the data. The directions that bend the curve through each noisy point are shallow and take millions of steps. Stopping in between keeps the shape and leaves the noise unfit - Test RMSE: 0.53 after 10 steps, lowest at step 1,467 (0.33, training RMSE 0.12), then 0.86 after 10¹⁰ steps, the degree-9 fit of "Too rigid, or too flexible" that passes through every point - The steps are on a log axis: the late rise in test RMSE takes 10 million steps or more on this tiny problem. On a network the same turn appears within tens of epochs, as on the previous slide - Stopping early keeps the weights closer to where they started, a limit on how closely they can fit the training data. Later in this lecture this idea gets a name, regularization, and the weight penalty does something similar - In practice you do not see the test curve: the validation set stands in for the new points, as on the previous slide
- This is the law of large numbers at work: as the test set grows, the measured accuracy converges to the true accuracy, the one we would get on every possible new image. How fast it converges comes from the binomial spread (or the central limit theorem): the interval shrinks as 1 over the square root of the number of test images, so four times the images halve its width - Computed: a logistic-regression readout of the six categories from the same 100 IT sites (Bao et al. 2020), trained on 300 images; for each test-set size, one random set of test images from the other 924, resampled 2,000 times. The interval holds the middle 95% of the resampled accuracies - The interval width falls roughly as one over the square root of the number of test images: 0.24 with 25, 0.15 with 100, 0.05 with 800 - To compare two models on the same test images, resample the same images for both and look at the difference (a paired bootstrap)
- Everything so far assumed that test images come from the same source as training images. In the world they often do not - A network trained on ImageNet photographs scores highly on new ImageNet photographs, its test set. Images of another kind can expose what it relies on - ResNet-50: a 50-layer image network trained on ImageNet, 1.2 million photographs in 1,000 categories. The cue-conflict images were made by style transfer, the cat's shape painted with elephant-skin texture - The pictured cat illustrates the conflict. The percentages summarize the whole experiment: across the cue-conflict images, counting only answers that named either the shape category or the texture category, people chose the shape in 95.9% of them, ResNet-50 in 22.1% - Training on stylized images, which removes texture as a cue, raised the network's shape choices - Geirhos et al. (2020) review shortcut learning across tasks: a pneumonia detector that read the hospital's marker in the X-ray, an animal classifier that used the background - A held-out test set can miss a shortcut when the same cue–label relationship holds in the training and test images. When you look at a network's errors, ask which cue it might have used - The next assignment covers parts of two photographs and watches a pretrained network's answer change
- The next slides show three ways: penalize large weights, train on altered copies of the images, and switch off random units during training. Early stopping, from the learning curves, is a fourth - All four are regularization: they give up some fit to the training data to do better on new data
- The polynomial with 10 coefficients and 10 points, from the start of the lecture. Without a penalty the coefficients reach about a million in size; with λ = 10⁻³, about 17 - Large coefficients are what let the curve swing between the points. Keeping them small keeps the curve smooth - θ stands for all the parameters. In the polynomial, θ is all 10 coefficients, the constant term included, and the penalty covers every one of them. λ is the strength of the penalty, a hyperparameter (elsewhere in the course λ is an eigenvalue). Choose λ on validation data, never on the test set - The current assignment adds this penalty to a readout - Bishop (2006), Fig. 1.7, shows the same effect
- Computed: the running readout (six categories, 100 IT sites) as a softmax logistic regression on 300 training images, full-batch gradient descent for 20,000 steps, without a penalty and with λ = 0.01 (bias not penalized). Left: the length of w; right: the training cross-entropy, both against the number of steps. Both classify all 300 training images correctly; on the other 924 images, 0.851 without the penalty and 0.860 with it - Magenta: no penalty. Green: weight decay. A longer w makes the readout more confident - Not every unpenalized readout grows. With cross-entropy, the weights grow without end only when the readout can classify every training image correctly (the classes are separable in the training set): then there is no finite best w. If some training images stay wrong whatever w is, a finite w minimizes the loss and gradient descent settles there. With squared error (linear regression) a finite best always exists. With 100 sites and only 300 images, separating them is easy, which is why it happens here - When every training image is already classified correctly, scaling w up pushes every p̂ for the true class closer to 1, so the cross-entropy keeps falling: there is no finite best w, only a best direction. Without a penalty the norm is 10.7 after 20,000 steps and still rising - With λ = 0.01 the norm levels off at 3.5 and the cross-entropy near 0.11. With 100 inputs and six classes, the penalty changes the direction of w as well as its length - scikit-learn's LogisticRegression adds this penalty by default. A PyTorch loop does not, unless you pass weight_decay to the optimizer - For plain gradient descent (torch.optim.SGD), weight_decay adds weight_decay × θ to each gradient, so every step also shrinks each weight by a fixed fraction. That is the gradient of the penalty with λ = weight_decay / 2 - torch.optim.Adam includes the penalty in its gradient and then rescales that gradient. AdamW shrinks the weights separately, at each step (Loshchilov & Hutter 2019) - By default, PyTorch applies weight_decay to every parameter it is given, biases included
- More data is the most reliable fix for overfitting, when it can be had. Labelled data is expensive, so the next best thing is to make more from what you have - Each epoch shows a different random version of each image, which makes memorizing the training images harder - Flips that would change the label (a 6 and a 9, a b and a d) must be left out. Speech recognizers train on recordings with stretches of time and bands of frequency masked out (SpecAugment, Park et al. 2019); medical-image networks on rotated and re-lit scans - Krizhevsky et al. (2012) trained AlexNet on random 224 × 224 crops of each 256 × 256 photo and their mirror images, which multiplies the training set by 2,048, plus colour changes - Photograph: THINGSplus, public domain (CC0)
- Regularization is any change to training that gives up some fit to the training data to do better on new data. The weight penalty of the previous slides is one; early stopping, from the learning curves, is another - Dropout (Srivastava et al. 2014): each hidden unit is switched off with probability p (often one half) at every training step, a different random set each time. A unit cannot count on any particular other unit, so the network cannot build fragile combinations that fit single training images. At test time all units are on, with their outputs scaled so their average matches training. AlexNet used dropout in its fully connected layers; without it, Krizhevsky et al. (2012) wrote, the network "exhibits substantial overfitting" - L1 penalizes the sum of the absolute values of the weights instead of their squares. It drives many weights to exactly zero, so the model uses fewer inputs - The penalties differ in detail, but they share one effect: they restrict which weight settings training can reach, so the network has fewer ways to fit the noise in its training data - In PyTorch: nn.Dropout(p=0.5) as a layer; model.train() switches it on and model.eval() switches it off. Weight decay is the weight_decay argument of the optimizer
- The same playground as last lecture, with three additions: held-out points (open circles) that training never sees, the held-out loss as a green curve, and a weight penalty and dropout - Default: two moons, 30 training points with 15% of their labels flipped, two hidden layers of 32 ReLU units, learning rate 0.03. The held-out points keep their true labels, so the held-out loss measures how well the boundary matches the real one - Unregularized: the held-out loss is lowest near epoch 100 (about 0.43), then rises to about 1.0 by epoch 5,000 as the boundary bends around the flipped points; held-out accuracy about 75% - With λ = 0.01 the held-out loss stays near 0.44 (accuracy about 82%). Dropout 0.5 brings it down to about 0.27 (about 88%). With 200 training points instead of 30 it falls to about 0.18, and every held-out point is classified correctly - The loss is the cross-entropy of a sigmoid output, as in last lecture's playground. The weight penalty adds λ·w to each weight's gradient, the gradient of (λ/2)‖w‖². Dropout silences each hidden unit with probability p on every training step and is switched off for the held-out loss and the picture - The demo is on the course site with the other demos. Play with it after class
- The weight penalty of this section, applied to a model of a neuron instead of a curve. The assignment fits this model, and the next assignment uses the same ridge readout - An encoding model predicts a neuron's response to each image from a network's features. With the penalty λ‖w‖² added to the squared error, the fit is called ridge regression. It is scored by R² on held-out images - The target is one IT site's response to each of the 1,224 object images of Bao et al. (2020); the features are the 512 units of the trained ResNet-18's late layer. A random fifth of the images is held out and never seen by the fit - The model is a weighted sum of the features plus a bias, fit by least squares: linear regression. Run with a small enough step on a continuous target, the delta rule minimizes the same squared error - λ is chosen by leave-one-out cross-validation within the 980 training images (scikit-learn's RidgeCV). The held-out fifth only scores the chosen fit. The held-out curve on the right is drawn to show what the penalty does; it was not used to choose λ - R² = 1 − (squared error of the prediction) / (squared error of predicting the mean response). 1 is perfect, 0 is no better than the mean, and it can be negative. The baselines lecture used the squared correlation, which is close for a good fit - Right panel: with almost no penalty, 512 weights fit the training images closely (R² 0.85) and predict held-out images poorly (0.28): overfitting. As λ grows, the training fit gets worse and the held-out fit better, up to a point (0.69) - The current assignment fits this model with nested cross-validation: λ is chosen inside each training fold, and the held-out R² comes from the outer folds
- In 1959 Hubel and Wiesel spent hours showing spots of light to a neuron in a cat's visual cortex without a response. It fired when the edge of the glass slide in their projector swept across the screen: the cell responded to an edge at one orientation. That discovery, and the methods that followed, earned them the 1981 Nobel Prize - The last slide predicted a neuron from a network's units. Now the reverse: what do the units of a trained network respond to, measured the way we measure neurons? - The methods are those of physiologists: show stimuli, record the responses, summarize them. In an animal that is all we can do. In a network we can also read the weights, and check one against the other - The same measurements describe a V1 cell, an IT site and a unit of AlexNet. The assignment uses them on network units and on IT sites
- Each small image is one first-layer filter of AlexNet (torchvision's trained weights), its 11 × 11 weights for the three colour channels shown as a colour image. A filter is the unit's template: the image patch that drives it most - Training only asked the network to name objects. Nothing in the objective mentions edges, orientations or V1 - The rest of this section answers the question in three steps: what V1 receptive fields look like, a way to describe any receptive field with a few numbers, and then the comparison, measured - The assignment does exactly this comparison for AlexNet's first layer
- Reproduced from Ringach (2002), Fig. 2 (rows 1–2, 4–5 and 7–8 of the original). Each receptive field was mapped by showing the cell rapid sequences of gratings and averaging the stimulus that preceded each spike (reverse correlation) - Ringach's caption: "In general, 2-dimensional Gabor functions provide a good representation of the shapes of receptive fields in V1" - Daugman (1985) proposed the two-dimensional Gabor as a description of simple-cell receptive fields. Jones & Palmer (1987) mapped cat simple cells and showed that Gabors fit them closely, with residuals that looked like noise - A residual with structure in it, such as a stripe the fit left out, would mean a Gabor does not describe that field - The next slide fits Gabors to toy fields we built, and keeps two numbers from each fit
- For a first-layer unit, the input weights form an image, its receptive field. A deeper unit combines earlier units, so its weights are not an image - Computed on toy units, not on data. Left: a Gabor with added pixel noise, the least-squares Gabor fit, and the residual (the field minus the fit). The residual is only noise, so the fit has captured the structure - SS_res is the sum of the squared residuals. SS_tot is the sum of the squared deviations of the field from its mean. R² is 1 when the residual is zero, and falls as the fit misses more of the field - Here R² measures how well the fit reproduces the field it was fit to. Earlier, for the model of a neuron, R² scored predictions of held-out responses instead - A residual with structure in it, such as a stripe the fit left out, means a Gabor does not describe that field - The Gabor is a cosine grating (frequency f, phase φ) multiplied by a Gaussian window with widths σx across and σy along the stripes; x′ and y′ are the image coordinates rotated to the stripes' orientation. Right: nx = σx·f and ny = σy·f are the window's standard deviations measured in cycles of the stripes (Ringach 2002). Below about 0.25 on both, the window holds only a small part of one cycle: a small spot with little orientation (A). Larger values mean more stripes, and longer ones (C) - Keeping only good fits means the comparison that follows says nothing about the fields a Gabor does not describe - The assignment fits a Gabor to each of AlexNet's first-layer filters
- Ringach (2002) mapped the receptive fields of 93 macaque V1 simple cells, fit a Gabor to each, and released the fits. The slate-grey squares are his cells: 71 of the 93 have both n_x and n_y below 0.6, and the medians are 0.32 and 0.41. The stars are the toy units of the Gabor-fit slide, for reference - nx measures the window across the stripes, ny along them, both as the window's standard deviation in wavelengths of the stripe pattern. A Gaussian window has no hard edge - The assignment places AlexNet's first-layer filters on this plot - Two summary numbers are a weak test of whether two sets of receptive fields are alike. Predicting a neuron's responses from a network is a stronger test: the model of a neuron earlier today was a first example, and the lecture on comparing models with brains takes it further
- The network's points are AlexNet's first-layer filters with a Gabor fit of R² above 0.75, each fit to the filter's mean over its three colour channels - The assignment makes this plot and asks these two questions - Nobody built Gabors into AlexNet: its first layer learned them from labelled photographs by backpropagation. A later lecture shows that a different objective, sparse coding of natural images, also learns them
- In an animal we cannot read the weights. We can only show stimuli and record. With a network unit we can do the same, and check the result against the weights - Hubel & Wiesel (1962) measured orientation tuning this way in cat visual cortex, with bars of light at many orientations - Computed: four 41 × 41 receptive fields built by hand. A, B and C are Gabors (an oriented stripe pattern inside a smooth elliptical, Gaussian window) with long, medium and short windows. D is a centre-surround unit like a retinal ganglion cell. Each is shown full-field gratings at 24 orientations and 4 phases - Top: each unit's weights and its orientation selectivity index (OSI). Bottom: its tuning curve, scaled to its own peak - Bandwidth is the half-width of the tuning curve at half its height above its minimum; the figure does not print it. Compare the narrow curve of A with the broad curve of C - The centre-surround unit is round, so it responds the same at every orientation. Its index is 0 and its curve is flat - A long window covers many points along the stripes, so a small tilt already misaligns them: narrow tuning. A short window tolerates more tilt: broad tuning. Both can still fall to near zero at the orthogonal orientation, which is why both indices are near 1 - The tuning curve follows from the template. It peaks where the grating best matches w - The assignment measures the tuning curves of AlexNet's first-layer units the same way
- Computed: a Gabor filter and a grating at its preferred orientation, at four evenly spaced phases. Responses scaled so the largest is 1 - The weighted sums are +1, +1, −1, −1 and average to 0, although this is the unit's preferred orientation. The cancellation is exact for a grating whose light and dark stripes balance, evenly spaced phases and no bias - After the ReLU they are 1, 1, 0, 0, average 0.5 - Why rectify: to compare a network unit with a recorded cell, the unit should behave like a cell, and a cell's firing rate cannot go below zero. A rectified weighted sum (a ReLU, or a rate that is zero below threshold) is the simplest such model, and AlexNet's first-layer units are followed by a ReLU anyway - What rectification is not needed for: the Gabor fit of the previous slides is fit to the weights, the receptive field itself, with no responses involved - Averaging a tuning curve over phase is an analysis step. A recorded cell's responses cannot cancel this way because they are never negative. That says nothing about how the cell combines its inputs - In V1, a simple cell responds to a grating only at some phases, like the rectified sum here. A complex cell responds at every phase. It behaves as if it pooled rectified simple-cell responses at different phases - The assignment rectifies each AlexNet response before averaging over phase
- Real data: trial-averaged responses of two IT sites to the 1,224 images of Bao et al. (2020), 51 objects in six categories with 24 views each. Each dot is one view, each bar an object's mean - IT sites respond to whole objects. The geometry lecture split the variance of whole populations of units the same way. Here it describes one site - Site A's object means differ a lot compared with the spread of its views: 60% of its variance lies between objects. Site B responds about as differently to two views of one object as to two objects: 22% - Here every object has 24 views, so the total variance equals the variance of the object means plus the mean within-object variance. With unequal numbers of views, each object's part must be weighted by its count - A different measure from the orientation selectivity index, which compares the peak and trough of a tuning curve. This one asks how much of all the variation is about identity - Trial-averaged responses still carry some noise. It adds to both parts, mostly to the within-object part - Analysis of variance (ANOVA) uses the same split but divides each sum of squares by its degrees of freedom (the number of values free to vary once the group means are fixed): F = [SS_between / (G − 1)] / [SS_within / (N − G)], with G objects and N responses. Whether an F is large needs a reference distribution, the F distribution or a shuffle test. With categories as the groups, it measures category selectivity - The assignment computes this index for IT neurons and for network units
- In a network, ablating a unit means setting its output to zero for every image, then measuring the readout's test accuracy again. In an animal, lesions or optogenetic silencing play the same role - A unit can be selective and still not be needed. Take ten identical selective units. With a refitted readout, the remaining nine can replace the removed one. A fixed readout may still lose accuracy, since its weighted sum changes. The reverse also happens: a population can be decoded well when no single unit separates the classes - Without the random control, a drop in accuracy only tells you that removing units hurts. The control tells you whether the selective ones are special - The assignment removes the most selective units, or random ones, in IT and in the network, and refits the readout each time
- Next lecture: the visual system and convolutional networks. Each first-layer filter is slid over the whole image, which is convolution, and the first-layer Gabors meet V1
- Hubel & Wiesel (1962), Receptive fields, binocular interaction and functional architecture in the cat's visual cortex. The classic behind "Measuring a tuning curve" - Ringach (2002), Spatial structure and symmetry of simple-cell receptive fields in macaque primary visual cortex. Goes with "Where V1 simple cells sit" - Sorscher, Ganguli & Sompolinsky (2022), Neural representational geometry underlies few-shot concept learning. Goes with "Generalization happens in a space" - Recht, Roelofs, Schmidt & Shankar (2019), Do ImageNet classifiers generalize to ImageNet? The ranking of networks held on the new test set, but every network lost accuracy: a new sample of a slightly different source is a small distribution shift. Goes with "Shortcut learning" - Geirhos, Jacobsen, Michaelis, Zemel, Brendel, Bethge & Wichmann (2020), Shortcut learning in deep neural networks. Goes with "Shortcut learning" - Before posting, skim the existing entries on your paper; your post must add something not already said
- Submitted on Canvas (Minute papers → Minute Paper 11); credit for a thoughtful attempt
- These slides belong to this lecture but were not presented in class
- The previous slide showed why to shrink the step. This one shows the shapes of schedules in common use, on one small problem - The story: all four runs fall quickly at first, because early steps are large in every schedule. The difference is at the end. With a constant step the loss keeps jumping (the dark trace in the inset); the shrinking schedules let it settle near the lowest possible loss (dashed line) - A minibatch gradient is noisy, and the noise does not shrink as the weights approach the minimum. A constant step keeps moving them around. Too large a step overshoots the valley, and too small a step takes many steps to get there - Computed: logistic regression on simulated, overlapping 2-D classes, minibatches of 8 examples, the cross-entropy loss, trained with each schedule from the same start and the same minibatches. The dashed line is the lowest loss the model can reach on these data - The third schedule written out: η_t = η0/(1 + t/τ), where η0 is the starting learning rate. Here η0 = 0.05 and τ = 100 steps, so the step has halved after 100 steps - Typical values: the classic ImageNet recipe for ResNets starts at 0.1 and divides it by 10 every 30 epochs (He et al. 2016). Cosine decay over the whole run is today's common default, often after a warm-up: a few epochs in which the learning rate grows from near 0 to its starting value, so that the first, large gradients do not throw the weights far off. The 1/(1 + t/τ) schedule is the one convergence proofs use; τ is chosen by hand like η, by trying a few values; a common choice makes the learning rate halve after one to a few epochs - Robbins & Monro's two conditions: the sum of all step sizes is infinite, so the weights can still travel as far as they need to. The sum of their squares is finite, so the noise of the gradients dies out. The 1/(1 + t/τ) schedule meets both. A fixed η fails the second - With extra assumptions about the loss and the gradient noise (for example, a bowl-shaped loss and gradient noise that stays bounded), steps that meet both conditions make stochastic gradient descent converge. For a network's loss, converging means reaching a point where the gradient is zero, which need not be the lowest loss - Schedules used for large networks (warmup, a short period of growing η, then cosine decay over a fixed number of steps) do not meet these conditions. They work well in practice and are tuned by experience
- Still the polynomial. One training set gives one fit. Asking how a method generalizes means asking what it would do with other training sets of the same size - Computed: the polynomial example; 20 training sets for the drawing, 2,000 for the numbers. Degree 1: bias² 0.222, variance 0.017. Degree 3: 0.007 and 0.030. Degree 9: 0.001 and 0.547 - Bias is the error of the average prediction. At each x, average the predictions of all the fits (the red curve, E[ŷ]) and compare with the true curve f(x): the shaded gap is f(x) − E[ŷ]. On the next slide, bias² is that gap squared and averaged over x. Variance is how much the prediction ŷ at a given x changes from one training set to another: the spread of the thin blue curves, not the spread of their errors - A weight penalty, later in this lecture, makes the degree-9 fits less sensitive to their noise: lower variance, at the cost of some bias
- The previous slide showed bias and variance as pictures. For squared error they add up exactly to the expected error on new points - At a fixed input x, bias and variance average over training sets. The expected error on the left also averages over the new point's own noise, which is independent of the training sets and has mean zero. The figure then averages all three terms over the inputs - σ²_noise is the variance of the noise around the true curve (0.3² = 0.09 here): no model can remove it - Computed: 2,000 training sets of 10 points for each degree. The expected error is lowest at degree 3 (0.127): bias² 0.007, variance 0.030, noise 0.090 - Bias here means a systematic error of the average fit, not the bias term b of a neuron - Geman, Bienenstock & Doursat (1992) brought this decomposition to neural networks. Its conclusion, that more flexible models overfit, is the classical view. Very large networks do not always follow it: they can memorize random labels yet generalize on real ones (Zhang et al. 2017, on the shuffled-label slide) - For a classifier scored by accuracy there is no exact decomposition, but the same two kinds of error exist
- The polynomial had one input. A network's hidden layer, or a layer of a trained network used as features, often has hundreds or thousands of units, and a readout on it has as many weights. A lab or an animal may have only a few hundred labelled examples - Computed: points drawn from a D-dimensional Gaussian; the label is the sign of the first coordinate. Logistic regression with almost no penalty, 100 training points, 2,000 new points, 20 repeats. With 1 dimension, 99.6% on new points; with 1,024, 58% - The task already needs only one dimension. The readout fails because it cannot tell which one: with D weights and fewer than D examples, it can fit the training labels using the noise dimensions, and those weights do not carry over to new points - Two fixes: a representation that drops or shrinks the irrelevant dimensions, or a limit on the readout's weights (a penalty, later in this lecture) so that it cannot fit their noise - The same failure as the shuffled-label readout of the baselines lecture (480 neurons, 102 images): more weights than examples - Curse of dimensionality: the number of examples needed grows quickly with the number of dimensions. Another face of it, also from the baselines lecture: in many dimensions, random directions are nearly perpendicular
- The previous slide ended on a fix: a representation that ignores the irrelevant dimensions. This is what such a representation buys, measured - More examples help; so does a better representation. Here the representation is fixed and the examples are few - Why a prototype? The simplest readout, an average of the labelled feature vectors: a neuron could compute it - The experiment, step by step (Sorscher et al. 2022, pp. 2–3 and Methods): train ResNet-50 on the 1,000 ImageNet categories and freeze it. Pick 1,000 new concepts from the larger ImageNet-21k collection, 500 photos each. Represent each photo by the network's 2,048 final features - For a pair of new concepts, average the few labelled feature vectors of each into a prototype. The readout's weight vector is the difference of the two prototypes, and the boundary sits halfway between them - Score on held-out photos of the same two concepts, over all 999,000 ordered pairs: 98.6% with 5 examples per concept, 92.0% with 1 - The theory predicts each pair's error from the geometry of the two object manifolds (geometry lecture): the distance between their centres, their radii and their dimension. Larger dimension can even help - The same analysis on monkey recordings (Majaj et al. 2015; 168 IT and 88 V4 sites, 64 objects): five-shot accuracy about 84% from IT, higher than from V4, and between AlexNet (80%) and ResNet-50 (93%) on the same images - Five examples suffice because the network's representation already separates new animals it was never trained on. The same examples can be too few in one representation and enough in another
- Accuracies are for telling apart two new categories, averaged over 999,000 ordered pairs of 1,000 new ImageNet-21k concepts (Fig. 1C) - The monkey numbers use the recordings of Majaj et al. (2015): 168 IT and 88 V4 sites, 3,200 images of 64 objects; five-shot accuracy from IT about 84%, higher than from V4 (Fig. 5) - The theory predicts each pair's error from the geometry of the two object manifolds (geometry lecture): the distance between their centres, their radii and their dimension - The same examples can be too few in one representation and enough in another: that is why the representation matters more than the readout
- The training loop of last lecture, with a validation pass after every epoch - model.train() and model.eval() switch layers that behave differently during training. One is dropout, which switches off random hidden units during training (later in this lecture). torch.no_grad() skips the bookkeeping for gradients, which validation does not need - model.state_dict() holds every parameter of the network; torch.save writes it to a file. That file is the checkpoint - The test set appears nowhere in the loop. It is used once, after the last line