Paul's Python CoursePPC

Project 3 of 14, for Neil

Optimiser Benchmark

A time trial for optimisers. One network, one start, one log of 800 evenings, and three optimisers written from scratch: plain SGD, momentum and Adam, compared fairly, then Adam again from all zeros.

About an hour and a half, in 12 steps.

Sign up free to open itLog in

Act 7 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • NeilMy network learnt Paul's whole log the plain way, and it did get there, eventually.
  • NeilSo let's have a time trial with the same network, start and batches, and whoever's fastest down the loss wins.
  • YahyaI'm calling it now, Adam wins.

The network from Neural Network from Scratch is in brain.py: forward, loss, backward, and batches, mended from Caitlin's version. In optimisers.py, plain SGD is already written, as the pattern.

  1. init_params(n_in, n_hidden, n_out, rng): W1 from rng.normal(0, np.sqrt(2 / n_in), (n_in, n_hidden)), then W2 from rng.normal(0, np.sqrt(1 / n_hidden), (n_hidden, n_out)), in that order. Both biases start at zeros. It returns the dict.
  2. Momentum(rate, beta=0.9): its step(params, grads) keeps a velocity for every weight, starting at zeros. Each step, velocity = beta * velocity + gradient, then the weight moves by rate times the velocity.
  3. Adam(rate=0.001, beta1=0.9, beta2=0.999, eps=1e-8): its step(params, grads) is Adam, as in its Learn step.
  4. train(X, T, params, optimiser, epochs, batch_size, rng): each epoch, for each batch from batches(X, T, batch_size, rng), forward and backward on that batch alone, then optimiser.step. After each epoch, the loss on every row of X. It changes params in place and returns the losses.
  5. Run as a program, it trains the network on all eight hundred evenings with each optimiser from the same start, then once from all zeros.
What it prints
From small random weights, 30 epochs in batches of 32:
sgd       loss 0.0468, every answer right on 89% of evenings
momentum  loss 0.0119, every answer right on 96% of evenings
adam      loss 0.0092, every answer right on 97% of evenings
From every weight at 0:
adam      loss 0.1756, every answer right on 40% of evenings

What you learn

What's in it

  1. Gathering speed
  2. The long gentle slope
  3. How Paul would do it
  4. Adam
  5. Adam's first step
  6. A handful at a time
  7. Fix Caitlin's version
  8. Where the weights start
  9. Sixteen of the same
  10. Training properly
  11. Ship it