How To Make a Neural Net Learn
Everyone says neural nets "learn." But what does that actually mean? I wanted to stop nodding along, so I built one from scratch: no PyTorch, no TensorFlow, just ~40 lines of Python and NumPy.
Here's the short answer: a neural net learns by guessing, measuring how wrong it was, and nudging its numbers to be a little less wrong. Then it repeats that thousands of times.
That's it. Everything else is detail.
The Problem: XOR
I needed a problem small enough to understand and hard enough to be interesting. XOR is the classic one. It takes two inputs and outputs 1 only if exactly one of them is 1.
Input A Input B → Output
0 0 → 0
0 1 → 1
1 0 → 1
1 1 → 0
Why XOR? You can't solve it by drawing a single straight line between the 0s and the 1s. A single neuron can only draw straight lines, so it fails. You need a hidden layer. This is the problem that famously stalled neural network research in 1969.
B
↑
1 | 1 0
|
|
0 | 0 1
└──────────────────→ A
0 1
No single straight line separates the 1s from the 0s.
The Network
The network is tiny: 2 inputs, 4 hidden neurons, 1 output.
Inputs Hidden Output
(A) ───┬───→ ( h1 ) ───┐
├───→ ( h2 ) ───┤
├───→ ( h3 ) ───┼───→ (prediction)
(B) ───┴───→ ( h4 ) ───┘
weights W1 weights W2
Every arrow is a weight: just a number. At the start, those numbers are random, so the network's guesses are garbage. "Learning" means finding the right numbers.
Each neuron does two things:
- Takes a weighted sum of its inputs (plus a bias, a constant offset)
- Squashes that sum between 0 and 1 using a sigmoid function
sigmoid(z) = 1 / (1 + e^(-z))
1 | ╭──────────
| ╭─╯
0.5 | ╭─╯
| ╭─╯
0 | ─────────╯
└──────────────────────────→ z
0
The squashing is what lets the network bend lines. Without it, stacking layers would just collapse into one big straight line again.
The Learning Loop
Learning is four steps, repeated over and over:
┌──────────────────────────────────────────────┐
│ │
↓ │
1. Forward → 2. Loss → 3. Backward → 4. Update
(guess) (how wrong?) (who's to blame?) (nudge weights)
1. Forward: make a guess. Push the inputs through the network and get a prediction.
2. Loss: measure how wrong it was. Compare the prediction to the right answer. I used mean squared error: take the difference, square it, average it. A loss of 0 means perfect.
3. Backward: figure out who's to blame. This is backpropagation. For every weight, it asks: "If I nudged this weight up a tiny bit, would the loss go up or down, and by how much?" That answer is called the gradient. It works backwards from the output using the chain rule from calculus. The output layer's error gets passed back to the hidden layer, split up according to how much each weight contributed.
4. Update: nudge every weight downhill. Move each weight a small step in the direction that lowers the loss. This is gradient descent. The size of the step is the learning rate.
The best mental image I found: you're blindfolded on a hilly landscape, and you want to reach the lowest valley. You can't see, but you can feel which way the ground slopes under your feet. So you take a step downhill. Then another. The loss is your altitude. The gradient is the slope under your feet.
Loss
↑
| • ← start (random weights)
| ╰╮
| ╰╮
| ╰╮ step, step, step...
| ╰─╮
| ╰──╮
| ╰────• ← trained
└──────────────────────────→ Weight
The Code
Here's the whole thing:
import numpy as np
# The data: XOR
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# The network: 2 inputs -> 4 hidden neurons -> 1 output
rng = np.random.default_rng(0)
W1 = rng.normal(size=(2, 4))
b1 = np.zeros((1, 4))
W2 = rng.normal(size=(4, 1))
b2 = np.zeros((1, 1))
def sigmoid(z):
return 1 / (1 + np.exp(-z))
learning_rate = 1.0
for step in range(5001):
# 1. Forward: make a guess
h = sigmoid(X @ W1 + b1)
pred = sigmoid(h @ W2 + b2)
# 2. Loss: how wrong was the guess?
loss = np.mean((pred - y) ** 2)
# 3. Backward: who's to blame?
d_pred = 2 * (pred - y) / len(X)
d_z2 = d_pred * pred * (1 - pred)
d_W2 = h.T @ d_z2
d_b2 = d_z2.sum(axis=0, keepdims=True)
d_h = d_z2 @ W2.T
d_z1 = d_h * h * (1 - h)
d_W1 = X.T @ d_z1
d_b1 = d_z1.sum(axis=0, keepdims=True)
# 4. Update: nudge every weight downhill
W2 -= learning_rate * d_W2
b2 -= learning_rate * d_b2
W1 -= learning_rate * d_W1
b1 -= learning_rate * d_b1
if step % 1000 == 0:
print(f"step {step:>4} loss {loss:.4f}")
print(pred.round(2))
A few lines worth explaining:
X @ W1is matrix multiplication: every input times every weight, summed up, for all four examples at once.pred * (1 - pred)is the derivative of the sigmoid. It's one of the reasons sigmoid was popular: its slope is easy to compute from its own output.d_z2 @ W2.Tis the moment of backpropagation: the output's error flows backwards through the same weights to the hidden layer.
The Result
step 0 loss 0.3430
step 1000 loss 0.0237
step 2000 loss 0.0033
step 3000 loss 0.0016
step 4000 loss 0.0011
step 5000 loss 0.0008
The loss drops from 0.34 (basically guessing) to 0.0008. And the final predictions:
Input Target Prediction
(0, 0) 0 0.01
(0, 1) 1 0.97
(1, 0) 1 0.97
(1, 1) 0 0.04
It learned XOR. Nobody told it the rule. It found a set of 17 numbers that encode it, just by being wrong 5,000 times and correcting a little each time.
What I Took Away
1. "Learning" is just optimization. No magic. A neural net is a function with knobs, and training is turning the knobs to reduce error. The intelligence, if you want to call it that, comes from scale: more knobs, more data, more steps.
2. Backprop is the whole trick. Computing the gradient for every weight efficiently, in one backwards pass, is what makes training possible. Without it you'd have to test each weight one at a time.
3. The same loop scales up. GPT-style models use the exact same four steps: forward, loss, backward, update. The differences are the architecture (transformers instead of 4 sigmoid neurons), the loss (predicting the next word), and the scale (billions of weights instead of 17). Modern frameworks like PyTorch just compute step 3 for you automatically.
Things to try if you run it yourself:
- Set
learning_rate = 0.01. After 5,000 steps it's still stuck guessing 0.5 for everything. The steps are too small. - Set
learning_rate = 50. Surprisingly, it still works on XOR. On bigger problems, steps that large usually overshoot the valley and the loss blows up. - Change the hidden layer to 1 neuron. It can't solve XOR anymore, and the loss stalls around 0.24.
- Change the random seed. It finds a different set of weights that also works.
Further reading:
- Neural Networks: Zero to Hero by Andrej Karpathy
- 3Blue1Brown: Neural Networks
- Neural Networks and Deep Learning by Michael Nielsen