Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 15 — Implementation: Neural Networks from Scratch and in PyTorch

Open in Colab

We build a neural network from scratch in NumPy, check that our backpropagation is right, and then do the same work in PyTorch on handwritten digits.

Contents

  1. The perceptron, and why it fails on XOR

  2. A multilayer perceptron in NumPy, with backpropagation

  3. Gradient checking: is backpropagation right?

  4. Learning a curved boundary

  5. Optimisers compared: SGD, momentum, Adam

  6. PyTorch: handwritten digits, overfitting, dropout and early stopping

1. The Perceptron

AND: predictions [0 0 0 1], targets [0 0 0 1]  ->  learned
OR : predictions [0 1 1 1], targets [0 1 1 1]  ->  learned
XOR: predictions [1 1 0 0], targets [0 1 1 0]  ->  FAILED

AND and OR are linearly separable; XOR is not, and the perceptron keeps cycling forever.

2. A Multilayer Perceptron in NumPy

A network with one hidden ReLU layer and a sigmoid output, trained with binary cross-entropy. The backward method is a direct transcription of the chapter’s equations, for a whole batch at once (examples are rows).

XOR predictions: [0.001 1.    1.    0.   ]
<Figure size 700x400 with 1 Axes>

3. Gradient Checking

Backpropagation bugs are silent: the network trains, just badly. We compare each gradient with a numerical estimate L(w+ϵ)−L(w−ϵ)2ϵ\frac{L(w + \epsilon) - L(w - \epsilon)}{2\epsilon}.

largest relative difference: 1.04e-08  (below 1e-6: backpropagation is right)

4. Learning a Curved Boundary

Logistic regression can only draw a line through the two interleaving “moons”; a small MLP bends its boundary around them.

training accuracy: 0.968
<Figure size 700x400 with 1 Axes>

5. Optimisers Compared

The same network and data, trained with three optimisers written in a few lines each.

<Figure size 700x400 with 1 Axes>

6. PyTorch: Handwritten Digits

scikit-learn’s digits dataset: 1 797 images of 8×8 pixels, digits 0–9. Small enough to train in seconds on a laptop CPU.

1149 training, 288 validation, 360 test images
<Figure size 1000x160 with 8 Axes>

Autograd computes the same gradients as our hand-written backpropagation:

y_hat = 0.580, loss = 0.0883
dL/dW2 = [-0.0661 -0.0563]   dL/dW1 = [-0.0164  0.0152] (first column; the second is 0)

These are exactly the numbers of the chapter’s worked example. Now a real training loop, with a validation curve:

<Figure size 1200x380 with 2 Axes>
validation accuracy: plain 0.969   regularised 0.983

Without regularisation, the training loss goes to almost zero while the validation loss creeps back up: overfitting. With dropout, weight decay and early stopping, the validation loss stays low and the validation accuracy is higher. Finally, the test set, once:

test accuracy of the regularised network: 0.975
<Figure size 800x180 with 6 Axes>

Key Takeaways

  • One neuron draws one line; a hidden layer lets the network combine lines into any shape.

  • Backpropagation is the chain rule run backwards; gradient checking proves an implementation right.

  • Momentum and Adam reach a low loss much faster than plain SGD.

  • PyTorch’s autograd gives the same gradients as the hand-derived equations, and the training loop is always: forward, loss, zero_grad, backward, step.

  • Watch the validation curve: dropout, weight decay and early stopping stop the network memorising.