Lecture 6
Introduction to Machine Learning
KU Leuven, campuses Diepenbeek and Geel
Academic year 2026–2027
Minibatch SGD trains the networks of lecture 5, but:
Better steps, limits on memorising, a cure for depth, and the whole training loop in PyTorch.
composed nonlinear layers
unchanged since lecture 5
cross-entropy, squared error, plus a penalty
the penalty of lecture 2
momentum, Adam
with a schedule for the learning rate
Exercise 3 uses all three: Adam, weight decay and dropout, in PyTorch.
Block 1
| \(\eta\) is shared by | the problem | the cure |
|---|---|---|
| every direction | curvature 172 times larger across the valley than along it | momentum |
| every weight | gradients spanning a factor of 1,382 | Adam |
| every step | a step that suits the start is too large near the minimum | a schedule |
Each cure keeps the gradient of backpropagation and changes only the step taken with it. The 172 and the 1,382 are measured on the slides that follow.
Near its minimum a smooth loss is a parabola like this one. \(\lambda\), its second derivative, is the curvature. A small \(\eta\) shrinks the error, a larger one flips its sign as well, and \(\eta\lambda > 2\) makes it grow.
One rate must satisfy the steepest direction and is then far too small for the flattest. The ratio \(\lambda_{\max} / \lambda_{\min}\) decides how much too small.
| across | along | |
|---|---|---|
| curvature \(\lambda\) | 74.5 | 0.43 |
| \(\eta \lambda\) at \(\eta = 0.024\) | 1.80 | 0.010 |
| error \(\times\) per step | 0.80 | 0.990 |
| steps to shrink it 100-fold | 21 | 438 |
\(\lambda_{\max} / \lambda_{\min} = \) 172, so \(\eta\) must stay below \(2 / 74.5 = 0.027\).
Across the valley \(1 - \eta\lambda\) is negative: the sign of the error flips every step, which is the zigzag. Along it the error barely moves, which is the crawl.
A steady direction speeds up tenfold, while a direction whose sign flips cancels itself.
| \(\beta\) | \(1/(1-\beta)\) | steps to the minimum |
|---|---|---|
| 0 | 1 | 1,841 |
| 0.5 | 2 | 914 |
| 0.9 | 10 | 86 |
| 0.95 | 20 | 95 |
| 0.99 | 100 | 667 |
The same \(\eta\) throughout, a third of the rate of the valley slide. \(\beta = 0\) is gradient descent, and three times slower than its 612 steps there.
Too little memory and the steps along the valley stay small. Too much and the velocity carries the weights past the minimum and back, which costs more than it saves. 0.9 is the usual default.
Checkpoint
The gradient of one weight can be a thousand times that of another.
One \(\eta\) is then too large for the first and too small for the second.
This rule is RMSProp. \(s\): the running mean of \(g^2\), per weight. The step no longer grows with the size of \(g\).
η=10⁻³, β1=0.9, β2=0.999
for t = 1, 2, ...:
g ← gradient
m ← β1 m + (1 − β1) g
s ← β2 s + (1 − β2) g²
m̂ ← m / (1 − β1ᵗ)
ŝ ← s / (1 − β2ᵗ)
w ← w − η m̂ / (√ŝ + ε)
m = b1 * m + (1 - b1) * g
s = b2 * s + (1 - b2) * g**2
m_hat = m / (1 - b1**t)
s_hat = s / (1 - b2**t)
root = np.sqrt(s_hat) + eps
w = w - lr * m_hat / root
\(m\) is the momentum of this block, \(s\) the RMSProp of the previous slide, and \(\hat{m}\), \(\hat{s}\) a bias correction.
Both averages start at zero, so both are too small at first — but by different factors. Without the correction the first step is 3.2 times \(\eta\).
| gradient \(g\) | one plain step \(\eta g\) | three Adam steps |
|---|---|---|
| 0.596 | 0.0060 | −0.0300 |
| 0.066 | 0.00066 | −0.0300 |
| 0.00043 | 0.0000043 | −0.0300 |
The largest, the middle and the smallest gradient of the 65 bearing weights, each held constant, \(\eta = 0.01\). The first step is \(\eta\) in every direction, since \(\hat{m}_1 = g\) and \(\hat{s}_1 = g^2\), and so is every step after it.
Plain steps differ by the same factor of 1,382 as the gradients. Divided by their own root mean square, all three weights move by \(\eta\) per step.
| rule | state per weight | 784-128-10 |
|---|---|---|
| SGD | nothing | 0.4 MB |
| momentum | \(v\) | 0.8 MB |
| Adam | \(m\) and \(s\) | 1.2 MB |
101,770 parameters in 32-bit floats, with the weights themselves counted.
Harmless here. On a model with a billion parameters, 4 GB of weights become 12 GB before a single activation is stored, and lecture 5 showed that the activations also have to be kept.
Adam's first step is \(\eta\) in every direction, whatever the gradient.
At the start the weights are random, the gradient says little, and a large \(\eta\) sends every weight the same distance into the dark.
Warm-up raises \(\eta\) from near zero over the first steps, by which time \(s\) has seen enough gradients to mean something.
On the bearing network it gains nothing: with Adam at \(\eta = 0.1\), the largest rate of the sweep and the one where warm-up has most to do, it ends at 0.1305 against 0.1311 for the same cosine schedule without it.
Leave \(\beta = 0.9\), \(\beta_1 = 0.9\) and \(\beta_2 = 0.999\) alone.
Reach for SGD with momentum when memory is tight, or when a published result used it. Add warm-up when the model is large.
Checkpoint
Block 2
| layer | parameters |
|---|---|
| 1 → 64 | 64 + 64 = 128 |
| 64 → 64 | 4,096 + 64 = 4,160 |
| 64 → 1 | 64 + 1 = 65 |
| total | 4,353 |
218 parameters for every training measurement.
Lecture 2 fitted a degree 12 polynomial, i.e. 13 numbers, to 50 points and it already swung. Nothing in the loss asks this network to be smooth, so it passes through all twenty points and does as it likes between them.
The penalty of lecture 2. Every step first shrinks each weight by the factor \(1 - 2\eta\lambda\): a decay.
after every epoch:
if the validation loss
is the best so far:
keep these weights
reset the counter
else:
count one epoch
stop at the patience
best, kept, waited = np.inf, 0, 0
for epoch, value in enumerate(val):
if value < best:
best, kept = value, epoch
waited = 0
else:
waited += 1
if waited == patience:
break
In each training step, each hidden unit is dropped with probability \(p\).
Kept units are scaled by \(1/(1-p)\), so the next layer receives the same input on average.
keep = rng.random(H.shape) >= p
H = H * keep / (1 - p)
At test time nothing is dropped and nothing is scaled.
No unit can rely on one particular other unit, since it may be gone in the next step.
Each step trains a different thinned network, sharing its weights with all the others.
At test time the full network approximates the average of the thinned networks: the bagging of lecture 4, inside one network.
The same mask on the way back. In that step a dropped unit receives no gradient, on either side of it.
| test RMSE | largest \(|w|\) | rms \(w\) | steepest slope | |
|---|---|---|---|---|
| no regularisation | 205 kW | 7.08 | 0.40 | 3,936 |
| weight decay, \(\lambda = 10^{-3}\) | 128 kW | 1.07 | 0.029 | 342 |
| dropout, \(p = 0.1\) | 129 kW | 3.09 | 0.35 | 719 |
| the true curve | — | — | — | 507 |
Slopes in kW per m/s over the training range. Weight decay shrinks the weights fourteenfold and leaves a fit flatter than the true curve. Dropout, at the same test error, leaves the weights almost as large as before.
| hidden units | parameters | training | test |
|---|---|---|---|
| 4 | 13 | 79 | 151 |
| 16 | 49 | 62 | 197 |
| 64, 64 | 4,353 | 9.5 | 205 |
RMSE in kW, the same twenty measurements and the same training.
It helps, and it is the bluntest of the cures: the training error rises eightfold and the test error still does not reach the 128 kW of a penalty on the large network.
| cure | test RMSE | what it costs |
|---|---|---|
| nothing | 205 kW | — |
| a smaller network | 151 kW | freedom removed everywhere |
| early stopping | 139 kW | a validation set |
| dropout, \(p = 0.1\) | 129 kW | one \(p\), slower training |
| weight decay, \(\lambda = 10^{-3}\) | 128 kW | one \(\lambda\) |
| ten times the data | 99 kW | 180 more measurements |
The noise in the measurements is 96 kW, which only the last row comes near. The three rows between are within 11 kW of one another, which on twenty measurements is not a difference worth defending.
For every unit, over the minibatch: the standardisation of lecture 2, inside the network, which keeps each sigmoid in its steep middle. \(\gamma\) and \(\beta\) are learned. At test time, running averages of \(\mu\) and \(\sigma^2\) replace the minibatch values.
layers.append(nn.Linear(n_in, 32))
layers.append(nn.BatchNorm1d(32))
layers.append(nn.Sigmoid())
Between the linear part of a layer and its activation, one normaliser per layer.
nn.BatchNorm1d(32) carries 64 learned numbers, a \(\gamma\) and a \(\beta\) per unit, and two running averages that are not learned.
For images the layer is nn.BatchNorm2d, which normalises each channel over the batch and over every pixel of it.
| unit 1 | unit 2 | unit 3 | |
|---|---|---|---|
| example 1 | 1 | 2 | 3 |
| example 2 | 3 | 2 | 1 |
| example 3 | 2 | 2 | 2 |
| example 4 | 0 | 2 | 4 |
Unit 1 has mean 1.5 and variance 1.25 over the batch, so its first value becomes \((1 - 1.5)/\sqrt{1.25} = \) −0.45.
The running mean after this one batch is 0.15, a tenth of 1.5: PyTorch mixes in each new batch with a weight of 0.1. In eval() mode the same value becomes 0.82.
A batch of one in train mode has no variance, so PyTorch refuses it: Expected more than 1 value per channel when training.
PyTorch switches both with one call, model.train() or model.eval(). Block 3 places both in the training loop.
One wind speed, 10 m/s, 100 forward passes of the same trained network.
| mode | prediction |
|---|---|
| eval | 923 kW |
| train | 847 to 1,040 kW |
A standard deviation of 37 kW on a single prediction, from nothing but the masks.
This is the forgotten eval() of the previous slide. Over the whole test set the noise averages out: the RMSE moves from 129 to about 134 kW. The aggregate error nearly hides the bug. A single prediction does not.
Checkpoint
Break
Block 3
Lecture 5 wrote every backward line by hand, for one architecture.
A framework records the forward pass as it runs, and computes every gradient from that record.
The same code runs on a graphics processing unit (GPU).
Exercise 3 uses PyTorch, as does most research code.
X = np.zeros((32, 2))
X.dtype # float64
X = torch.zeros(32, 2)
X.dtype # torch.float32
A tensor is an array that also knows its device and can record gradients.
torch.from_numpy(a).float() converts, since PyTorch works in 32-bit floats.
X = torch.tensor([[1.0, 2.0]])
W1 = torch.tensor([[0.5, -0.3],
[0.2, 0.4]])
b1 = torch.tensor([0.0, 0.1])
W2 = torch.tensor([[0.8], [-0.5]])
b2 = torch.tensor([0.1])
for t in (W1, b1, W2, b2):
t.requires_grad_()
H1 = torch.relu(X @ W1 + b1)
P = torch.sigmoid(H1 @ W2 + b2)
loss = -torch.log(P).mean()
loss.backward()
The worked network of lecture 5, with X @ W1 + b1 as there. The target is \(y = 1\), so the loss is \(-\ln p\).
W2.grad: −0.336, −0.224
W1.grad: −0.298, 0.186, −0.597, 0.373
The numbers of the backward slides of lecture 5, to a relative error below \(10^{-6}\).
loss.backward() sweeps it backwards. Gradients are added to .grad, so every step starts with zero_grad().node = loss.grad_fn
while node is not None:
print(type(node).__name__)
after = node.next_functions
if not after:
break
node = after[0][0]
NegBackward0
MeanBackward0
LogBackward0
SigmoidBackward0
AddBackward0
MmBackward0
ReluBackward0
AddBackward0
MmBackward0
The forward pass of the previous slide, read from the bottom up. It stops at the matrix product that reads \(X\): the data need no gradient.
The same forward pass and backward() twice, with no zero_grad() between them:
W1.grad[0] | |
|---|---|
| after one | −0.2983, 0.1864 |
| after two | −0.5966, 0.3729 |
Exactly doubled. .grad is added to, never replaced.
Leave zero_grad() out of a loop and step \(k\) uses the sum of the first \(k\) gradients, which is the gradient of nothing.
model = nn.Sequential(
nn.Linear(2, 16),
nn.ReLU(),
nn.Linear(16, 1),
)
nn.Linear(2, 16) holds a weight of shape 16 × 2 and computes X @ W.T + b: the transpose of lecture 5. Weights copied from numpy are transposed.
class BearingNet(nn.Module):
def __init__(self):
super().__init__()
self.l1 = nn.Linear(2, 16)
self.l2 = nn.Linear(16, 1)
def forward(self, x):
h = torch.relu(self.l1(x))
return self.l2(h)
| shape | |
|---|---|
xb | 32 × 2 |
l1.weight, l1.bias | 16 × 2, 16 |
l1(xb), after relu | 32 × 16 |
model(xb) | 32 × 1 |
yb | 32 × 1 |
loss | a scalar |
The batch size runs down the rows and never meets a weight.
Shape errors are the commonest failure of part 2 of exercise 3. Print them when something does not fit: print(xb.shape, out.shape, yb.shape) finds the mistake faster than reading the traceback.
sum(p.numel()
for p in model.parameters())
65 for the 2-16-1 bearing network, the count of lecture 5.
101,770 for the 784-128-10 network of part 3 of exercise 3.
model.parameters() is also what the optimiser is given. To count only what is being trained when some weights are frozen, as in the transfer learning of lecture 7, add if p.requires_grad.
loss_fn = nn.BCEWithLogitsLoss()
opt = torch.optim.SGD(
model.parameters(), lr=0.1,
momentum=0.9)
opt = torch.optim.Adam(
model.parameters(), lr=1e-3,
weight_decay=1e-4)
BCEWithLogitsLoss takes the score \(z\), not \(\sigma(z)\): it folds the sigmoid into the loss, which is numerically stable.
Block 1 in one line: momentum or Adam.
weight_decay adds weight_decay · w to the gradient, i.e. \(2\lambda\) of block 2, and it decays the biases too.
X = torch.from_numpy(X_np).float()
y = torch.from_numpy(y_np).float()
data = TensorDataset(X, y)
loader = DataLoader(data,
batch_size=32, shuffle=True)
One pass over loader is one epoch of shuffled batches of 32: the loop of lecture 5, built in.
y is a column of shape \(n \times 1\), like the output. BCEWithLogitsLoss rejects labels of shape \(n\). MSELoss accepts them with a warning and broadcasts to an \(n \times n\) difference.
for each epoch:
for each batch (xb, yb):
reset the gradients
out ← model(xb)
loss ← L(out, yb)
backward: the gradients
one step of the optimiser
for epoch in range(epochs):
for xb, yb in loader:
opt.zero_grad()
out = model(xb)
loss = loss_fn(out, yb)
loss.backward()
opt.step()
dZ2 = (P - y) / len(y)
dW2 = H1.T @ dZ2
db2 = dZ2.sum(axis=0)
dH1 = dZ2 @ W2.T
dZ1 = dH1 * (Z1 > 0)
dW1 = X.T @ dZ1
db1 = dZ1.sum(axis=0)
loss.backward()
Seven lines written for one architecture, against one line that works for any. Change the activation, add a layer, branch the network: the left column is rewritten, the right one is not.
model = nn.Sequential(
nn.Linear(1, 64), nn.Tanh(),
nn.Dropout(p),
nn.Linear(64, 64), nn.Tanh(),
nn.Dropout(p),
nn.Linear(64, 1),
)
opt = torch.optim.Adam(
model.parameters(), lr=1e-3,
weight_decay=2e-3)
The wide network of block 2, with dropout and weight decay.
nn.Dropout holds no parameters: still 4,353.
weight_decay=2e-3 is \(\lambda = 10^{-3}\) of block 2: PyTorch adds weight_decay · w to the gradient, i.e. \(2\lambda w\).
Batch normalisation would be nn.BatchNorm1d(64) between each nn.Linear and its nn.Tanh, not where the dropout sits. Early stopping is the only one of the four with no layer and no argument: it is written in the loop.
model.eval()
with torch.no_grad():
P = torch.sigmoid(model(X))
model.train()
eval(): dropout off, batch norm on its running averagesno_grad(): no graph is recorded, which saves memory and timetrain(): back to training before the next stepfor epoch in range(epochs):
model.train()
for xb, yb in loader:
opt.zero_grad()
out = model(xb)
loss = loss_fn(out, yb)
loss.backward()
opt.step()
model.eval()
with torch.no_grad():
out = model(X_val)
val = loss_fn(out, y_val)
The training loop of this block, with a validation pass at the end of every epoch.
train() at the top of the epoch, since the validation pass of the last one left the model in eval mode.
This is what mlcourse.training.train() runs in exercise 3. Its printed lines are the next slide.
epoch 1/5 train loss 0.486
val loss 0.282
epoch 2/5 train loss 0.197
val loss 0.182
epoch 3/5 train loss 0.150
val loss 0.176
epoch 4/5 train loss 0.144
val loss 0.177
epoch 5/5 train loss 0.141
val loss 0.176
Print both losses after every epoch and read the shape:
Validation on 500 fresh bearings. The real lines also carry an accuracy for each set, left out here for width.
ready = torch.cuda.is_available()
dev = "cuda" if ready else "cpu"
model = model.to(dev)
for xb, yb in loader:
xb = xb.to(dev)
yb = yb.to(dev)
Nothing else in the loop changes.
Every tensor in an operation must sit on the same device, or PyTorch raises an error.
It pays when the batches are large and the model has work to do. A model as small as today's gains little: every batch costs a copy to the device and back, and 32 rows through 65 weights is no work at all.
BCEWithLogitsLoss, the loss cannot fall below 0.62.Target size … must be the same as input size, or a silent broadcast from MSELossmat1 and mat2 must have the same dtypeshapes cannot be multiplied (32x3 and 2x16)zero_grad(): the loss falls, then wanders or divergeseval(): predictions that change between callsBCEWithLogitsLoss: a loss stuck above 0.62The 2-16-1 network, Adam, ten epochs, five seeds:
0.1336 to 0.1374, a spread of 0.004.
The seed fixes the initial weights and the order of the batches, and nothing else in this run is random.
torch.manual_seed(0) before the model and before the loader. Every figure of this lecture does it; without it, none of its numbers would hold.
Checkpoint
opt.zero_grad() missing, SGD's loss falls for the first steps and then wanders. Why does it fall at all?| lecture 5 | lecture 6 | |
|---|---|---|
| model | composed nonlinear layers, unchanged | |
| loss | cross-entropy | \(+ \lambda \sum w^2\) |
| step | \(w - \eta g\) | momentum, Adam |
| rate | one constant | per weight, with a schedule |
| network while training | fixed | dropout, batch norm |
| gradient | seven lines of numpy | loss.backward() |
composed nonlinear layers
unchanged from lecture 5
cross-entropy, squared error, plus \(\lambda \sum w^2\)
the penalty of lecture 2
momentum, Adam
with a schedule, in PyTorch
All three books are free to read online.
Two moons and Fashion-MNIST: backpropagation in numpy, then the same network in PyTorch, trained with the loop of today and regularised with dropout and weight decay.
It uses lectures 5 and 6.
Convolutional neural networks: structure for images.