Chapter 3 / 16

Neural Networks and Deep Learning

Intermediate 3โ€“4 h ยท Prerequisites: Mathematics and Python for AI

Learning objectives

  • Explain neurons, layers, activations and why depth helps
  • Understand backpropagation and automatic differentiation
  • Write a complete PyTorch training loop with validation
  • Diagnose overfitting, underfitting and unstable training

Introduction

Neural networks are the engine of modern AI โ€“ from image recognition to large language models. In this chapter you build intuition for what a neuron and a layer compute, see how backpropagation finds the gradient of millions of parameters, and write a complete PyTorch training loop that you will reuse for every model in this course, including the GPT in chapter 5.

Linear models can only separate data with straight lines (or flat planes). Real data โ€“ images, language, sensor signals โ€“ is not linearly separable. Neural networks combine linear layers with non-linear activation functions; with enough units they can approximate practically any function, and with depth they learn useful intermediate representations by themselves. Their weakness is the flip side: many parameters, so they need data, compute and careful training to generalise.

Neurons, layers and activations

A neuron computes a weighted sum of its inputs plus a bias, z = w ยท x + b, and passes it through an activation function, a = f(z). A layer applies many neurons in parallel: a = f(xW + b) โ€“ one matrix multiplication for the whole batch (chapter 2).

Without a non-linear activation, stacking layers is pointless: a composition of linear functions is linear. The ReLU activation, max(0, z), is the most common choice in hidden layers โ€“ simple, fast and with gradients that do not vanish for positive inputs. Transformers often use GELU, a smooth variant.

The output layer depends on the task: one logit with a sigmoid for binary classification, one logit per class with softmax for multi-class classification, one logit per vocabulary token for language models, or a plain linear output for regression.

Backpropagation and automatic differentiation

To train, we need the gradient of the loss with respect to every weight. Backpropagation computes it efficiently with the chain rule: first a forward pass computes all intermediate values and the loss; then a backward pass multiplies local derivatives from the loss back to each parameter, reusing intermediate results.

PyTorch records the operations of the forward pass in a computational graph (autograd). Calling loss.backward() traverses this graph backwards and stores each parameter's gradient in .grad. The small autograd example below checks the result against derivatives calculated by hand.

Gradients accumulate: PyTorch adds new gradients to existing ones. That is why every training step starts with optimizer.zero_grad().

The training loop

Every PyTorch training step has four lines that matter: reset gradients, forward pass and loss, backward pass, optimiser step. Everything else โ€“ data loading, logging, evaluation โ€“ is organised around them.

Optimisers improve on plain gradient descent. Adam keeps running averages of gradients and their squares per parameter and adapts the step size, which makes it robust for most problems; SGD with momentum remains common for vision models.

Mini-batches: instead of the full dataset, each step uses a random batch (for example 32 examples). This is cheaper per step, adds useful noise, and is the only option when data does not fit in memory. One pass over all batches is an epoch.

model.train() and model.eval() switch layers such as dropout and batch normalisation between training and inference behaviour; torch.no_grad() turns off graph recording during evaluation and saves memory.

Overfitting, underfitting and regularisation

Underfitting: the model is too simple or trained too briefly โ€“ training and validation error are both high. Overfitting: training error keeps falling while validation error rises โ€“ the model memorises noise.

Countermeasures for overfitting: more (or augmented) data, smaller models, early stopping (stop when validation loss stops improving), weight decay (penalising large weights), and dropout (randomly disabling units during training).

Always watch both curves โ€“ training and validation loss โ€“ during training. The lab in this chapter provokes overfitting on purpose so you can recognise it.

Why deep networks work โ€“ and how they are kept trainable

Each layer transforms the representation of the previous one. In vision models, early layers detect edges and later layers object parts; in language models, layers progressively build syntactic and semantic features.

Very deep networks used to be hard to train because gradients vanished or exploded on the way back. Three techniques changed this and appear in every transformer (chapter 4): residual connections (x + f(x)) that give gradients a direct path, normalisation layers (LayerNorm) that keep activations in a stable range, and careful initialisation.

Key terminology

Activation function
Non-linear function applied after a layer's weighted sum, e.g. ReLU or GELU.
Backpropagation
Efficient computation of all gradients of the loss via the chain rule, from the output back to the input.
Autograd
PyTorch's automatic differentiation that records operations and computes gradients with .backward().
Epoch
One full pass over the training data.
Mini-batch
A small random subset of examples used for one optimisation step.
Adam
Optimiser with adaptive per-parameter step sizes based on running gradient statistics.
Early stopping
Ending training when validation performance stops improving.
Residual connection
Adding a layer's input to its output (x + f(x)) to keep deep networks trainable.

Architecture diagrams

A small multi-layer perceptron

flowchart LR
  X[Input x1, x2] --> L1[Linear 2 to 32]
  L1 --> R1[ReLU]
  R1 --> L2[Linear 32 to 32]
  L2 --> R2[ReLU]
  R2 --> L3[Linear 32 to 1]
  L3 --> S[Logit - sigmoid gives probability]
Two hidden layers with ReLU turn two coordinates into one logit; the sigmoid of the logit is the probability of class 1.

One training step in PyTorch

flowchart LR
  Z[optimizer.zero_grad] --> F[Forward: logits = model of x]
  F --> L[Loss = loss_fn of logits, y]
  L --> B[loss.backward - gradients via chain rule]
  B --> S[optimizer.step - update weights]
  S --> Z
The four lines of every training loop; gradients flow backwards along the recorded graph.

Practical examples

Credit-card fraud detection. A neural network on transaction features (amount, time, merchant category) outputs a fraud probability; a threshold chosen on validation data trades missed fraud against false alarms.

Image classification. Convolutional or transformer-based vision networks learn to classify images from labelled examples โ€“ the same training loop as in this chapter, with a different architecture and much more data.

Working code

What backpropagation computes

Tested with: Python 3.13, PyTorch 2.15 (CPU)

# pip install torch
# python ch3_autograd.py
"""Chapter 3 โ€“ what backpropagation computes, checked by hand."""
import torch

x = torch.tensor(2.0, requires_grad=True)
w = torch.tensor(3.0, requires_grad=True)
y = (w * x + 1) ** 2        # y = (wx + 1)^2
y.backward()
# dy/dw = 2(wx+1)*x = 2*7*2 = 28 ; dy/dx = 2(wx+1)*w = 2*7*3 = 42
print("dy/dw:", w.grad.item(), "dy/dx:", x.grad.item())
Expected output
dy/dw: 28.0 dy/dx: 42.0

Autograd reproduces the hand-calculated chain-rule derivatives exactly.

Project: training a small neural network

Tested with: Python 3.13, PyTorch 2.15 (CPU), scikit-learn 1.9

# pip install torch scikit-learn
# python ch3_mlp_pytorch.py
"""Chapter 3 โ€“ train a small neural network with PyTorch (CPU, < 10 s)."""
import torch
from torch import nn
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

torch.manual_seed(0)

# Two interleaving half circles: not separable by a straight line.
X, y = make_moons(n_samples=1000, noise=0.2, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=0)
X_train, X_val = torch.tensor(X_train, dtype=torch.float32), torch.tensor(X_val, dtype=torch.float32)
y_train, y_val = torch.tensor(y_train, dtype=torch.float32), torch.tensor(y_val, dtype=torch.float32)

model = nn.Sequential(
    nn.Linear(2, 32), nn.ReLU(),
    nn.Linear(32, 32), nn.ReLU(),
    nn.Linear(32, 1),            # one logit: probability of class 1 after sigmoid
)
loss_fn = nn.BCEWithLogitsLoss()  # sigmoid + binary cross-entropy, numerically stable
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)

for epoch in range(200):
    model.train()
    optimizer.zero_grad()                       # 1. reset gradients
    loss = loss_fn(model(X_train).squeeze(1), y_train)   # 2. forward pass + loss
    loss.backward()                             # 3. backpropagation
    optimizer.step()                            # 4. update weights
    if epoch % 50 == 0 or epoch == 199:
        model.eval()
        with torch.no_grad():
            acc = ((model(X_val).squeeze(1) > 0).float() == y_val).float().mean()
        print(f"epoch {epoch:3d}  loss {loss.item():.4f}  val acc {acc.item():.3f}")
Expected output
epoch   0  loss 0.7124  val acc 0.460
epoch  50  loss 0.1212  val acc 0.950
epoch 100  loss 0.0810  val acc 0.960
epoch 150  loss 0.0782  val acc 0.965
epoch 199  loss 0.0766  val acc 0.970

From chance level (0.46) to 97 % validation accuracy in 200 full-batch steps. A logit > 0 means probability > 0.5. Exact numbers can differ slightly across PyTorch versions and hardware; the trend should not.

Practice Lab

Each exercise changes one thing in the project script and asks you to predict the result before running it.

Remove the non-linearity

Beginner

Delete both nn.ReLU() layers and train again. Predict the validation accuracy first.

  • Three linear layers in a row are one linear function.
Show solution
model = nn.Sequential(nn.Linear(2, 32), nn.Linear(32, 32), nn.Linear(32, 1))
# val acc โ‰ˆ 0.855: the network is a linear classifier and cannot follow the moons.

Train with mini-batches

Intermediate

Use torch.utils.data.DataLoader with batch_size=32 and shuffle=True, train for 20 epochs and report the validation accuracy.

  • Iterate over the loader inside the epoch loop; zero the gradients per batch.
Show solution
from torch.utils.data import DataLoader, TensorDataset
loader = DataLoader(TensorDataset(X_train, y_train), batch_size=32, shuffle=True)
for epoch in range(20):
    model.train()
    for xb, yb in loader:
        optimizer.zero_grad()
        loss = loss_fn(model(xb).squeeze(1), yb)
        loss.backward()
        optimizer.step()
# val acc โ‰ˆ 0.955 after 20 epochs (25 steps per epoch = 500 steps)

Provoke and fix overfitting

Advanced

Use only 120 samples with noise=0.35, a network with two hidden layers of 256 units and 2000 training steps. Compare training and validation accuracy. Then train for 150 steps with weight_decay=1e-3 and compare again.

  • Report accuracy on both splits; the gap is the symptom.
Show solution
# 2000 steps, no regularisation: train 1.000, validation 0.750 โ€“ memorised noise.
# 150 steps + weight decay 1e-3:   train 0.917, validation 0.875 โ€“ a smaller gap and better generalisation.
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=1e-3)

Practise with OOHM

Reinforce the chapter's vocabulary and concepts with dictation, rapid typing and quizzes on this topic.

Please log in to use this AI feature.

Knowledge check

1. Why are activation functions needed between layers?
2. What does loss.backward() do in PyTorch?
3. Why call optimizer.zero_grad() every step?
4. Training loss falls, validation loss rises. What is happening?
5. Which measure does NOT reduce overfitting?
6. What is an epoch?
7. What does BCEWithLogitsLoss combine?
8. What do residual connections do?
9. Why use torch.no_grad() during evaluation?
10. A network without ReLU on the moons dataset reaches about 85 %. Why not more?

Common mistakes and troubleshooting

RuntimeError: shapes cannot be multiplied (32x2 and 3x64).
Cause: The first Linear layer's in_features does not match the number of input features.
Fix: Set in_features to X.shape[1]; print shapes after each layer when building models.
Loss does not decrease at all.
Cause: Learning rate far too small or too large, missing optimizer.step(), or labels with the wrong dtype/shape for the loss.
Fix: Overfit a tiny batch first (e.g. 10 examples) โ€“ if the model cannot, the bug is in the code, not the data.
Validation accuracy is lower than expected only during evaluation.
Cause: model.eval() not called, so dropout or batch norm behave as in training.
Fix: Call model.eval() before evaluation and model.train() before training.

Summary

  • A layer is a matrix multiplication plus a non-linearity; depth builds representations.
  • Backpropagation computes all gradients with the chain rule; autograd does it automatically.
  • The training loop is: zero_grad, forward + loss, backward, step.
  • Watch training and validation curves; regularise when they diverge.

Learning outcomes

  • You can build, train and evaluate a neural network in PyTorch.
  • You can recognise and counter underfitting and overfitting.

Official documentation