Paul's Python CoursePPC

Project 5 of 14, for Paul

PyTorch Fundamentals

Take It Home: the digit recogniser rebuilt in PyTorch on your own computer, with tensors, autograd, nn.Module and a training loop, checked by a real pytest suite.

About 2 hours, in 9 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

  • PaulNearly everyone out there trains their networks in PyTorch, and I'd like to know if they're right to.
  • PaulYour NumPy network reads the digits. Build the same one in PyTorch at home and see if it agrees.
  • CaitlinWait, PyTorch does the backward pass for you? Then the cards were basically a waste of a week.
  • PaulThe cards are how you'll know what it's doing when it goes wrong, though.

On your own computer, in reader.py:

  1. to_tensors(X, labels): the greys as a float32 tensor and the labels as int64 (torch.long).
  2. blackboard_gradients(): the blackboard chain from Neural Network from Scratch, in tensors made with requires_grad=True. After backward(), return dL/dw1 and dL/dw2 as plain floats.
  3. DigitReader(hidden=32), an nn.Module: self.hidden is nn.Linear(64, hidden) and self.out is nn.Linear(hidden, 10), with a ReLU between. forward returns the raw scores, with no softmax.
  4. train(model, X, labels, epochs, batch_size, rate, seed): Adam and nn.CrossEntropyLoss, in mini-batches shuffled by a torch.Generator seeded with seed. It returns the loss on every row of X after each epoch, as floats.
  5. accuracy(model, X, labels): the fraction of rows whose biggest score is on the right digit, as a float, worked out under torch.no_grad().
  6. python reader.py learns from the same 1500 digits as the Digit Recogniser, and reads the same 297.

Hand in the pytest report when every test passes.

What it prints
(.venv) $ python reader.py
Loss: 0.481 after the first epoch, 0.035 after the last
Read 291 of 297 digits it had never seen

What you learn

What's in it

  1. Tensors remember too
  2. A network as an object
  3. Zero, forward, loss, backward, step
  4. Softmax twice
  5. Your network, in PyTorch's words
  6. How Paul would do it
  7. The digit reader, at home
  8. Ship it