What this is
What is a neural network?
A neural network is a program that learns a task from examples instead of following rules a person wrote down. It is built from many tiny units, loosely inspired by the brain, each of which takes in numbers, weighs them, and passes a number on. Chatbots, image generators and translation tools are all neural networks, mostly very large ones.
Why it matters: The first time you train an AI model instead of calling a finished one, the config asks for epochs, a batch size and an activation, and the loss curve may refuse to move. Knowing which part of training each setting controls tells you which one to change.
At a glance
Key takeaways
- A neuron multiplies each input by a weight, adds the products and a bias, and passes the total through an activation function. A layer is many neurons computed at once as a matrix multiply, and a neural network is layers stacked.
- Without an activation between them, stacked layers collapse into one layer, so extra depth adds nothing.
- Training repeats one loop: predict, measure the loss, find every weight's gradient by backpropagation (the chain rule), and step each weight against it.
- Backpropagation reuses the values computed on the way forward, so training needs more memory than inference.
How it works, from scratch
A neural network turns its inputs into an answer using a long list of numbers called weights. The weights start out random, so the first answers are wrong, and training changes each one a little at a time in whichever direction makes the answers less wrong.
Chapter 1
Learning with one weight
Take a model with one weight, w, that predicts y = w·x. It should learn y = 3x, and its one training example is x = 1, y = 3. How wrong it is at any setting of w is measured by the loss, here the squared miss (w·1 − 3)², which is 0 at w = 3 and grows on either side.
To improve, the model needs to know which way to turn w. The derivative, or slope, of the loss with respect to a weight answers that: if the weight goes up a tiny bit, does the loss go up or down, and how fast? Here the slope is 2(w − 3). A model with many weights has one slope per weight, and the list of them is the gradient. Moving each weight against its slope moves the loss downhill. (Math notation, from zero explains every symbol used here.)
Start at w = 0 and step against the slope with step size 0.25:
| step | w | slope 2(w − 3) | new w = w − 0.25·slope |
|---|---|---|---|
| 0 | 0 | −6 | 1.5 |
| 1 | 1.5 | −3 | 2.25 |
| 2 | 2.25 | −1.5 | 2.625 |
Each step halves the distance to 3. A full-size network trains the same way, around a loop of four steps:
Figure 1 · Diagram
flowchart LR D[Batch of examples] --> F[Forward pass<br/>make predictions] F --> L[Loss<br/>how wrong were we?] L --> B[Backpropagation<br/>gradient per weight] B --> O[Optimizer step<br/>adjust weights] O -->|next batch| D
The step size is called the learning rate, written η. The update rule, applied to every weight at once, is:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| one weight (a knob the model can turn) | 0 at the start | |
| "replace the old value with" (an update, not an equation) | ||
| "eta", the learning rate: how big a step to take | 0.25 | |
| the loss: one number saying how wrong the model is | ||
| the slope of the loss with respect to (the "partial derivative": how the loss changes when only moves) |
In words: "the new weight is the old weight minus the learning rate times the slope of the loss at the old weight."
With the numbers: , the first row of the table.
In Python
w, eta, target = 0.0, 0.25, 3.0
for step in range(3):
# ∂L/∂w for the loss (w - 3)²
slope = 2 * (w - target)
# w ← w - η ∂L/∂w
w = w - eta * slope
print(w) # → 1.5 2.25 2.625
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
The same loop trains a spam filter and the largest language models; what changes is the size of the network, the data and the loss. When a training run misbehaves, the fault is in one of its four steps.
In code: learn_one_weight runs the table, and train runs the loop
for a real network. View source
Chapter 2
A neuron: a weighted sum and a rule
The weight above multiplied a single input. A neuron takes several inputs and multiplies each by its own weight, so an input with a large weight counts for more, and one with a negative weight counts against. It adds the products together with one more number, the bias, a baseline that shifts the total whatever the inputs are. Then it passes the total through a fixed rule, the activation function, which decides what the neuron puts out.
Take inputs (2, 3), weights (0.5, 1.0) and bias 0.5. The weighted sum is 2 × 0.5 + 3 × 1.0 + 0.5 = 4.5. The rule here is ReLU, which passes a positive total through unchanged and turns a negative one into 0, so the output is 4.5.
Figure 2 · Diagram
flowchart LR X1((x1 = 2)) -- "× w1 = 0.5" --> S["Sum + bias<br/>1.0 + 3.0 + 0.5 = 4.5"] X2((x2 = 3)) -- "× w2 = 1.0" --> S B((bias 0.5)) --> S S --> A["Activation φ<br/>ReLU(4.5) = 4.5"] A --> Y((y = 4.5))
A layer is many neurons side by side, each wired to every input, and computing a whole layer for a batch of examples is one matrix multiply (the second formula below). A neural network is layers stacked, each layer's outputs becoming the next layer's inputs. The feed-forward half of every transformer block, which holds most of a language model's parameters, is two such layers.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the -th input | , | |
| the weight on the -th input | , | |
| a counter over the inputs | 1, 2 | |
| "add up the following for every " | ||
| the bias (the baseline added to every sum) | 0.5 | |
| the dot product: multiply matching entries of two lists, then add | ||
| "phi", the activation function | ReLU | |
| the neuron's output | 4.5 | |
| a batch of inputs, one example per row | shape (batch, inputs) | |
| a layer's weights, one column per neuron | shape (inputs, neurons) | |
| matrix multiply: every row of dotted with every column of | shape (batch, neurons) | |
| every neuron's output for every example | shape (batch, neurons) |
In words: "multiply each input by its weight, add them up, add the bias, and pass the total through the activation function."
With the numbers: .
In Python
x = [2, 3]
w = [0.5, 1.0]
b = 0.5
# ReLU: keep positives, zero the rest
def phi(z): return max(0.0, z)
# w · x = Σ_i w_i x_i
sum(w_i * x_i for w_i, x_i in zip(w, x)) # → 4.0
# y = φ(w · x + b)
phi(sum(w_i * x_i for w_i, x_i in zip(w, x)) + b) # → 4.5
In code: MLP.forward computes two of these layers. View source
Chapter 3
Backpropagation: passing the blame backwards
Suppose the right answer for the neuron's inputs (2, 3) was 5. Its output was 4.5, so the loss, the squared miss, is (5 − 4.5)² = 0.25. To reduce it, each of the neuron's three knobs, the two weights and the bias, needs its own slope: how much the loss changes when that knob alone moves. Backpropagation finds every slope by starting at the loss and working backwards.
Think of an assembly line that turned out a faulty product. The inspector at the end measures the fault and passes the complaint back. Each station works out how much of the fault came from what it did, passes the rest further back, and so learns how to adjust its own machine. In the neuron, the loss is the inspector, and the activation and the sum are the stations.
Each row of the table is one link: its local derivative is how much that step scales a change passing through it, and the running blame is the product of the local derivatives from the loss to that point.
| link | local derivative | running blame |
|---|---|---|
| loss → y | 2(y − 5) = −1 | −1 |
| y → z (ReLU, z > 0) | 1 | −1 |
| z → w1 | x1 = 2 | −2 |
| z → w2 | x2 = 3 | −3 |
| z → b | 1 | −1 |
One step with learning rate 0.01 moves the weights to (0.52, 1.03) and the bias to 0.51. The new output is 4.64, and the loss falls from 0.25 to 0.1296. The weight whose input was bigger (3) got the bigger share of the blame and moved more.
Figure 3 · Diagram
flowchart RL L["Loss (5 − y)² = 0.25"] -- "dL/dy = −1" --> Y[y = ReLU z] Y -- "dy/dz = 1" --> Z[z = w·x + b] Z -- "× x1 = 2 → dL/dw1 = −2" --> W1[w1] Z -- "× x2 = 3 → dL/dw2 = −3" --> W2[w2] Z -- "× 1 → dL/db = −1" --> Bb[b]
The formula and its symbols
This is the chain rule: when a change passes through several steps, the overall rate of change is the product of each step's rate of change. If turning a knob moves a gear 3× as fast, and that gear moves a needle 2× as fast, the knob moves the needle 6× as fast.
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the loss | 0.25 | |
| the target (the right answer) | 5 | |
| the neuron's output | 4.5 | |
| the weighted sum before the activation | 4.5 | |
| how the loss changes as the output changes | ||
| how the output changes as the sum changes: the activation's slope | ReLU slope at 4.5 = 1 | |
| how the sum changes as weight changes: just its input | ||
| the activation's derivative (slope) | 1 for ReLU when |
In words: "the blame on a weight is how much the loss cares about the output, times how much the output cares about the sum, times how much the sum cares about that weight."
With the numbers: for : ; for : .
In Python:
x, t, z = [2, 3], 5, 4.5
# ReLU(4.5)
y = max(0.0, z)
# ∂L/∂y
dL_dy = 2 * (y - t)
# φ'(z): ReLU's slope
dy_dz = 1 if z > 0 else 0
# × ∂z/∂w_i = x_i, for w_1 and w_2
[dL_dy * dy_dz * x_i for x_i in x] # → [-2.0, -3.0]
# one step, learning rate 0.01
w = [0.5 - 0.01 * -2.0, 1.0 - 0.01 * -3.0]
b = 0.5 - 0.01 * -1.0
y_new = w[0] * x[0] + w[1] * x[1] + b
# the new output and the smaller loss
round(y_new, 2), round((t - y_new) ** 2, 4) # → (4.64, 0.1296)
PyTorch's loss.backward() does the same for billions of weights: it
records the forward computation and replays it backwards, applying the
chain rule at each step.
In code: one_neuron_worked_example computes every row of the table. View source
Chapter 4
Why the nonlinearity is essential
In the neuron above, ReLU passed 4.5 through unchanged, so the rule seemed to do nothing. It starts to matter once layers are stacked. A layer without an activation is linear: it only multiplies and adds, and two linear layers in a row multiply out to a single linear layer. However many you stack, the result is one layer, and one linear layer can separate two classes only with a straight line. Tinted glass behaves the same way: stack three sheets and you get one darker sheet, and no arrangement of flat panes bends light around a corner. A nonlinear activation between the layers is the bend.
In one dimension: a layer that multiplies by 3, followed by a layer that multiplies by 2, is the same as one layer that multiplies by 6. With a ReLU between them, inputs −1 and 1 give 0 and 6, and no single multiplication does that.
Figure 4 · Diagram
flowchart LR
subgraph NoAct["Without activation"]
direction LR
a1[X] --> a2[·W1] --> a3[·W2] --> a4[·W3] --> a5["= X·(W1W2W3)<br/>one matrix"]
end
subgraph WithAct["With activation"]
direction LR
b1[X] --> b2[·W1] --> b3[φ] --> b4[·W2] --> b5[φ] --> b6[·W3] --> b7[curved<br/>decision boundary]
end
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the inputs | or | |
| two layers' weights | 3 and 2 | |
| the two layers multiplied into one | 6 | |
| an activation between the layers | ReLU | |
| any single weight you might try instead | none works | |
| "is not equal to" |
In words: "two linear layers in a row are the same as one linear layer, but put an activation between them and no single layer can copy them."
With the numbers: without ReLU, and , exactly . With ReLU, and . A single weight would need and at once: impossible.
In Python
W_1, W_2 = 3, 2
# ReLU
def phi(z): return max(0, z)
# (X W_1) W_2 ...
[(x * W_1) * W_2 for x in [-1, 1]] # → [-6, 6]
# ... equals X (W_1 W_2): one layer of 6
[x * (W_1 * W_2) for x in [-1, 1]] # → [-6, 6]
# φ(X W_1) W_2: no single W' gives 0 and 6
[phi(x * W_1) * W_2 for x in [-1, 1]] # → [0, 6]
Figure 5 · Chart
Two-moons decision boundaries: logistic regression's straight line misclassifies the moon tips (88%), while one hidden tanh layer bends around the gap (99.75%)
In code: make_moons builds the half-moons, train_logistic_regression
fits the straight line on the left, and linear_stack_collapses checks
that five stacked linear layers match their single-matrix product to 1e-16. View source
Chapter 5
Activation functions: the rule after the sum
ReLU is one rule among several, and each has a different shape. ReLU passes positive inputs unchanged and turns negative ones into 0. Sigmoid squeezes any input into the range 0 to 1 and flattens out at both ends. Tanh has the same S shape, centred on zero and running from −1 to 1. GELU follows ReLU but curves smoothly near zero, so small negative inputs give small negative outputs.
What matters most about the shape is its slope. Backpropagation multiplies the blame by the activation's slope at every neuron it passes back through; in the backpropagation example, ReLU's slope of 1 let all of it through. Here are values you can check on a calculator (the ′ mark, as in sigmoid′, means "the slope of"):
| z | ReLU | sigmoid | sigmoid' | tanh' | GELU |
|---|---|---|---|---|---|
| −1 | 0 | 0.269 | 0.197 | 0.420 | −0.159 |
| 0 | 0 | 0.5 | 0.25 (its maximum) | 1 (its maximum) | 0 |
| 1 | 1 | 0.731 | 0.197 | 0.420 | 0.841 |
Figure 6 · Chart
Activations and their slopes: sigmoid's slope peaks at 0.25 and sigmoid and tanh slopes vanish past |z| = 3, while ReLU's slope is a clean step from 0 to 1
The slope decides whether the blame survives a deep stack. With sigmoid in every layer, deep networks were hard to train before 2010; ReLU and residual connections are what made them trainable (see Training deep neural networks). The table says where each rule is used.
| Function | Formula | Range | Where it's used |
|---|---|---|---|
| ReLU | max(0, z) | [0, ∞) | Hidden layers of CNNs and MLPs. Fast. A neuron stuck negative gets zero gradient forever ("dying ReLU"). |
| GELU | z·Φ(z), Φ = normal CDF | ≈[−0.17, ∞) | Transformers (BERT, GPT-2 and most since). |
| Sigmoid | 1 / (1 + e^−z) | (0, 1) | Binary outputs, and the gates inside LSTMs. |
| Tanh | (e^z − e^−z)/(e^z + e^−z) | (−1, 1) | RNN hidden states; zero-centred. |
| Softmax | e^{z_i} / Σ e^{z_j} | probabilities | The output layer over classes or tokens, and inside attention. |
Reading the formulas: e is Euler's number, about 2.718, and e^z means "2.718 raised to the power z", which is always positive and grows fast. Φ(z) is the fraction of a bell curve (the standard normal distribution) that lies below z: Φ(0) = 0.5, Φ(1) = 0.841. Softmax turns a list of scores into shares that are all positive and add up to 1: raise e to each score, then divide each by the total (Σ means "add them all up"). Attention works softmax through by hand.
In code: relu, sigmoid, tanh and gelu compute each rule, and
relu_grad, sigmoid_grad, tanh_grad and gelu_grad compute its slope. View source
Chapter 6
Backprop through two layers
A network with more than one layer is an assembly line with more than one station. With two layers, a hidden layer (any layer between the input and the output) and an output layer, the blame from the loss first reaches the output layer's weights, then travels back through the hidden layer's activation to the hidden layer's weights. Crossing the activation multiplies it by the activation's slope, which can shrink it.
Take the smallest such network: one input x = 1, one hidden unit with weight w1 = 0.5 and rule tanh, and one output with weight w2 = 2 and rule sigmoid, which turns its sum into a probability ŷ. The target is 1. The loss is binary cross-entropy (below), and its slope at the output's sum works out to prediction minus target, ŷ − y. The first four rows run forward, the last five run back.
| step | value |
|---|---|
| z1 = x·w1 | 0.5 |
| h = tanh(0.5) | 0.4621 |
| z2 = h·w2 | 0.9242 |
| ŷ = σ(0.9242) | 0.7159 |
| dL/dz2 = ŷ − y | −0.2841 |
| dL/dw2 = h · dL/dz2 | −0.1313 |
| dL/dh = dL/dz2 · w2 | −0.5682 |
| dL/dz1 = dL/dh · (1 − h²) | −0.5682 × 0.7864 = −0.4469 |
| dL/dw1 = x · dL/dz1 | −0.4469 |
Figure 7 · Diagram
flowchart LR
subgraph Forward
direction LR
X[X] --> Z1["z1 = X·W1 + b1"] --> H["h = tanh z1"] --> Z2["z2 = h·W2 + b2"] --> P["ŷ = σ z2"] --> L["L = BCE ŷ, y"]
end
L -. "ŷ − y" .-> dZ2[dL/dz2]
dZ2 -. "hᵀ · dz2" .-> dW2[dL/dW2]
dZ2 -. "dz2 · W2ᵀ" .-> dH[dL/dh]
dH -. "⊙ 1 − h²" .-> dZ1[dL/dz1]
dZ1 -. "Xᵀ · dz1" .-> dW1[dL/dW1]
H -. cached .-> dW2
H -. cached .-> dZ1
X -. cached .-> dW1
Binary cross-entropy, , is the usual loss for yes-or-no predictions (see Loss functions). After a sigmoid output its slope simplifies to ŷ − y. For a whole batch, the five backward lines are:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example (one example, one unit) |
|---|---|---|
| inputs, one row per example | ||
| first and second layer weights | 0.5, 2 | |
| each layer's weighted sum, before its activation | 0.5, 0.9242 | |
| hidden activations, | 0.4621 | |
| "y-hat", the prediction | 0.7159 | |
| the target | 1 | |
| sigmoid, squashes any number into 0 to 1 | ||
| hyperbolic tangent, squashes into −1 to 1 | ||
| "transpose": flip a matrix so rows become columns, so the shapes line up for the multiply | a scalar is its own transpose | |
| multiply element by element (not a matrix multiply) | ||
| the slope of tanh at | 0.7864 |
In words: "the error at the output is prediction minus target; each layer's weight gradient is that layer's input times the error arriving at it; to send the error one layer further back, multiply by the weights it came through and by the activation's slope."
With the numbers: ; ; ; ; .
In Python
import math
X, W_1, W_2, y = 1, 0.5, 2, 1
z_1 = X * W_1
h = math.tanh(z_1)
z_2 = h * W_2
# σ(z_2)
y_hat = 1 / (1 + math.exp(-z_2))
# ŷ - y
dL_dz2 = y_hat - y
# hᵀ ∂L/∂z_2
dL_dW2 = h * dL_dz2
# ∂L/∂z_2 W_2ᵀ
dL_dh = dL_dz2 * W_2
# ⊙ (1 - h²), tanh's slope
dL_dz1 = dL_dh * (1 - h ** 2)
# Xᵀ ∂L/∂z_1
dL_dW1 = X * dL_dz1
[round(v, 4) for v in (dL_dz2, dL_dW2, dL_dh, dL_dz1, dL_dW1)] # → [-0.2841, -0.1313, -0.5682, -0.4469, -0.4469]
The factor (1 − h²) is where the blame shrinks. It is at most 1 and near 0 when tanh is saturated, so after fifty layers of it the first layers hear almost nothing. This is the vanishing gradient problem, and Training deep neural networks covers the fixes.
Hand-written gradients like these can be checked without calculus: move one weight up by a tiny amount ε and then down by ε, and divide the change in the loss by 2ε. This numerical gradient check is slow, two forward passes for every weight, but it catches a wrong derivative.
In code: tiny_two_layer_example computes every row of the table, and
gradient_check compares the network's hand-written gradients with
numerical ones. View source
Chapter 7
Batch, step, epoch
Each step worked by hand so far used a single example. A real training run deals its examples into small piles and takes one step per pile, averaging the blame over the pile. Think of studying a deck of 400 flashcards: you work through a pile of 32, then pause to update your notes. The pile is a batch, the pause is a step, and one pass through the whole deck is an epoch, after which the deck is shuffled and dealt again.
400 examples in batches of 32 make 12 full batches and one of 16, so ⌈400/32⌉ = 13 steps per epoch, and two epochs take 26 steps.
Figure 8 · Diagram
flowchart LR E[Epoch: one pass over all 400 examples] --> SH[Shuffle] SH --> B1[Batch 1<br/>32 examples] --> S1[Step 1<br/>update weights] S1 --> B2[Batch 2] --> S2[Step 2] S2 --> D[...] --> B13[Batch 13<br/>last 16 examples] --> S13[Step 13] S13 -->|next epoch| E
Figure 9 · Chart
Training loss per epoch on a log axis: slow at first, a steep fall once hidden units find features, then a flat tail near zero
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| number of training examples | 400 | |
| batch size | 32 | |
| "ceiling": round up to the next whole number (the last, smaller batch still counts as a step) |
In words: "an epoch takes as many steps as it takes batches of size B to cover N examples, rounding up."
With the numbers: steps per epoch; 2 epochs = 26 steps.
In Python
import math
N, B, epochs = 400, 32, 2
N / B # → 12.5
# ⌈N / B⌉: the last, smaller batch still counts
math.ceil(N / B) # → 13
epochs * math.ceil(N / B) # → 26
A larger batch gives a smoother estimate of the gradient and keeps a GPU busy, but needs more memory. The number of epochs depends on how much data there is. Pretraining a language model makes roughly one pass over trillions of tokens, so it rarely sees the same text twice. Fine-tuning makes several passes over a small dataset, which is why a fine-tune can overfit, memorising its examples instead of learning the pattern.
In code: train reshuffles the data every epoch, takes one gradient
step per batch and records the loss after each epoch. View source
Test yourself
6 questions
Answer each one out loud or on paper before you open it.
Question 1Why can't you just stack linear layers?Think it through, then reveal
Their composition is a single linear map (W1·W2 is just another matrix), so extra layers add parameters but no expressive power.
Question 2What does backprop actually compute?Think it through, then reveal
The gradient: for every weight, how much a tiny change would change the loss. It applies the chain rule from the output backward, reusing values cached in the forward pass.
Question 3Why is ReLU preferred over sigmoid in hidden layers?Think it through, then reveal
Sigmoid's derivative is at most 0.25 and near 0 when saturated, so gradients shrink multiplicatively with depth. ReLU's derivative is exactly 1 for positive inputs. The cost: neurons whose input stays negative get zero gradient and "die".
Question 4Why does training need more memory than inference?Think it through, then reveal
The backward pass needs every layer's activations from the forward pass, so they must be kept until the gradients are computed. Inference can discard each activation as soon as the next layer has used it.
Question 5What's the gradient of sigmoid + binary cross-entropy with respect to the logit?Think it through, then reveal
ŷ − y: prediction minus target. Clean, bounded and cheap, which is why the two are always fused.
Question 6Batch vs. step vs. epoch?Think it through, then reveal
A batch is the examples per update, a step is one update, an epoch is one full pass over the data.
Primary sources
The papers behind this lesson
Rumelhart, Hinton & Williams, Learning representations by back-propagating errors (Nature, 1986): Showed that the chain rule, run backwards through a multi-layer network, trains hidden units to discover useful internal features.
The paperHendrycks & Gimpel, Gaussian Error Linear Units (GELUs) (2016): Introduced GELU, the smooth ReLU that became the default activation in transformers.
The paperResearcher's shelf
Further reading
- CS231n notes, Backpropagation, intuitions: https://cs231n.github.io/optimization-2/
- CS231n notes, Neural Networks Part 1: https://cs231n.github.io/neural-networks-1/
- Andrej Karpathy, micrograd (autograd in about 100 lines): https://github.com/karpathy/micrograd
- Andrej Karpathy, The spelled-out intro to neural networks and backpropagation: https://www.youtube.com/watch?v=VMj-3S1tku0
- 3Blue1Brown, Neural networks series: https://www.3blue1brown.com/topics/neural-networks
- Michael Nielsen, Neural Networks and Deep Learning, ch. 2: http://neuralnetworksanddeeplearning.com/chap2.html
- Hendrycks & Gimpel, GELU (2016): https://arxiv.org/abs/1606.08415
- PyTorch autograd tutorial: https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html
About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.