Gradient descent and backpropagation: how a network adjusts its weights to make fewer mistakes

A neural network starts with random weights, so its first predictions are noise. By the end of training, it gets things right. What happens in between? According to the scikit-learn documentation, the multi-layer perceptron starts from random initial weights and minimises the loss function by repeatedly updating those weights. That one sentence contains the whole article. Let’s open it up, piece by piece.

A loop, not a mystery

Training is a repeated cycle: predict, measure how wrong you were, and nudge the weights in the direction that reduces that error. No magic, just a loop that runs many times.

I assume you already know what a neuron, a layer and an activation are; if you need a refresher, there is the guide to how neural networks work. Here we go deeper into how the weights are adjusted during training. There are four pieces: the loss (how wrong you are), the gradient (which way to correct), the learning rate (how far to correct) and backpropagation (how the gradient for all the weights is calculated at once).

The loss function: putting a number on the error

To reduce the error, you first have to turn it into a number. That is the loss function. According to scikit-learn, the multi-layer perceptron uses mean squared error for regression and cross-entropy for classification. Rumelhart, Hinton and Williams framed it in 1986, in their Nature paper, as minimising a measure of the difference between the network’s actual output vector and the desired one.

For the rest of the article we will use the smallest example possible: a single neuron with a weight w and a bias b fitting a line to some points. The prediction is w·x + b and the loss is the mean of the squared errors:

L = mean((w·x + b − y)²)

Squaring means the error is never negative and large misses weigh far more than small ones. The loss depends on w and b: each pair of values gives a different error. Training is the search for the pair that makes it small.

The gradient: which way is down

Picture the loss as a landscape where each weight is a coordinate and the height is the error. The gradient is the vector of partial derivatives: it points in the direction where the ground rises most steeply. That is why, as Dive into Deep Learning explains, the direction of steepest descent is the negative gradient, −∇f(x).

Here is a toy example from that same chapter: f(x) = x₁² + 2·x₂², with gradient [2·x₁, 4·x₂]. Starting from [−5, −2], the gradient is [−10, −8]. Each component is the derivative with respect to a single variable: it tells you how much f changes if you move only that coordinate. The 2 multiplying x₂² in the function makes its derivative grow twice as fast per unit of x₂, but that does not mean its slope is steeper at this point: here it is smaller in absolute value (8 against 10), because x₂ is closer to zero.

The same happens in a network, but with one partial derivative of the loss for each weight. A large network has a great many of them; the gradient is the list of all of them.

Gradient descent and the learning rate

Once you have the gradient, the update rule fits on one line. Dive into Deep Learning writes it as x ← x − η∇f(x), and scikit-learn writes it as W(i+1) = Wi − ε∇Loss. They are the same thing: η (or ε) is the learning rate, a number greater than 0 that sets the size of the step.

Gradient descent on a loss curveA U-shaped curve represents the loss as a function of the value of one weight. Four points go down the left branch towards the minimum; the steps are long at first, where the slope is steep, and shorter as they approach the bottom.Each step: subtract η times the slopeMinimumWeight value →Loss

The size of the step matters. If the rate is too small, the update moves very slowly and you need more iterations: in the single-variable example on d2l.ai, f(x) = x², with η = 0.05, after 10 steps we are still very far from the optimal solution. If it is too large, you overshoot the bottom and can end up higher than where you started (you will see this for yourself in the code).

Work it out with the two-variable example and η = 0.1, the value d2l.ai uses: x₁ becomes 0.8 times its previous value and x₂ becomes 0.6 times. In the first step, x₁ moves by 1 and x₂ by 0.8. In absolute distance x₁ moves more, but proportionally x₂ gets closer to zero faster.

When does it stop? According to scikit-learn, when a preset maximum number of iterations is reached or when the improvement in the loss falls below a small value.

My opinion, not a fact: if training goes badly, η is the first hyperparameter I would look at.

Backpropagation: the gradient for every weight

Here is the most common confusion: backpropagation does not update the weights. It is the method for calculating the gradient of the network’s parameters, according to Dive into Deep Learning. What uses that gradient to move the weights is gradient descent. Two separate tasks, which alternate at every step.

The trick is to walk through the network in reverse order, from output to input, applying the chain rule from calculus. Scikit-learn describes it like this: after the loss is calculated, a backward pass propagates it from the output layer to the earlier ones and gives each weight an update value meant to reduce it.

Forward pass and backward passThree boxes in a row: input and weights, prediction and loss. An upper arrow runs through them from left to right (forward pass) and a lower arrow from right to left (backpropagation of the gradients).Input and weightsPredictionLossForward pass →← Backpropagation: gradients

Two practical details. First, backpropagation reuses the intermediate values stored during the forward pass so it does not repeat calculations, which means they have to be kept until it finishes. Second, for that very reason, according to d2l.ai training needs considerably more memory than inference.

Libraries automate this calculation. The PyTorch documentation has an example with Q = 3a³ − b²: its derivatives are ∂Q/∂a = 9a² and ∂Q/∂b = −2b, and calling .backward() leaves them in the .grad attribute of a and b, without you having to write them out.

A brief historical note: in 1986 Rumelhart, Hinton and Williams presented backpropagation as a new procedure for networks of neuron-like units. According to the authors, it makes the hidden units end up representing important features of the task, and this ability to create new features sets it apart from earlier, simpler methods such as the perceptron convergence procedure. The wider debate about its scope is the territory of our colleague Kia; if you want the research context, she is the one to follow.

The complete loop in code

Code makes it clearer. One neuron, data generated from a known line (w = 2, b = 1, plus a little noise) so that we know what the right answer is, and the whole cycle written by hand. The script checks itself: if anything goes wrong, an assert fails.

import numpy as np

rng = np.random.default_rng(42)           # fixed seed
x = np.linspace(-1, 1, 20)
y = 2.0 * x + 1.0 + rng.normal(0, 0.05, size=x.shape)  # true line + noise

def perdida(w, b):
    return np.mean((w * x + b - y) ** 2)

def gradiente(w, b):
    error = w * x + b - y                  # pred - y
    # chain rule: dL/dpred = 2*error/n, dpred/dw = x, dpred/db = 1
    return np.mean(2 * error * x), np.mean(2 * error)

w, b = rng.normal(size=2)                  # random initial weights
tasa = 0.1
perdida_inicial = perdida(w, b)

# gradient check with finite differences (starting point)
eps = 1e-6
gw, gb = gradiente(w, b)
gw_num = (perdida(w + eps, b) - perdida(w - eps, b)) / (2 * eps)
gb_num = (perdida(w, b + eps) - perdida(w, b - eps)) / (2 * eps)
assert np.allclose([gw, gb], [gw_num, gb_num], atol=1e-6)

for paso in range(500):
    gw, gb = gradiente(w, b)               # backward pass
    w -= tasa * gw                         # update: subtract the gradient
    b -= tasa * gb

print("initial loss:", perdida_inicial)
print("final loss:  ", perdida(w, b))
print("learned w and b:", w, b, "(expected: close to 2 and 1)")
assert perdida(w, b) < perdida_inicial
assert abs(w - 2.0) < 0.1 and abs(b - 1.0) < 0.1
print("OK")

What each part does:

  • Forward pass: w * x + b gives the prediction for every point, and perdida boils it down to a single number.
  • Gradient: gradiente applies the chain rule by hand. The loss depends on the error, the error on the prediction, and the prediction on w and b; you multiply the derivatives of each link. It is backpropagation for a single neuron.
  • Update: w -= tasa * gw is x ← x − η∇f(x) applied to each parameter.
  • Gradient check: the finite difference estimates the derivative by measuring how much the loss changes when you move the weight by a tiny amount. If it matches the analytical derivative, the formula is correct.

What you should see when you run it: the final loss is lower than the initial one, w and b end up close to 2 and 1 (not exact, because of the noise in the data), and the program finishes by printing “OK” without any assert failing.

The same thing with PyTorch

According to the autograd tutorial, calling .backward() on the error tensor starts backpropagation and leaves each parameter’s gradients in its .grad attribute; an optimiser such as SGD then applies the update. This program runs as it stands and checks itself. The formulas for Q are those from the documentation; I chose the values 2 and 3 myself:

import torch

a = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(3.0, requires_grad=True)
Q = 3 * a**3 - b**2
Q.backward()

# expected: dQ/da = 9*a**2 = 36 and dQ/db = -2*b = -6
print(a.grad.item(), b.grad.item())
assert a.grad.item() == 36.0
assert b.grad.item() == -6.0
print("OK")

Common mistakes

  • A badly chosen learning rate. Too small: the loss goes down, but very slowly. Too large: expect the loss to rise or oscillate instead of falling. Change tasa in the code and see for yourself.
  • Confusing backpropagation with gradient descent. The first calculates the gradient; the second uses it to update the weights.
  • Adding the gradient instead of subtracting it. The gradient points towards where the loss rises. If you add it, you climb the hill.
  • Looking only at the training loss. My opinion: the fact that it goes down does not guarantee the model will work on new data. A model can memorise. We cover that in the article on overfitting.

Practice

  • Change tasa to much smaller and much larger values, and print the loss every so many steps. Notice which one goes down slowly and which one runs out of control.
  • Add a second weight: use x**2 as a second input and extend gradiente with the corresponding derivative. Check the derivative with the finite difference.
  • Reproduce the d2l.ai example: f(x) = x₁² + 2·x₂², gradient [2·x₁, 4·x₂], starting from [−5, −2] with η = 0.1. Print the position at each step and check that x₁ is multiplied by 0.8 and x₂ by 0.6. Which one moves more in absolute distance at the start, and which one gets closer to zero sooner in proportion?
  • Challenge: remove gradiente and train using only the finite difference. Use assert to check that the final result is similar.

To continue, if you want to see which types of network exist and what each is for, move on to types of neural networks. The loop you have written here is the same in all of them.

Sources

Image: Hans on Pixabay

Translated and adapted by Ollie.

Leave a comment