Neural networks,
from scratch.
Six chapters that build a neural network one idea at a time, from a single artificial neuron up to a multi-layer network that learns a spiral. Every number is computed live in your browser and shown to you. There's no library and no black box: if you can multiply and add, you can follow every step.
One neuron: a weighted vote
Strip away the biology metaphors. An artificial neuron is just this:
- Multiply every input by its own weight. The weight says how much that input matters, and whether it pushes the answer up (positive) or down (negative).
- Add it all up, plus one extra number called the bias. The bias is the neuron's default leaning, what it says before it has seen any evidence. Call the total
z. - Squash
zthrough an activation function. The step function answers a hard yes/no (1 ifz ≥ 0, else 0). The sigmoidσ(z) = 1 / (1 + e−z)answers softly with a number between 0 and 1 that you can read as confidence.
With two inputs, every possible input is a point on a plane, and the neuron colours that plane. Look at what z = 0 describes: w₁x₁ + w₂x₂ + b = 0 is the equation of a straight line. Points on one side get z > 0 (orange, "yes"); points on the other get z < 0 (blue, "no").
(w₁, w₂) always points perpendicular to it, towards "yes". The bias slides the line without rotating it. Bigger weights don't move the line. They make the transition sharper, so the neuron gets more confident.Try this
- Drag the white diamond around the plane and watch
zand the output change. The output only depends on which side of the line you're on and how far away. - Set
w₂ = 0. The line goes vertical, because the neuron now ignoresx₂entirely. - Move only
b. The line slides parallel to itself. - With sigmoid on, double both weights (and the bias). The line stays put, but the soft orange/blue fade becomes a knife edge.
- Flip the sign of every weight and the bias. Same line, opposite colours.
The perceptron learns from its mistakes
In chapter 1 you set the weights by hand. Learning means letting the data set them. Frank Rosenblatt's perceptron (1958) does it with a rule simple enough to do on paper. Show it one example at a time:
- If its guess
ŷis right, change nothing. - If it's wrong, nudge each weight by
η · (y − ŷ) · xᵢ, and the bias byη · (y − ŷ).
Here y is the correct answer (0 or 1), ŷ is the guess, and η (eta) is the learning rate, the size of each nudge. The error y − ŷ is only ever +1 (said no, should have said yes), −1 (said yes, should have said no), or 0.
Why does that work? If the neuron said "no" to a "yes" example, adding η·x to the weights makes w·x bigger next time, because x·x is always positive. The line rotates and slides towards putting that point on the right side. Each mistake drags the line a little towards fixing itself.
One pass through the whole dataset is an epoch. When a full epoch goes by with zero mistakes, the perceptron has converged, and it will never change again.
Try this
- On AND, press Step a few times and read each log entry. Check that the arithmetic matches the rule above.
- Try OR and NAND. Different gates, same algorithm, different line.
- Pick Random, then click the plane to add points of either class. As long as a line can split them, it still converges.
- Now pick XOR and press Play. Watch it never settle. Can you draw one straight line that puts (0,1) and (1,0) on one side and (0,0), (1,1) on the other?
- Set η very small or very large. For the perceptron it barely matters (it scales everything equally). In chapter 4 it will matter a lot.
The XOR wall, and how layers climb it
XOR ("one or the other, but not both") is the simplest function a single neuron cannot learn. The two "yes" points sit on opposite corners, and no straight line separates them from the two "no" corners. In 1969 Minsky and Papert made this limitation famous, and neural-network research went quiet for over a decade.
The way out: stack neurons. Put two neurons in a hidden layer and feed their outputs into a third one:
h₁learns OR: "at least one input is on".h₂learns NAND: "not both inputs are on".- The output learns AND of those two. "At least one, but not both" is exactly XOR.
Each neuron is still drawing a single line. The trick is where the output neuron draws its line. It doesn't look at (x₁, x₂). It looks at (h₁, h₂), a brand-new coordinate system the hidden layer invented.
Notice that the activation function is what makes this possible. Without the squashing non-linearity, a layer of neurons is just a linear transformation, and stacking linear transformations gives you another linear transformation, still one straight line. Set the activation to a pure linear one in the playground later and see networks lose their power.
Try this
- Slide morph from 0 to 1, slowly. Watch (0,1) and (1,0) collide while (0,0) and (1,1) stay apart.
- Press Scramble, then try to solve XOR by hand with the nine sliders. Hint: get the two dashed lines (the hidden neurons) to cut off opposite corners first.
- Switch to step activation. In hidden space the four points collapse onto just three corners of a square.
Gradient descent: learning as walking downhill
The perceptron rule only works for a single step-function neuron. For networks with many layers we need a more general recipe, and it is the recipe behind essentially every neural network trained today, ChatGPT included.
Step 1: measure how wrong you are with one number. That number is the loss. Here the model is a line ŷ = w·x + b fitted to some points, and the loss is the mean squared error: the average of (ŷ − y)² across all points. Those are the dashed purple gaps in the left chart, squared.
Step 2: see the loss as a landscape. Every choice of (w, b) gives a loss. The right chart shows all of them at once, with darker meaning higher loss. Training means finding the lowest point in this landscape (marked ✕).
Step 3: walk downhill. You can't see the whole landscape in a real network (it has billions of dimensions), but you can compute the gradient: the slope under your feet. ∂L/∂w says "if I nudge w up a tiny bit, the loss changes by this much". The gradient points uphill, so step the other way:
w ← w − η · ∂L/∂w b ← b − η · ∂L/∂b
Repeat. That's it. That is "training".
b direction. In real networks, finding a good η is half the craft.Try this
- Press Step and read the numbers. Check the update: new w = old w − η × gradient.
- Click anywhere on the landscape to start from there. Every start rolls to the same ✕. This loss is a perfect bowl (it's convex). Neural network losses are not, and that is where it gets interesting.
- Set η ≈ 0.9 and watch it zig-zag across the valley. Then try 1.1.
- Set η = 0.01 and press Play. Notice how the steps shrink near the bottom: the slope flattens, so the gradient (and the step) gets small on its own.
Backpropagation, one number at a time
Gradient descent needs ∂L/∂(every weight). In chapter 4 there were two weights and we could write the formulas by hand. A real network has millions, buried several layers deep. How much is a weight in the first layer to blame for an error measured at the end?
Backpropagation answers that with the chain rule from calculus. If A affects B and B affects C, then how C responds to A = (how C responds to B) × (how B responds to A). Errors are computed at the output and passed backwards through the network, multiplying by one local slope per step, so every weight gets its share of the blame in a single sweep.
Below is the XOR network from chapter 3 (2 inputs → 2 hidden → 1 output, all sigmoid), but this time it starts with random weights and has to learn them. Press Next and walk through one full training step: forward pass, loss, backward pass, update. Every number is the real one.
z moved slightly. Then:∂L/∂(weight) = δ of the neuron it feeds into × value flowing through itδ of a hidden neuron = (Σ δ downstream × weight to it) × slope of its activationThat's all of backprop. Everything else is bookkeeping.
Try this
- Click Next through all 10 phases for one sample. At phase 9, compare the analytic gradients with the numeric "nudge it and see" ones. They match, and that's how you know backprop is right.
- Notice the factor
ŷ(1−ŷ). It's at most 0.25, and it shrinks every time you go back a layer. Stack 10 sigmoid layers and the gradient reaching the first layer is tiny. That's the vanishing gradient problem, and the reason modern networks use ReLU. - Press Train 2,000 epochs and watch XOR get solved. Sometimes it gets stuck near loss 0.125 or so: a local minimum. Press New random weights and try again.
Playground: train a real network
Same machinery, scaled up: any number of layers and neurons, mini-batch gradient descent, backprop through all of it. The only new pieces are the ones every real network uses:
- Activations:
tanh(like sigmoid but centred on 0) andReLU(max(0, z), the default today, cheap and resistant to vanishing gradients). The output neuron is always sigmoid, to give a probability. - Cross-entropy loss
−[y·log ŷ + (1−y)·log(1−ŷ)]instead of squared error. It punishes confident wrong answers brutally, and it makes the output δ simplyŷ − y. - Mini-batches: estimate the gradient from 10 random points at a time instead of all of them. It's noisier, but you get many more steps for the same compute.
- Train vs. test: 30% of the points are hidden from training (hollow dots). If train loss keeps falling while test loss rises, the network is memorising noise instead of learning the pattern. That's overfitting.
Try this
- Circle with 0 hidden layers: the network can't do it (it's one neuron, one line). Add 1 layer with 3 neurons and it can.
- Spiral: it needs depth. Try 3 layers × 6 neurons with ReLU or tanh, η = 0.03.
- Set η = 3 on anything and watch the loss explode or oscillate, just like chapter 4.
- Turn noise up to 0.5 and use a big network (4 × 8). Watch the test loss line separate from the train loss: overfitting.
- Switch to linear activation with several layers. However deep, the boundary stays a straight line, as promised in chapter 3.
The whole story on one page
Neuron
z = Σ wᵢxᵢ + b, then output = f(z). A weighted vote plus a default leaning, squashed.
One neuron = one line
The decision boundary z = 0 is a straight line (hyperplane). Weights set its angle, bias its position.
Perceptron rule
On a mistake: w ← w + η(y − ŷ)x. Guaranteed to converge if the data is linearly separable. Hopeless on XOR.
Hidden layers
Each layer re-represents the data in new coordinates, so a straight line in the last layer can be any curve in the input.
Non-linearity is essential
Without activation functions, any stack of layers collapses into a single linear layer.
Loss
One number measuring wrongness: squared error for numbers, cross-entropy for probabilities. Training means making it small.
Gradient descent
θ ← θ − η·∂L/∂θ. Step against the slope. Learning rate too small = slow, too big = divergence.
Backpropagation
The chain rule, applied from the output backwards. δ per neuron; ∂L/∂w = δ(target) × input value. One backward sweep gets every gradient.
Vanishing gradients
Sigmoid's slope ≤ 0.25 multiplies at every layer. ReLU (slope 1 when active) keeps deep networks trainable.
Generalisation
The goal isn't low training loss, it's low loss on data the network has never seen. Watch the test curve.
From here to ChatGPT
Everything a frontier model does still rests on these pieces: neurons computing weighted sums, non-linear activations, a loss, gradients via backprop, and some flavour of gradient descent. What changes is scale and plumbing:
- Softmax output: instead of one sigmoid ("yes or no"), a probability over many classes, like 100,000 possible next words.
- Better optimisers (Adam): gradient descent with momentum and a per-weight adaptive learning rate.
- Architectures that wire neurons smartly: convolutions (reuse the same small weights across an image), attention/transformers (let every word decide which other words to look at).
- Embeddings: words turned into vectors of numbers, so they can be inputs
xlike the ones here. This is chapter 3's "new coordinate system" idea again, learned at enormous scale. - Scale: billions of weights, trillions of training examples, thousands of GPUs. Same
w ← w − η·∂L/∂w.