Every neural network learns in the same way: it measures how wrong it is, then nudges its weights to be a little less wrong. This module explains both halves of that idea: the loss function that measures the error, and gradient descent, the method that reduces it.
- Level: Beginner
- Time: about 40 minutes
- Needs: Modules 1 to 3
By the end of this module you will be able to
- Explain what a loss function measures
- Choose the right loss for regression and classification
- Describe the loss landscape and what "going downhill" means
- Apply the gradient descent update by hand
- Explain how the learning rate affects training
- Explain batches, mini-batches and epochs
- Describe momentum and the Adam optimiser
- Code gradient descent from scratch in NumPy
4.1What is a loss function?
A network can't improve unless it knows how wrong it is. A loss function (also called a cost function) turns every mistake into a single number: the loss. A big loss means bad predictions; a loss of zero means perfect ones.
The whole of training in one sentence
Training a neural network means finding the weights that make the loss as small as possible.
Like a satnav
A satnav constantly measures one number: how far you are from your destination. Every turn it recommends is chosen to make that number smaller. The loss is the network's "distance to destination", and gradient descent is its satnav.
4.2Choosing a loss function
You've met most of these in the Machine Learning track. The right choice depends on the task, and it goes hand in hand with the output activation from Module 3.
| Task | Loss function | What it measures | Keras name |
|---|---|---|---|
| Regression | Mean squared error (MSE) | Average of the squared errors; punishes big misses | "mse" |
| Regression with outliers | Mean absolute error (MAE) | Average size of the errors; less upset by extreme values | "mae" |
| Binary classification | Binary cross-entropy (log loss) | Punishes confident wrong probabilities very hard | "binary_crossentropy" |
| Multi-class classification | Categorical cross-entropy | The same idea, across several classes with softmax | "sparse_categorical_crossentropy" |
Cross-entropy, in plain English
For classification, the loss only looks at the probability the network gave to the correct answer. If the correct digit is 7:
| Probability given to "7" | Cross-entropy loss | Verdict |
|---|---|---|
| 0.95 | 0.05 | Confident and right: tiny penalty |
| 0.50 | 0.69 | Unsure: medium penalty |
| 0.05 | 3.00 | Confident and wrong: big penalty |
The loss is calculated as −log(probability of the correct answer). You don't need to calculate it by hand; just remember it rewards being confidently right and heavily punishes being confidently wrong.
4.3The loss landscape
Imagine every possible combination of weights as a location on a map, and the loss as the height at that location. The result is a landscape of hills and valleys. Training means finding the lowest valley.
Walking down a mountain in fog
You're on a mountain in thick fog and want to reach the valley. You can't see the bottom, but you can feel the slope under your feet. So you take a step in the steepest downhill direction, feel again, and repeat. That's gradient descent. The risk: you might end up in a small dip (a local minimum) rather than the lowest valley. In practice, big networks have so many dimensions that there's usually a way downhill, so this is less of a problem than it sounds.
4.4Gradient descent
The gradient is the slope of the loss for each weight: it says which direction is uphill, and how steeply. To go downhill, we step in the opposite direction:
| If the gradient is… | It means… | So the weight… |
|---|---|---|
| Positive (+) | Increasing this weight increases the loss | Goes down |
| Negative (−) | Increasing this weight decreases the loss | Goes up |
| Close to 0 | We're near a flat spot, hopefully the bottom | Barely changes |
A worked example
A weight is currently 5. The gradient of the loss for this weight is 4 (uphill to the right). With a learning rate of 0.1:
The weight moves a little to the left, downhill. Next step, we measure the new gradient and repeat. A real network does this for every weight at once. Working out all those gradients efficiently is the job of backpropagation, in Module 5.
4.5The learning rate
The learning rate sets how big each step is. It's one of the most important settings in deep learning. Try it: the ball starts on the left and wants to reach the bottom of the curve.
Try it: roll down the loss curve
| Learning rate | What happens |
|---|---|
| Too small | Tiny, safe steps, but training takes forever |
| Just right | Reaches the bottom quickly and settles |
| A bit too big | Overshoots and bounces from side to side before settling |
| Far too big | Each step overshoots more than the last: the loss explodes (divergence) |
Common starting values are 0.001 for the Adam optimiser and 0.01 for plain gradient descent. If your loss shoots up to huge numbers or becomes nan ("not a number"), the learning rate is usually too high.
4.6Batches, mini-batches and epochs
Should the network look at every training example before taking one step, or take a step after each one? There are three options:
| Method | Examples per step | Pros | Cons |
|---|---|---|---|
| Batch gradient descent | All of them | Smooth, accurate steps | Very slow and memory-hungry with big datasets |
| Stochastic gradient descent (SGD) | 1 | Fast, frequent updates | Very noisy, jumpy path |
| Mini-batch gradient descent | A small group, e.g. 32 | The best of both; makes good use of GPUs | One more setting to choose |
Mini-batches are the standard. Three words you'll see all the time:
| Term | Meaning | Example: 1,000 images, batch size 32 |
|---|---|---|
| Batch size | Examples used for each weight update | 32 |
| Iteration (step) | One weight update | 1 update per batch of 32 |
| Epoch | One full pass through the whole training set | 1,000 ÷ 32 ≈ 32 iterations |
4.7Smarter optimisers: momentum and Adam
Plain gradient descent has a weakness. In long, narrow valleys, the steepest direction points across the valley rather than along it, so it zigzags from side to side. Modern optimisers fix this.
| Optimiser | Idea | Analogy |
|---|---|---|
| SGD | Plain gradient descent on mini-batches | Walking downhill, one careful step at a time |
| Momentum | Keeps a running average of recent steps, so it speeds up in a consistent direction | A ball rolling downhill, building speed |
| RMSprop | Gives each weight its own step size, smaller for weights with big, jumpy gradients | Taking smaller steps on steep, slippery ground |
| Adam | Combines momentum and RMSprop | A heavy ball with smart brakes |
What should I use?
Adam with its default learning rate (0.001) is the usual starting point. It works well on most problems with little tuning. In Keras: optimizer="adam".
4.8Gradient descent from scratch in Python
Let's write gradient descent ourselves in NumPy. We'll create data that follows the rule y = 3x + 2 (plus noise), start with a terrible guess of y = 0x + 0, and let gradient descent find the rule. Then we'll try three learning rates.
import numpy as np
# 1. Some data: y is roughly 3x + 2, plus noise
rng = np.random.default_rng(0)
x = rng.uniform(0, 2, 100)
y = 3 * x + 2 + rng.normal(0, 0.3, 100)
def mse(y_true, y_pred):
return np.mean((y_true - y_pred) ** 2)
# 2. Gradient descent: start with a bad guess and improve it step by step
def train(learning_rate, steps=200):
w, b = 0.0, 0.0 # starting guess
history = []
for step in range(steps):
y_pred = w * x + b # forward pass
loss = mse(y, y_pred) # how wrong are we?
grad_w = -2 * np.mean(x * (y - y_pred)) # slope of the loss for w
grad_b = -2 * np.mean(y - y_pred) # slope of the loss for b
w -= learning_rate * grad_w # step downhill
b -= learning_rate * grad_b
history.append(loss)
return w, b, history
w, b, history = train(learning_rate=0.1)
for step in [0, 10, 50, 199]:
print(f"Step {step:3}: loss = {history[step]:.4f}")
print(f"Learned: y = {w:.2f}x + {b:.2f} (true rule: y = 3x + 2)")
# 3. The learning rate matters
print()
for lr in [0.001, 0.1, 0.9]:
w, b, h = train(lr)
print(f"learning rate {lr:<5}: final loss = {h[-1]:.4g}, w = {w:.3g}, b = {b:.3g}")
Step 0: loss = 31.0796 Step 10: loss = 0.0895 Step 50: loss = 0.0850 Step 199: loss = 0.0846 Learned: y = 2.98x + 2.00 (true rule: y = 3x + 2) learning rate 0.001: final loss = 4.593, w = 1.77, b = 1.35 learning rate 0.1 : final loss = 0.0846, w = 2.98, b = 2 learning rate 0.9 : final loss = 3.82e+210, w = -3.33e+105, b = -2.58e+105
What the output tells us
- The loss falls fast: from 31.1 at the start to 0.09 after just 10 steps, then it levels off. It can't reach zero, because the data contains random noise.
- Gradient descent found the rule by itself: y = 2.98x + 2.00, extremely close to the true y = 3x + 2.
- A learning rate of 0.001 is too small: after 200 steps it's still far from the answer (w = 1.77).
- A learning rate of 0.9 is far too big: every step overshoots further, and the numbers explode to around 10210. This is divergence.
grad_wandgrad_bare the slopes of the MSE loss, worked out with calculus. In real networks you never write these yourself: Keras and PyTorch calculate them automatically (Module 5).
SummaryKey takeaways
- A loss function turns a network's mistakes into one number. Training means making it as small as possible.
- Use MSE (or MAE) for regression and cross-entropy for classification.
- The loss landscape is like a mountain range; training looks for the lowest valley.
- Gradient descent: new weight = weight − learning rate × gradient.
- The learning rate sets step size: too small is slow, too big overshoots or explodes.
- Mini-batches (e.g. 32 examples) are the standard; an epoch is one full pass through the data.
- Momentum builds speed, Adam adapts step sizes; Adam is the usual default.
Check your understanding
Your neural networks roadmap
- 01Introduction to Neural NetworksWhat neural networks are and how they work
- 02The Perceptron and the Artificial NeuronBuild a single neuron from scratch
- 03Activation FunctionsSigmoid, tanh, ReLU and softmax
- 04Loss Functions and Gradient DescentYou are here
- 05BackpropagationHow every weight learns its share of the blame
- 06Building Networks with KerasYour first deep learning library
- 07Training Better NetworksOverfitting, dropout, batch normalisation, early stopping
- 08Convolutional Neural NetworksTeaching computers to see
- 09Recurrent Neural Networks and LSTMsWorking with sequences
- 10Transformers and AttentionThe architecture behind ChatGPT and Claude
- 11Transfer Learning and Pretrained ModelsStanding on the shoulders of giants
- 12Capstone ProjectBuild and present a deep learning project
Next module
Backpropagation