The network
A neural network wires simple neurons together in layers. Ours has an input layer of 2, a hidden layer of 2 and an output layer of 1. Each link carries a weight: the signal travelling along it is multiplied by that number.
The task is XOR: answer 1 when exactly one input is 1, otherwise 0. No single neuron can learn it, because no one straight line splits the 1s from the 0s. A hidden layer can: its neurons learn useful in-between features.
Forward pass
Forward pass, with input (1, 1). Each hidden neuron multiplies every input by its weight, adds them up, then adds its bias. h1: 1×1 + 1×1 + 0 = 2. h2: 1×1 + 1×1 − 1 = 1.
Next each neuron applies its activation function. Ours is ReLU: keep a positive sum, turn a negative one into 0. Both sums are positive, so h1 = 2 and h2 = 1. For input (0, 0), h2's sum, −1, would become 0.
The output neuron does the same with the hidden values: 2×1 + 1×(−1) + 0 = 1. So the network answers 1 for (1, 1), but XOR says 0: it is wrong. Its weights are not trained yet.
Learning
The loss measures how wrong the answer is. We use half the squared error, (y − t)² / 2, where t = 0 is the target. (1 − 0)² / 2 = 0.5. Learning means changing the weights so the loss gets smaller.
Backpropagation sends the error, y − t = 1, backwards. Each weight's gradient is the error reaching its neuron times the signal it carried: 1 × 2 = 2 for h1's output weight. The chain rule passes the error back through every weight.
Gradient descent then moves every weight against its gradient, scaled by the learning rate 0.05: 1 − 0.05 × 2 = 0.9. The hidden weights become 0.95 and 1.05. Run (1, 1) again: the output is now 0.41, closer to 0.
Training repeats this for every example, again and again. After 200 passes (epochs) over the four examples, the loss for a pass falls from 0.5 to 0.000047, and the outputs are 0, 1, 1, 0: the network has learned XOR.
Deep learning runs this same loop, forward, loss, backward, update, on networks with many hidden layers and millions or billions of weights: GPT-3 has 175 billion. Libraries such as PyTorch work out every gradient automatically.
What happens
;; step 1/10 · layers
input layer x1, x2 the numbers we feed in
hidden layer h1, h2 neither input nor answer
output layer y the network's answer
each neuron: sum of (input x weight) + bias,
then its activation function
links: 6 weights, plus 3 biases (h1, h2, y)
The starting weights are the XOR solution from the Deep Learning book (section 6.1) with one output weight changed from −2 to −1, so the numbers stay simple. Real networks start from small random weights. This network updates after every example (stochastic gradient descent). Large networks usually average the gradient over a small batch of examples first.