← Mike Builds Things
An interactive notebook

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.

CHAPTER 01

One neuron: a weighted vote

Strip away the biology metaphors. An artificial neuron is just this:

  1. 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).
  2. 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.
  3. Squash z through an activation function. The step function answers a hard yes/no (1 if z ≥ 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").

Key insight. A single neuron can only ever draw one straight line (a flat plane in 3D, a "hyperplane" in more dimensions). The weights set the line's angle: the arrow (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

  1. Drag the white diamond around the plane and watch z and the output change. The output only depends on which side of the line you're on and how far away.
  2. Set w₂ = 0. The line goes vertical, because the neuron now ignores x₂ entirely.
  3. Move only b. The line slides parallel to itself.
  4. With sigmoid on, double both weights (and the bias). The line stays put, but the soft orange/blue fade becomes a knife edge.
  5. Flip the sign of every weight and the bias. Same line, opposite colours.
Input space: horizontal axis = x₁, vertical = x₂. Colour = neuron output. Solid line = where z = 0. Arrow = weight vector. Click or drag to move the input.

      
Activation
Weights & bias
Input
CHAPTER 02

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.

The perceptron convergence theorem. If any straight line can separate the two classes, this rule is guaranteed to find one in a finite number of steps. And if no such line exists, it will thrash forever. Hold that thought.

Try this

  1. On AND, press Step a few times and read each log entry. Check that the arithmetic matches the rule above.
  2. Try OR and NAND. Different gates, same algorithm, different line.
  3. Pick Random, then click the plane to add points of either class. As long as a line can split them, it still converges.
  4. 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?
  5. Set η very small or very large. For the perceptron it barely matters (it scales everything equally). In chapter 4 it will matter a lot.
Click the plane to add a point of class:
Mistakes per epoch
Update log (newest first)
CHAPTER 03

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.

Key insight. This is the whole idea of deep learning. Each layer re-represents the data so the next layer's job becomes easier. Drag the morph slider: every point (and the whole grid of space) moves from its input coordinates to its hidden-layer coordinates. The plane gets bent and folded until the two orange points land together on one side, and a single straight line can finish the job.

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

  1. Slide morph from 0 to 1, slowly. Watch (0,1) and (1,0) collide while (0,0) and (1,1) stay apart.
  2. 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.
  3. Switch to step activation. In hidden space the four points collapse onto just three corners of a square.
morph0.00
Hidden neuron h₁ (dashed line)
Hidden neuron h₂ (dashed purple line)
Output neuron (looks at h₁, h₂)
CHAPTER 04

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".

The learning rate η is the most important knob. Too small and you crawl. Too big and you overshoot the valley, bounce from wall to wall, and can even fly off to infinity (divergence). Here it diverges above roughly η ≈ 1, because the landscape is steepest in the b direction. In real networks, finding a good η is half the craft.

Try this

  1. Press Step and read the numbers. Check the update: new w = old w − η × gradient.
  2. 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.
  3. Set η ≈ 0.9 and watch it zig-zag across the valley. Then try 1.1.
  4. 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.
Data & current line
Loss landscape: w →, b ↑. Click to start here.
η

        
CHAPTER 05

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.

The one pattern to remember. For every neuron, backprop computes its δ (delta), meaning how much the loss would change if that neuron's sum 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 activation

That's all of backprop. Everything else is bookkeeping.

Try this

  1. 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.
  2. 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.
  3. 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.
Training sample
η2.0
Average loss over the 4 XOR samples, per epoch. One epoch = one backprop + update per sample.
CHAPTER 06

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) and ReLU (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.
Read the little squares. Each neuron in the diagram is drawn as a tiny map of the input plane, showing what that neuron responds to. First-layer neurons can only ever draw a single line, the same as chapter 1. Each later layer combines the maps before it into curves, rings and spirals. You're watching features get built from simpler features.

Try this

  1. 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.
  2. Spiral: it needs depth. Try 3 layers × 6 neurons with ReLU or tanh, η = 0.03.
  3. Set η = 3 on anything and watch the loss explode or oscillate, just like chapter 4.
  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.
  5. Switch to linear activation with several layers. However deep, the boundary stays a straight line, as promised in chapter 3.
Dataset
noise0.10
Hidden layers
Activation
Learning rate η
epoch 0
Lines = weights (orange positive, blue negative, thickness = size). Squares = what each neuron outputs across the input plane.
train loss –
test loss –
Solid = train loss, dashed = test loss.
SUMMARY

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 x like 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.