Paul's Python CoursePPC

Project 1 of 14, for Aaesha

Neural Network from Scratch

A two-layer network in NumPy that learns how Paul makes three calls every evening: one neuron and its limits, the forward pass, backpropagation on paper and in code, every gradient checked by measurement, then trained and tested on evenings it never saw.

About 3 hours, in 21 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

  • AaeshaWelcome to the Engine Room! Paul's logged the tower's lights, beacon and shutters every evening for years.
  • AaeshaI want to know if a network can learn how he decides, just the how, never mind the why.
  • NeilI once trained a small one on his log, four readings in and three answers out, and I only kept the weights.
  • AaeshaAnd I've already written a gradient checker.

Paul's log, evenings.csv, has 800 evenings. Each is four readings from 0 to 1, visibility, wind, rain and dark, and three answers: whether the clock-face lights came on, the beacon flashed and the storm shutters closed. Neil's network has a hidden layer of five neurons and an output layer of three, with its weights in a dict under "W1", "b1", "W2" and "b2".

  1. In network.py: relu, sigmoid, and forward(X, params), which returns the answers for every row of X and a dict of the values on the way. Then decisions, which names the answers above 0.5. Run as a program, it puts four evenings through Neil's weights.
  2. In learn.py: backward, which works out how the mean squared error changes with every weight and bias, with no loops; check_gradients, which compares each one with a measured slope; and train, which walks downhill.
  3. Run as a program, learn.py checks every gradient, trains a network from random weights on 600 evenings, tests it on the other 200, and answers for tonight.
What it prints
Gradients: W1 ok, b1 ok, W2 ok, b2 ok
Loss: 0.2952 at the start, 0.0051 at the end
All three right on 195 of 200 evenings it never saw
Tonight: lights, beacon, shutters

What you learn

What's in it

  1. One neuron
  2. Learning from mistakes
  3. One neuron, two nights
  4. One neuron, one straight line
  5. The stairs light
  6. A layer of neurons
  7. Which way round
  8. Bend and squash
  9. Two lines for the stairs light
  10. Fix Caitlin's version
  11. The forward pass
  12. Passing the blame back
  13. Blame, on paper
  14. Checking by measuring
  15. Your turn, on paper
  16. The same, in matrices
  17. Sure, and wrong
  18. Fix Aaesha's version
  19. Learning backwards
  20. Ship it