Learning path: Neural Networks from Scratch to Embeddings · Step 3 of 9
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
What you will learn
- Score a mistake with MSE for numbers and cross-entropy for classes
- Explain why cross-entropy punishes a confident wrong answer the hardest
- Pass the blame backwards through a chain by hand with the chain rule
- Get the same gradients with PyTorch loss.backward() and use them for one update step
Before you start
- The Forward Pass and Activation Functions
- Gradient Descent Explained
Imagine a football match. The ball goes from the midfield to the defender to the keeper, and the team concedes a goal. After the match, the coach plays the footage backwards, from the goal to the midfield. Each player hears how much they gave away: the keeper 20%, the defender 50%, the midfield 30%. Nobody gets all the blame; everybody gets a share.
Training a network works the same way. The goal conceded is the loss. The backwards review is backpropagation. Each player's share is a gradient. The network is the team, and every weight is a player.
Scoring the mistake: MSE and cross-entropy
We need one number that says how wrong the network was. Which number depends on what we predict:
- Predicting a number? Use the mean squared error (MSE): the gap, squared.
- Picking a class? Use cross-entropy: minus the log of the probability the network gave to the right class.
For cross-entropy we reuse example two from the forward-pass article. Its softmax output was 0.13, 0.62 and 0.26, but the right answer was class 2, so the network gave only 0.26 to the correct class.
import numpy as np
import torch
# MSE: the guess was 6, the truth was 10
y_hat, y = 6.0, 10.0
print("MSE:", (y_hat - y) ** 2)
# cross-entropy: example 2, right class 2
P = np.array([0.13, 0.62, 0.26])
true_class = 2
p = P[true_class]
print("cross-entropy:", round(-np.log(p), 2))
MSE: 16.0
cross-entropy: 1.35
A gap of 4, squared, is 16. And -log(0.26) is 1.35.
Confident and wrong hurts most
Why is cross-entropy so good for classes? Try four different probabilities for the right class:
# the probability the network gave to the RIGHT class
for p in [0.9, 0.62, 0.26, 0.05]:
print(f"p = {p:<5} loss = {-np.log(p):.2f}")
p = 0.9 loss = 0.11
p = 0.62 loss = 0.48
p = 0.26 loss = 1.35
p = 0.05 loss = 3.00
Sure and right (0.9) costs only 0.11. At 0.05 the network was sure it was something else, and the loss shoots up to 3. A confident wrong answer is punished the hardest, which is exactly what we want.
Passing the blame backwards
How does each weight find its share? Take the smallest network possible, a chain with two weights:
x = 2h = w1 * x = 1.5 * 2 = 3y_hat = w2 * h = 2 * 3 = 6- The truth is 10, so the loss is
(6 - 10)² = 16.
Now walk backwards. The blame on y_hat is 2 * (y_hat - y) = -8. Each step back multiplies the blame by whatever it was multiplied by on the way forward:
In Python, the same steps:
x, y = 2.0, 10.0
w1, w2 = 1.5, 2.0
h = w1 * x
y_hat = w2 * h
loss = (y_hat - y) ** 2
d_yhat = 2 * (y_hat - y)
d_w2 = d_yhat * h
d_h = d_yhat * w2
d_w1 = d_h * x
print(h, y_hat, loss)
print(d_yhat, d_w2, d_h, d_w1)
3.0 6.0 16.0
-8.0 -24.0 -16.0 -32.0
What does a negative gradient mean? If we increase that weight, the loss goes down.
PyTorch does it: loss.backward()
Nobody writes these steps by hand for 101,770 weights. PyTorch's autograd does it. Mark the weights with requires_grad=True so PyTorch keeps track of them, run the forward pass, and call one line:
w1 = torch.tensor(1.5, requires_grad=True)
w2 = torch.tensor(2.0, requires_grad=True)
y_hat = w2 * (w1 * 2.0)
loss = (y_hat - 10.0) ** 2
loss.backward()
print("loss:", loss.item())
print("w1.grad:", w1.grad.item())
print("w2.grad:", w2.grad.item())
loss: 16.0
w1.grad: -32.0
w2.grad: -24.0
Exactly the numbers we got by hand. On the digit network, the same single backward() call fills a gradient for every one of its 101,770 weights and biases.
One small nudge
What do we do with the blame? We use the update rule from Gradient Descent Explained: new weight = weight - learning rate x gradient.
lr = 0.01
with torch.no_grad():
w1 -= lr * w1.grad
w2 -= lr * w2.grad
new_loss = (w2 * (w1 * 2.0) - 10.0) ** 2
print("w1:", round(w1.item(), 2))
print("w2:", round(w2.item(), 2))
print("loss before:", loss.item())
print("loss after:", round(new_loss.item(), 2))
w1: 1.82
w2: 2.24
loss before: 16.0
loss after: 3.41
Both weights step against their gradient: w1 from 1.5 to 1.82, w2 from 2 to 2.24. One small nudge, and the loss drops from 16 to 3.41. Training is this nudge, repeated many times; see The Training Loop.
Common mistakes
- Using MSE for classes. For picking a class, cross-entropy is the right loss.
- Taking the log of the wrong probability. Cross-entropy uses the probability of the right class only.
- Stepping with the gradient instead of against it. The rule subtracts:
w -= lr * grad. - Updating weights without
torch.no_grad(). The update itself should not be tracked by autograd.
Quick recap
| Idea | Code | Example |
|---|---|---|
| MSE for a number | (y_hat - y) ** 2 | (6 - 10)² = 16 |
| Cross-entropy for a class | -np.log(p) | -log(0.26) = 1.35 |
| Chain rule | d_w1 = d_h * x | -16 x 2 = -32 |
| Autograd | loss.backward() | w1.grad -32, w2.grad -24 |
| One nudge | w -= lr * w.grad | loss 16 to 3.41 |
Try it yourself
Set w1 = 3.0 and w2 = 2.0. The guess is now 12. What is the loss, what are the two gradients, and what do their signs tell you?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Next →The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.
Your First Neural Network with Keras: MNIST Digits at 97.7%
Build the 784-128-10 digit network in Keras in five steps: load and scale, Sequential with Flatten and Dense, compile, fit for ten epochs, and test once. It reads handwritten digits with 97.72% test accuracy.