Expert: deep learning and AI · Neural networks and deep learning · topic 45 of 62 · 35 min
Training: loss, backpropagation and optimisers
Explanation
The training loop
- Forward pass: push a mini-batch of examples through the network to get predictions.
- Loss: compare predictions with the true labels. Mean squared error for numbers; cross-entropy for classes.
- Backward pass (backpropagation): compute the gradient of the loss with respect to every weight.
- Optimiser step: update every weight a little in the direction that lowers the loss (gradient descent from module 5).
- Repeat for every mini-batch; one pass over all the data is an epoch.
Cross-entropy loss
For classification, the network outputs probabilities with softmax. Cross-entropy loss for one example is −ln(probability given to the correct class). If the right class gets 0.9, the loss is about 0.105. If it gets 0.05, the loss is about 3.0. So the network is pushed to put high probability on the right answer. Binary cross-entropy (log loss, module 5) is the two-class version.
Backpropagation in plain words
A deep network has millions of weights, and changing any one of them changes the loss a tiny bit. Backpropagation computes all these effects efficiently by going backwards from the loss, layer by layer, using the chain rule of calculus: the effect of a weight on the loss equals its effect on the next layer times that layer's effect on the loss, and so on. You never do this by hand in practice; frameworks like PyTorch record the forward pass and compute gradients automatically (autograd).
One tiny worked step
Take one neuron with no activation: prediction = w·x + b, with w = 0.5, b = 0, input x = 2 and target y = 3. Prediction is 1, error is 1 − 3 = −2, and the squared-error loss is 4. The gradients are: d(loss)/dw = 2 × error × x = −8, and d(loss)/db = 2 × error = −4. With learning rate 0.05: w becomes 0.5 − 0.05 × (−8) = 0.9 and b becomes 0 − 0.05 × (−4) = 0.2. The new prediction is 0.9 × 2 + 0.2 = 2.0, closer to 3.
Optimisers
Plain stochastic gradient descent (SGD) uses the same learning rate for every weight. SGD with momentum keeps a running direction, like a ball rolling downhill, which speeds up and smooths training. Adam adapts the step size for each weight based on recent gradients and is a popular default. Learning-rate schedules lower the rate as training goes on.
import torch
from torch import nn
model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 3))
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(10):
for X_batch, y_batch in train_loader:
optimizer.zero_grad() # clear old gradients
loss = loss_fn(model(X_batch), y_batch)
loss.backward() # backpropagation
optimizer.step() # update the weightsKeeping networks from overfitting
- Dropout: during training, randomly switch off a share of neurons (say 20%) in each step, so the network cannot rely on any single path.
- Weight decay (L2 regularisation): penalise large weights.
- Early stopping: watch the validation loss and stop when it stops falling.
- Data augmentation: for images, train on flipped, cropped or slightly rotated copies, so the network sees more variety.
- More data, or a smaller network.
Common mistakes
- Forgetting optimizer.zero_grad(), so gradients pile up from previous batches.
- Applying softmax before nn.CrossEntropyLoss, which already includes it.
- Only watching training loss. Plot validation loss too; when it rises while training loss falls, you are overfitting.
- Vanishing gradients in very deep networks with sigmoid activations; ReLU and careful initialisation help.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Training: loss, backpropagation and optimisers · 1/7
Training repeats four steps: forward pass, loss, backward pass, and an optimiser step.
Prefer a video by a teacher? Find free videos on “backpropagation explained neural network training loop pytorch” on YouTube ↗
In real life: Training a crop-disease classifier
An agri-tech team trains a network to recognise common leaf diseases from farmers' phone photos. They use cross-entropy loss, the Adam optimiser and data augmentation (random flips, brightness changes) because photos come from many phones and lighting conditions. Validation loss is checked after every epoch, and training stops when it has not improved for five epochs. The best checkpoint, not the last one, is shipped.
Practice (0/2 done)
Write cross_entropy(probs, correct) where probs is a list of class probabilities and correct is the index of the true class. Return −ln(probs[correct]) rounded to 4 decimal places. If the probability is 0, use 1e-15 instead to avoid log(0).
Do one training step for a single neuron with no activation and squared-error loss. Write sgd_step(w, b, x, y, lr): pred = w·x + b; error = pred − y; grad_w = 2·error·x; grad_b = 2·error; return (round(w − lr·grad_w, 4), round(b − lr·grad_b, 4)).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- CNNs, RNNs and transformers at a glanceNeural networks and deep learning · same module
- The artificial neuronNeural networks and deep learning · same module
- Decision treesk-NN, decision trees and ensembles
- Overfitting, underfitting and regularisationEvaluating models
- Gradient boostingk-NN, decision trees and ensembles
- Scaling and transforming numbersClustering, dimensionality reduction and feature engineering
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does backpropagation compute?
Answer: The gradient of the loss with respect to every weight
It applies the chain rule backwards through the network.
In PyTorch, what happens if you forget optimizer.zero_grad()?
Answer: Gradients from earlier batches add up and the updates become wrong
PyTorch accumulates gradients by default.
Training loss keeps falling but validation loss starts rising. What is happening?
Answer: Overfitting
The network is memorising the training data; consider early stopping.
What does dropout do during training?
Answer: Randomly switches off some neurons in each step
It stops the network relying on any single neuron.
Which optimiser adapts the step size for each weight and is a common default?
Answer: Adam
Adam keeps running averages of gradients per weight.
At the current weight the gradient of the loss is positive. What should gradient descent do?Related
Answer: Decrease the weight
Positive slope means the loss rises as w rises, so step the other way.
Which prediction gives the LARGEST log loss when the true label is 1?Related
Answer: p = 0.02
A confident wrong answer (p near 0 for a true 1) is punished most.
A tree trained on flats priced ₹30–90 lakh is asked about a much bigger flat. What will it predict at most?Related
Answer: No more than the highest leaf average, around ₹90 lakh
Trees predict leaf averages, so they cannot go beyond the training range.
From Decision trees
Which method can set some weights to exactly zero?Related
Answer: Lasso (L1)
The L1 penalty pushes small weights all the way to zero.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Neural networks and deep learning” before its exam: CNNs, RNNs and transformers at a glance, Deep learning tools and hardware.
- Module 9 exam: Neural networks and deep learning · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, NLP, embeddings and large language models. 62 topics left in the course before the final exam.