Chapter 15: Neural Networks
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:
: the inputs; : the weights (how much each input counts); : the bias.
is the pre-activation; is the activation function; is the neuron’s output.
Logistic regression is exactly one neuron with , the sigmoid.
The perceptron¶
Rosenblatt’s perceptron (1958) uses a step function: output 1 if , else 0. Its learning rule, for each misclassified example, is
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 from , 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
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6))
P = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]); Y = np.array([0, 1, 1, 0])
for ax in axes:
ax.scatter(P[Y == 0, 0], P[Y == 0, 1], s=180, c='C0', marker='o', label='0', zorder=3)
ax.scatter(P[Y == 1, 0], P[Y == 1, 1], s=180, c='C3', marker='s', label='1', zorder=3)
ax.set_xlim(-0.5, 1.5); ax.set_ylim(-0.5, 1.5); ax.set_xticks([0, 1]); ax.set_yticks([0, 1]); ax.set_aspect('equal')
axes[0].plot([-0.5, 1.5], [1.2, -0.3], '--', color='gray'); axes[0].set_title('One line cannot separate XOR')
g = np.linspace(-0.5, 1.5, 300); xx, yy = np.meshgrid(g, g)
h1 = (xx + yy - 0.5 > 0); h2 = (xx + yy - 1.5 > 0); out = (h1 & ~h2)
axes[1].contourf(xx, yy, out, alpha=0.2, cmap='coolwarm', levels=[-0.5, 0.5, 1.5])
axes[1].plot(g, 0.5 - g, color='C2'); axes[1].plot(g, 1.5 - g, color='C2'); axes[1].set_title('Two hidden neurons: two lines')
axes[0].legend(loc='upper right'); plt.tight_layout(); plt.show()
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 has a weight matrix (one row per neuron) and a bias vector . Starting from :
and the output is . For a batch of examples stacked as rows of a matrix , the same computation becomes : one matrix product per layer, which is why GPUs make neural networks fast.
Counting parameters. A layer with inputs and neurons has weights and biases. A 784–128–10 network (for 28×28 digit images) has parameters.
Why the nonlinearity matters¶
Without activation functions, two layers collapse into one: is still linear. The nonlinear is what gives depth its power.
15.3 Activation Functions¶
| Function | Formula | Range | Derivative | Use |
|---|---|---|---|---|
| Sigmoid | binary output | |||
| Tanh | hidden layers (older nets), RNNs | |||
| ReLU | 1 if , else 0 | default for hidden layers | ||
| Leaky ReLU | 1 or 0.01 | avoids “dead” ReLUs | ||
| Softmax | probabilities | (with cross-entropy: simple) | multi-class output |
Source
z = np.linspace(-5, 5, 400)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.4))
sig = 1 / (1 + np.exp(-z))
for f, name in [(sig, 'sigmoid'), (np.tanh(z), 'tanh'), (np.maximum(0, z), 'ReLU'), (np.maximum(0.05 * z, z), 'leaky ReLU')]:
axes[0].plot(z, f, label=name, lw=2)
axes[0].set_ylim(-1.5, 3); axes[0].axhline(0, color='gray', lw=0.5); axes[0].legend(); axes[0].set_title('Activation functions')
axes[1].plot(z, sig * (1 - sig), label="sigmoid'", lw=2); axes[1].plot(z, 1 - np.tanh(z) ** 2, label="tanh'", lw=2); axes[1].plot(z, (z > 0).astype(float), label="ReLU'", lw=2)
axes[1].legend(); axes[1].set_title('Their derivatives: the sigmoid\'s is at most 0.25')
plt.tight_layout(); plt.show()
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 : 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¶
| Task | Output layer | Loss |
|---|---|---|
| Regression | 1 linear neuron | mean squared error |
| Binary classification | 1 sigmoid neuron | binary cross-entropy |
| -class classification | neurons + softmax | cross-entropy |
With softmax and cross-entropy together, the gradient with respect to the scores is remarkably simple: (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 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 depends on through and (), then
Backpropagation computes these factors from the output backwards, reusing each one for every weight below it.
The equations¶
Define the error of layer as . Then:
Output layer: (for softmax + cross-entropy: simply ).
Backwards, for :
Gradients: ,
( is element-wise multiplication.) Each error is the next layer’s error, sent back through the same weights, and scaled by the local slope .
Worked example¶
A 2–2–1 network with sigmoid units, input , target , loss :
Forward.
, so
, so
Backward.
Output error:
Output weights:
Hidden errors: ,
Hidden weights: : only the first column (input ) is nonzero:
Update with : , , , and so on. Running the forward pass again gives and : 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):
shuffle the training data;
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¶
| Optimiser | Idea | Update (simplified) |
|---|---|---|
| SGD | plain gradient step | |
| Momentum | keep a velocity; roll through small bumps | , |
| RMSProp | divide by a running size of recent gradients | per-weight step sizes |
| Adam | momentum + RMSProp + bias correction | the usual default, |
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 , for sigmoid and tanh;
He: variance , 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:
| Technique | How | Why it helps |
|---|---|---|
| Weight decay (L2) | add to the loss | prefers small, smooth weights (Chapter 8’s ridge) |
| Dropout | during training, zero each hidden neuron with probability (e.g. 0.5) | the network cannot rely on any single neuron: like training an ensemble |
| Early stopping | watch the validation loss; stop (and keep the best weights) when it starts rising | stops before memorising |
| Batch normalisation | normalise each layer’s inputs over the mini-batch | faster, more stable training; mild regularisation |
| Data augmentation | train on modified copies (flipped, shifted images) | more data, for free |
Source
rng = np.random.default_rng(3)
ep = np.arange(1, 101)
train = 1.2 * np.exp(-ep / 18) + 0.05 + rng.normal(0, 0.01, 100)
valid = 1.2 * np.exp(-ep / 18) + 0.12 + 0.0012 * np.maximum(0, ep - 30) ** 1.5 / 3 + rng.normal(0, 0.012, 100)
best = int(np.argmin(valid))
plt.figure(figsize=(7, 3.4)); plt.plot(ep, train, label='training loss'); plt.plot(ep, valid, label='validation loss')
plt.axvline(ep[best], ls='--', color='C2'); plt.text(ep[best] + 2, 0.9, 'early stopping:\nkeep these weights', color='C2')
plt.xlabel('epoch'); plt.ylabel('loss'); plt.legend(); plt.title('Overfitting shows up as a rising validation loss'); plt.tight_layout(); plt.show()
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 weightThe 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¶
Start small: overfit a tiny subset (say 100 examples) first. If the network cannot, there is a bug.
Scale the inputs (standardise, or divide pixels by 255).
Use ReLU in hidden layers, Adam with , and a sensible batch size (32–256).
Plot training and validation loss every epoch.
If training loss is high: a bigger network, more epochs, a better learning rate (underfitting).
If validation loss is much higher than training loss: more data, dropout, weight decay, early stopping (overfitting).
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 ; one neuron draws one line, so it cannot learn XOR.
An MLP stacks layers: ; 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: .
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¶
Find weights and biases for a 2–2–1 network with step activations that computes XOR.
How many parameters does a 100–50–50–3 network have?
In the worked example, compute and the new value of after the update.
Why can a network with only linear activations not learn XOR, however many layers it has?
A network reaches 99% training accuracy and 70% validation accuracy. Name three things to try.
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/