Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 15: Neural Networks

Open in Colab

What I cannot create, I do not understand.

Richard Feynman

15.1 From Neurons to Networks

Chapter 8’s linear and logistic models compute a weighted sum of the features. They are fast and explainable, but their decision boundary is always a straight line (a hyperplane). Neural networks stack many such units, with nonlinear functions between them, and can learn almost any shape of boundary: faces, voices, sentences.

The artificial neuron

A biological neuron receives signals through its dendrites, and fires along its axon when the total input is strong enough. The artificial neuron keeps the idea and nothing of the biology:

a=g(∑j=1dwjxj+b)=g(w⊤x+b)a = g\Big(\sum_{j=1}^{d} w_j x_j + b\Big) = g(\mathbf{w}^\top\mathbf{x} + b)
  • xjx_j: the inputs; wjw_j: the weights (how much each input counts); bb: the bias.

  • z=w⊤x+bz = \mathbf{w}^\top\mathbf{x} + b is the pre-activation; gg is the activation function; aa is the neuron’s output.

Logistic regression is exactly one neuron with g=σg = \sigma, the sigmoid.

The perceptron

Rosenblatt’s perceptron (1958) uses a step function: output 1 if z>0z > 0, else 0. Its learning rule, for each misclassified example, is

w←w+η (y−y^) x,b←b+η (y−y^)\mathbf{w} \leftarrow \mathbf{w} + \eta\,(y - \hat y)\,\mathbf{x}, \qquad b \leftarrow b + \eta\,(y - \hat y)

If the two classes can be separated by a line, this rule is guaranteed to find one.

The XOR problem

XOR outputs 1 when exactly one of its two inputs is 1. No single line separates {(0,1),(1,0)}\{(0,1), (1,0)\} from {(0,0),(1,1)}\{(0,0), (1,1)\}, so no single neuron can learn XOR. Minsky and Papert’s 1969 book made this limitation famous and slowed neural network research for a decade (one of the “AI winters” of Chapter 1).

The fix is to add a hidden layer: two neurons draw two lines, and a third combines them.

Source
<Figure size 1000x360 with 2 Axes>

15.2 Multilayer Perceptrons

A multilayer perceptron (MLP), or fully connected feed-forward network, arranges neurons in layers:

  • an input layer (the features: not real neurons, just the values),

  • one or more hidden layers,

  • an output layer (one neuron for regression, one per class for classification).

Every neuron of a layer is connected to every neuron of the next.

The forward pass in matrix form

Layer ll has a weight matrix W[l]W^{[l]} (one row per neuron) and a bias vector b[l]\mathbf{b}^{[l]}. Starting from a[0]=x\mathbf{a}^{[0]} = \mathbf{x}:

z[l]=W[l]a[l−1]+b[l],a[l]=g[l](z[l])\mathbf{z}^{[l]} = W^{[l]}\mathbf{a}^{[l-1]} + \mathbf{b}^{[l]}, \qquad \mathbf{a}^{[l]} = g^{[l]}(\mathbf{z}^{[l]})

and the output is y^=a[L]\hat{\mathbf{y}} = \mathbf{a}^{[L]}. For a batch of examples stacked as rows of a matrix XX, the same computation becomes Z=XW⊤+bZ = XW^\top + \mathbf{b}: one matrix product per layer, which is why GPUs make neural networks fast.

Counting parameters. A layer with ninn_{in} inputs and noutn_{out} neurons has nin×noutn_{in} \times n_{out} weights and noutn_{out} biases. A 784–128–10 network (for 28×28 digit images) has 784⋅128+128+128⋅10+10=101 770784\cdot128 + 128 + 128\cdot10 + 10 = 101\,770 parameters.

Why the nonlinearity matters

Without activation functions, two layers collapse into one: W[2](W[1]x)=(W[2]W[1])xW^{[2]}(W^{[1]}\mathbf{x}) = (W^{[2]}W^{[1]})\mathbf{x} is still linear. The nonlinear gg is what gives depth its power.

15.3 Activation Functions

FunctionFormulaRangeDerivativeUse
Sigmoidσ(z)=11+e−z\sigma(z) = \frac{1}{1+e^{-z}}(0,1)(0, 1)σ(z)(1−σ(z))\sigma(z)(1-\sigma(z))binary output
Tanhtanh⁡(z)\tanh(z)(−1,1)(-1, 1)1−tanh⁡2(z)1 - \tanh^2(z)hidden layers (older nets), RNNs
ReLUmax⁡(0,z)\max(0, z)[0,∞)[0, \infty)1 if z>0z > 0, else 0default for hidden layers
Leaky ReLUmax⁡(0.01z,z)\max(0.01z, z)R\mathbb{R}1 or 0.01avoids “dead” ReLUs
Softmaxezk∑jezj\frac{e^{z_k}}{\sum_j e^{z_j}}probabilities(with cross-entropy: simple)multi-class output
Source
<Figure size 1100x340 with 2 Axes>

The vanishing gradient

Backpropagation (Section 15.5) multiplies one derivative per layer. The sigmoid’s derivative is at most 0.25, so through 10 sigmoid layers the gradient can shrink by a factor 0.2510≈10−60.25^{10} \approx 10^{-6}: the early layers stop learning. ReLU’s derivative is exactly 1 for positive inputs, which is a main reason deep networks became trainable around 2010.

ReLU has its own failure: a neuron whose input is always negative outputs 0, gets gradient 0, and never recovers (a dead ReLU). Leaky ReLU and careful initialisation help.

15.4 Loss Functions

TaskOutput layerLoss
Regression1 linear neuronmean squared error 1n∑(y^−y)2\frac{1}{n}\sum (\hat y - y)^2
Binary classification1 sigmoid neuronbinary cross-entropy
KK-class classificationKK neurons + softmaxcross-entropy −log⁡y^true class-\log \hat y_{\text{true class}}

With softmax and cross-entropy together, the gradient with respect to the scores is remarkably simple: ∂L∂z=y^−y\frac{\partial L}{\partial \mathbf{z}} = \hat{\mathbf{y}} - \mathbf{y} (predicted probabilities minus the one-hot true label), the same form as logistic regression in Chapter 8.

15.5 Backpropagation

Training means gradient descent on the loss, so we need ∂L/∂w\partial L / \partial w for every weight, possibly millions of them. Backpropagation computes all of them in one backward sweep, at about the cost of one forward pass. It is nothing more than the chain rule applied efficiently.

The chain rule on a computational graph

If LL depends on ww through zz and aa (w→z→a→Lw \to z \to a \to L), then

∂L∂w=∂L∂a⋅∂a∂z⋅∂z∂w\frac{\partial L}{\partial w} = \frac{\partial L}{\partial a}\cdot\frac{\partial a}{\partial z}\cdot\frac{\partial z}{\partial w}

Backpropagation computes these factors from the output backwards, reusing each one for every weight below it.

The equations

Define the error of layer ll as δ[l]=∂L/∂z[l]\boldsymbol{\delta}^{[l]} = \partial L / \partial \mathbf{z}^{[l]}. Then:

  1. Output layer: δ[L]=∂L∂a[L]⊙g′(z[L])\boldsymbol{\delta}^{[L]} = \frac{\partial L}{\partial \mathbf{a}^{[L]}} \odot g'(\mathbf{z}^{[L]}) (for softmax + cross-entropy: simply y^−y\hat{\mathbf{y}} - \mathbf{y}).

  2. Backwards, for l=L−1,…,1l = L-1, \dots, 1: δ[l]=(W[l+1]⊤δ[l+1])⊙g′(z[l])\boldsymbol{\delta}^{[l]} = \big(W^{[l+1]\top}\boldsymbol{\delta}^{[l+1]}\big) \odot g'(\mathbf{z}^{[l]})

  3. Gradients: ∂L∂W[l]=δ[l] a[l−1]⊤\frac{\partial L}{\partial W^{[l]}} = \boldsymbol{\delta}^{[l]}\,\mathbf{a}^{[l-1]\top}, ∂L∂b[l]=δ[l]\quad\frac{\partial L}{\partial \mathbf{b}^{[l]}} = \boldsymbol{\delta}^{[l]}

(⊙\odot is element-wise multiplication.) Each error is the next layer’s error, sent back through the same weights, and scaled by the local slope g′g'.

Worked example

A 2–2–1 network with sigmoid units, input x=(1,0)\mathbf{x} = (1, 0), target y=1y = 1, loss L=12(y^−y)2L = \frac{1}{2}(\hat y - y)^2:

W[1]=(0.5−0.40.30.8), b[1]=(0.1−0.1),W[2]=(0.7  −0.6), b[2]=0.2W^{[1]} = \begin{pmatrix} 0.5 & -0.4 \\ 0.3 & 0.8 \end{pmatrix},\ \mathbf{b}^{[1]} = \begin{pmatrix} 0.1 \\ -0.1 \end{pmatrix},\qquad W^{[2]} = (0.7\ \ -0.6),\ b^{[2]} = 0.2

Forward.

  • z[1]=(0.5+0.1, 0.3−0.1)=(0.6,0.2)\mathbf{z}^{[1]} = (0.5 + 0.1,\ 0.3 - 0.1) = (0.6, 0.2), so h=σ(z[1])=(0.646,0.550)\mathbf{h} = \sigma(\mathbf{z}^{[1]}) = (0.646, 0.550)

  • z[2]=0.7(0.646)−0.6(0.550)+0.2=0.322z^{[2]} = 0.7(0.646) - 0.6(0.550) + 0.2 = 0.322, so y^=σ(0.322)=0.580\hat y = \sigma(0.322) = 0.580

  • L=12(0.580−1)2=0.0883L = \frac{1}{2}(0.580 - 1)^2 = 0.0883

Backward.

  • Output error: δ[2]=(y^−y) y^(1−y^)=(−0.420)(0.580)(0.420)=−0.1024\delta^{[2]} = (\hat y - y)\,\hat y(1 - \hat y) = (-0.420)(0.580)(0.420) = -0.1024

  • Output weights: ∂L/∂W[2]=δ[2] h=(−0.0661, −0.0563)\partial L / \partial W^{[2]} = \delta^{[2]}\,\mathbf{h} = (-0.0661,\ -0.0563)

  • Hidden errors: δ1[1]=δ[2](0.7) h1(1−h1)=−0.0164\delta^{[1]}_1 = \delta^{[2]}(0.7)\,h_1(1-h_1) = -0.0164,   δ2[1]=δ[2](−0.6) h2(1−h2)=+0.0152\;\delta^{[1]}_2 = \delta^{[2]}(-0.6)\,h_2(1-h_2) = +0.0152

  • Hidden weights: ∂L/∂W[1]=δ[1]x⊤\partial L / \partial W^{[1]} = \boldsymbol{\delta}^{[1]}\mathbf{x}^\top: only the first column (input x1=1x_1 = 1) is nonzero: (−0.0164, 0.0152)(-0.0164,\ 0.0152)

Update with η=0.5\eta = 0.5: W[2]→(0.733, −0.572)W^{[2]} \to (0.733,\ -0.572), W11[1]→0.508W^{[1]}_{11} \to 0.508, W21[1]→0.292W^{[1]}_{21} \to 0.292, and so on. Running the forward pass again gives y^=0.602\hat y = 0.602 and L=0.0791L = 0.0791: the loss went down, as it should.

15.6 Training Neural Networks

Mini-batches and epochs

Training repeats, for many epochs (full passes over the training set):

  1. shuffle the training data;

  2. for each mini-batch of, say, 32 or 64 examples: forward pass, loss, backward pass, update.

Mini-batches make each step cheap and add useful noise that helps escape bad regions.

Better optimisers

OptimiserIdeaUpdate (simplified)
SGDplain gradient stepw←w−ηgw \leftarrow w - \eta g
Momentumkeep a velocity; roll through small bumpsv←βv+gv \leftarrow \beta v + g,   w←w−ηv\;w \leftarrow w - \eta v
RMSPropdivide by a running size of recent gradientsper-weight step sizes
Adammomentum + RMSProp + bias correctionthe usual default, η=10−3\eta = 10^{-3}

The learning rate is still the most important hyperparameter. Common practice: start around 10-3 with Adam, and lower it during training (a schedule), for example by 10× when the validation loss stops improving.

Initialisation

If all weights start equal, all neurons of a layer compute the same thing and receive the same gradient: they stay identical forever. Weights must start random, with a carefully chosen scale so that signals neither vanish nor explode from layer to layer:

  • Xavier/Glorot: variance 2nin+nout\frac{2}{n_{in} + n_{out}}, for sigmoid and tanh;

  • He: variance 2nin\frac{2}{n_{in}}, for ReLU.

Biases usually start at 0. Libraries such as PyTorch use good defaults.

15.7 Regularisation: Generalising Better

Networks have many parameters and overfit easily. The main remedies:

TechniqueHowWhy it helps
Weight decay (L2)add λ∑w2\lambda\sum w^2 to the lossprefers small, smooth weights (Chapter 8’s ridge)
Dropoutduring training, zero each hidden neuron with probability pp (e.g. 0.5)the network cannot rely on any single neuron: like training an ensemble
Early stoppingwatch the validation loss; stop (and keep the best weights) when it starts risingstops before memorising
Batch normalisationnormalise each layer’s inputs over the mini-batchfaster, more stable training; mild regularisation
Data augmentationtrain on modified copies (flipped, shifted images)more data, for free
Source
<Figure size 700x340 with 1 Axes>

15.8 Neural Networks in PyTorch

Writing backpropagation by hand is the best way to understand it, and a bad way to build real systems. PyTorch computes gradients automatically (autograd): you write the forward pass, and loss.backward() does the rest.

import torch
from torch import nn

model = nn.Sequential(            # a 64-32-10 MLP for 8x8 digit images
    nn.Linear(64, 32), nn.ReLU(),
    nn.Linear(32, 10)              # raw scores: CrossEntropyLoss applies the softmax itself
)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(30):
    for xb, yb in train_loader:    # mini-batches
        loss = loss_fn(model(xb), yb)
        optimizer.zero_grad()      # clear the old gradients
        loss.backward()            # backpropagation
        optimizer.step()           # one update of every weight

The four lines inside the loop are the same in almost every PyTorch program, from this small MLP to a large language model.

15.9 A Practical Recipe

  1. Start small: overfit a tiny subset (say 100 examples) first. If the network cannot, there is a bug.

  2. Scale the inputs (standardise, or divide pixels by 255).

  3. Use ReLU in hidden layers, Adam with η=10−3\eta = 10^{-3}, and a sensible batch size (32–256).

  4. Plot training and validation loss every epoch.

  5. If training loss is high: a bigger network, more epochs, a better learning rate (underfitting).

  6. If validation loss is much higher than training loss: more data, dropout, weight decay, early stopping (overfitting).

  7. Compare with a simple baseline (Chapter 8): a neural network is not always the best tool for small tabular data.

15.10 Summary

  • A neuron computes g(w⊤x+b)g(\mathbf{w}^\top\mathbf{x} + b); one neuron draws one line, so it cannot learn XOR.

  • An MLP stacks layers: a[l]=g(W[l]a[l−1]+b[l])\mathbf{a}^{[l]} = g(W^{[l]}\mathbf{a}^{[l-1]} + \mathbf{b}^{[l]}); nonlinear activations make depth useful.

  • ReLU for hidden layers; sigmoid or softmax at the output, with cross-entropy.

  • Backpropagation applies the chain rule from the output backwards: δ[l]=(W[l+1]⊤δ[l+1])⊙g′(z[l])\boldsymbol\delta^{[l]} = (W^{[l+1]\top}\boldsymbol\delta^{[l+1]}) \odot g'(\mathbf{z}^{[l]}).

  • Train with mini-batches and Adam; initialise randomly (Xavier, He).

  • Regularise with weight decay, dropout and early stopping.

  • PyTorch computes gradients automatically; the training loop is: forward, loss, zero_grad, backward, step.

Exercises

  1. Find weights and biases for a 2–2–1 network with step activations that computes XOR.

  2. How many parameters does a 100–50–50–3 network have?

  3. In the worked example, compute ∂L/∂b[2]\partial L / \partial b^{[2]} and the new value of b[2]b^{[2]} after the update.

  4. Why can a network with only linear activations not learn XOR, however many layers it has?

  5. A network reaches 99% training accuracy and 70% validation accuracy. Name three things to try.

  6. What would happen if all weights were initialised to 0? Explain using the backpropagation equations.

Further Reading

  • M. Nielsen, Neural Networks and Deep Learning, 2015 (free online): the clearest introduction to backpropagation.

  • I. Goodfellow, Y. Bengio, A. Courville, Deep Learning, MIT Press, 2016, Chapters 6–8.

  • C. C. Aggarwal, Artificial Intelligence: A Textbook, Springer, 2021, Chapter 7.

  • The PyTorch tutorials: https://pytorch.org/tutorials/