Week 05 · Minibatches, momentum, and Adam

Compare optimizers at the same update count and see why learning rate still matters.

← Week 4 · Subject contents · Week 6 →

Compare optimizers at the same update count and see why learning rate still matters.

Work through the problem

A minibatch gradient averages derivatives from the selected rows. Momentum accumulates past gradients, making consecutive updates less sensitive to one noisy batch. Adam maintains moving estimates of the first and second gradient moments and divides the bias-corrected mean by the square root of the bias-corrected second moment plus ε.

For L(w)=w²/2 at w=2, SGD with η=0.1 takes the first step to 1.8. With β₁=0.9 and β₂=0.999, Adam’s first bias-corrected moments are 2 and 4. The first step is about 0.1, taking w to 1.9. Equal nominal rates can produce different step sizes.

Run the Python lab

import torch
from torch import nn
targets = [0.,4.,1.,3.]
for name, constructor in [("SGD",torch.optim.SGD),("Momentum",lambda p,lr:torch.optim.SGD(p,lr,momentum=.9)),("Adam",torch.optim.Adam)]:
    w = nn.Parameter(torch.tensor(5.))
    opt = constructor([w],lr=.1)
    for t in targets*8:
        opt.zero_grad()
        ((w-t)**2/2).backward()
        opt.step()
    print(name,round(w.item(),3),"full loss",round(sum((w.item()-t)**2/2 for t in targets)/4,3))

Output from the lab

SGD 2.177 full loss 1.266
Momentum 1.75 full loss 1.281
Adam 2.69 full loss 1.488

Practice

  1. Why feed each optimizer the same batch order?

Check your reasoning

  1. Changing batch order changes the noise in its updates and confounds the comparison.

← Week 4 · Subject contents · Week 6 →

Further reading · Goodfellow, Bengio, and Courville · Deep Learning