How a Neural Network Learns

The chain rule, the gradient and gradient descent, by hand and by playing

Published

Oct. 2026

Introduction

A neural network is a function. You give it numbers (the pixels of an image, the words of a sentence turned into vectors, the measurements of a flower) and it gives back numbers: a prediction y^\hat y. The hat means predicted: the network’s answer, which we compare with the true answer yy.

What makes it a learning machine is that this function has knobs: thousands, sometimes billions of numbers, the weights and the biases, that decide what the function computes. We write them all in one big vector θ\theta, and the network as y^=fθ(x)\hat y = f_\theta(x).

Training the network means finding values of the knobs for which its predictions are close to the true answers, on examples where we know them. We measure “close” with a single number, the loss: the bigger it is, the worse the network. Training is then a minimization problem:

min⁡θ L(θ)\min_\theta \ \mathcal{L}(\theta)

For a model with two knobs, like a straight line y^=ax+b\hat y = a x + b, there is a formula that gives the best (a,b)(a, b) directly. For a network with millions of knobs there is none. Instead, we improve the knobs a little at a time:

θ0 → θ1 → θ2 → ⋯ → the “best” θ\theta_0 \ \to\ \theta_1 \ \to\ \theta_2 \ \to\ \cdots \ \to\ \text{the ``best'' } \theta

Each arrow answers the same question: in which direction should I turn each knob, and by how much, to lower the loss? This page builds the answer in four steps:

  1. The derivative tells how much a function’s output changes when you turn one knob.
  2. The chain rule computes that derivative for a function made of layers, which is what a network is: this is backpropagation.
  3. Gradient descent uses the derivative to walk downhill, one step at a time, and the learning rate sets the size of the steps.
  4. The gradient does the same for many knobs at once.

At the end, you will train a small model by hand, with pen and paper, and watch a real network train in your browser. All you need is to remember what a function is; section 0 recalls, quickly, the two other objects we need, vectors and matrices, and uses them to write what a network computes: the forward pass.

0. Vectors, matrices and the forward pass

0.1 Data are vectors

A vector is a list of numbers. In machine learning, every data point is one: an iris flower is the vector of its four measurements (sepal length and width, petal length and width), x∈R4x \in \mathbb{R}^4; a word, for a language model, is a vector of a few hundred numbers, its embedding.

Vectors add entry by entry, and multiply by a number entry by entry. The operation that matters most is the dot product, which multiplies two vectors entry by entry and sums the results:

u⋅v=u1v1+u2v2+⋯+unvnu \cdot v = u_1 v_1 + u_2 v_2 + \dots + u_n v_n

The length, or norm, of a vector is ∥u∥=u⋅u\|u\| = \sqrt{u \cdot u}, and dividing the dot product by the two lengths gives the cosine similarity, the cosine of the angle between the two vectors:

cos⁡(u,v)=u⋅v∥u∥ ∥v∥\cos(u, v) = \frac{u \cdot v}{\|u\|\,\|v\|}

It is 11 when the vectors point the same way, 00 when they are unrelated, −1-1 when they are opposite. This is how search engines and language models compare documents or words: two vectors that point the same way mean similar things.

0.2 A layer is a matrix

A matrix of size m×nm \times n is a table of numbers with mm rows and nn columns. Multiplied by a vector of Rn\mathbb{R}^n, it gives a vector of Rm\mathbb{R}^m: each entry of the result is the dot product of one row of the matrix with the vector.

(1201)(11)=(1×1+2×10×1+1×1)=(31)\begin{pmatrix} 1 & 2 \\ 0 & 1 \end{pmatrix} \begin{pmatrix} 1 \\ 1 \end{pmatrix} = \begin{pmatrix} 1 \times 1 + 2 \times 1 \\ 0 \times 1 + 1 \times 1 \end{pmatrix} = \begin{pmatrix} 3 \\ 1 \end{pmatrix}

The sizes must fit: an (m×n)(m \times n) matrix times an (n×1)(n \times 1) vector gives an (m×1)(m \times 1) vector, and the two inner sizes, nn, must be equal.

This product is exactly what a layer of a network computes. A layer with nn inputs and mm neurons multiplies its input xx by a weight matrix WW of size m×nm \times n, adds a bias vector bb, then applies an activation σ\sigma to each entry:

output=σ(Wx+b)\text{output} = \sigma(W x + b)

WW and bb are the knobs of the layer: with 2 inputs and 3 neurons, WW is 3×23 \times 2 and bb has 3 entries, so 9 knobs. A network stacks several such layers, the output of one being the input of the next.

0.3 The forward pass

Running a network on an input means computing its layers one after the other, from the input to the output: this is the forward pass. With one hidden layer and one output, it is two lines:

h=σ(W1x+b1),y^=W2 h+b2h = \sigma(W_1 x + b_1), \qquad \hat y = W_2\,h + b_2

The hidden layer turns the input xx into a vector hh, one entry per neuron; the output layer takes a weighted sum of these entries, with no activation. The knobs of the network are θ=(W1,b1,W2,b2)\theta = (W_1, b_1, W_2, b_2).

For example, with 2 inputs, 2 hidden neurons and the activation ReLU(z)=max⁡(0,z)\text{ReLU}(z) = \max(0, z), which keeps the positive numbers and replaces the negative ones by 00:

x=(12),W1=(10−11),b1=(0−2),W2=(21),b2=1x = \begin{pmatrix} 1 \\ 2 \end{pmatrix}, \quad W_1 = \begin{pmatrix} 1 & 0 \\ -1 & 1 \end{pmatrix}, \quad b_1 = \begin{pmatrix} 0 \\ -2 \end{pmatrix}, \quad W_2 = \begin{pmatrix} 2 & 1 \end{pmatrix}, \quad b_2 = 1 W1x+b1=(1−1),h=(10),y^=2×1+1×0+1=3W_1 x + b_1 = \begin{pmatrix} 1 \\ -1 \end{pmatrix}, \qquad h = \begin{pmatrix} 1 \\ 0 \end{pmatrix}, \qquad \hat y = 2 \times 1 + 1 \times 0 + 1 = 3

The second neuron receives a negative number and outputs 00: for this input, it plays no part in the prediction.

With a single input xx, the sizes shrink: W1W_1 is a column of nn weights wjw_j, W2W_2 a row of nn weights vjv_j, and b2b_2 a single number cc. The network becomes a function from R\mathbb{R} to R\mathbb{R},

y^=fθ(x)=∑j=1nvj σ(wjx+bj)+c\hat y = f_\theta(x) = \sum_{j=1}^{n} v_j\,\sigma(w_j x + b_j) + c

and a function from R\mathbb{R} to R\mathbb{R} can be drawn. Do the forward pass for every xx and you get a curve: the shape the network draws. With ReLU, each neuron adds one bend to it, and its knobs decide where the bend is and how steep. More neurons, more bends: with enough of them, a network can draw almost any shape.

The forward pass: what a network can draw Open the Space ↗
Each thin line is one neuron, vj σ(wj x + bj); the blue curve, their sum plus c, is the prediction. Drag on the plot to follow the forward pass for one x.
What to look at

Add neurons and try to fit the orange points by hand, turning one knob at a time. Then click Let backprop fit it: the knobs that fit exist, and the rest of this page is about how to find them: the derivative, then the backward pass.

1. The derivative: what happens when you turn one knob

1.1 A rate of change

Drive 120 km in 2 hours and your average speed is 60 km/h: the change of distance divided by the change of time. Your speedometer shows something else, the speed now: the same ratio, measured over a moment so short that the speed has no time to change.

The derivative is that speedometer, for any function. Between x0x_0 and x0+hx_0 + h, the function ff changes by f(x0+h)−f(x0)f(x_0 + h) - f(x_0), so its average rate of change is

f(x0+h)−f(x0)h\frac{f(x_0 + h) - f(x_0)}{h}

Make hh smaller and smaller. If this ratio settles on a finite value, ff is differentiable at x0x_0, and that value is its derivative:

f′(x0)=lim⁡h→0f(x0+h)−f(x0)hf'(x_0) = \lim_{h \to 0} \frac{f(x_0 + h) - f(x_0)}{h}

It is also written dfdx\dfrac{df}{dx}: a tiny change of ff, dfdf, divided by the tiny change of xx, dxdx, that caused it. On the graph of ff, it is the slope of the tangent at x0x_0.

For f(x)=x2f(x) = x^2, with a2−b2=(a+b)(a−b)a^2 - b^2 = (a + b)(a - b):

(x0+h)2−x02h=h (2x0+h)h=2x0+h →h→0 2x0\frac{(x_0 + h)^2 - x_0^2}{h} = \frac{h\,(2x_0 + h)}{h} = 2x_0 + h \ \xrightarrow[h \to 0]{} \ 2x_0

So f′(x0)=2x0f'(x_0) = 2x_0, at every point: the derivative is itself a function, f′(x)=2xf'(x) = 2x.

1.2 In practice: a table and a few rules

Nobody computes limits by hand every time. We use a table for the usual functions, and rules to combine them.

f(x)f(x)f′(x)f'(x)
cc (a constant)00
xnx^nn xn−1n\,x^{n-1}
exe^xexe^x
ln⁡x\ln x1/x1 / x
Rule
sum(u+v)′=u′+v′(u + v)' = u' + v'
constant factor(c u)′=c u′(c\,u)' = c\,u'
product(u v)′=u′v+u v′(u\,v)' = u'v + u\,v'

The sign of f′(x0)f'(x_0) says which way the function goes at x0x_0: up if it is positive, down if it is negative. Its size says how fast. Keep this in mind: it is all a computer needs to find which way is down.

Optional How does a computer compute a derivative?: finite differences or automatic differentiation

Give a computer a function, say y = 3 * x**2 + x. It can estimate f′(x)f'(x) in two ways.

Numerically, with finite differences: compute f(x+h)−f(x)h\frac{f(x + h) - f(x)}{h} with a small hh, like 10−510^{-5}. It is simple, but only approximate, and it needs one extra evaluation of the function per knob: far too many for a network.

Exactly, with automatic differentiation: the computer records every operation it makes (++, ×\times, powers, exp⁡\exp…) and applies the table and the rules above to each one. This is what PyTorch does when you call loss.backward(), and the next section explains how it chains the steps.

Exercise 1.2 Basic derivatives

Differentiate:

  1. f(x)=3x2+5x−2f(x) = 3x^2 + 5x - 2
  2. f(x)=x4−2xf(x) = x^4 - 2x
  3. f(x)=4ex+ln⁡xf(x) = 4e^x + \ln x
  4. f(x)=x exf(x) = x\,e^x (product rule)
Hint

Differentiate each term separately (sum rule), keeping the constant factors in front: (3x2)′=3×2x(3x^2)' = 3 \times 2x.

Hint

For question 4, set u=xu = x and v=exv = e^x, then (u v)′=u′v+u v′(u\,v)' = u'v + u\,v'.

Checkpoint what you should get

At x=1x = 1, the four derivatives are 1111, 22, 4e+1≈11.874e + 1 \approx 11.87 and 2e≈5.442e \approx 5.44.

Solution
  1. f′(x)=3×2x+5=6x+5f'(x) = 3 \times 2x + 5 = 6x + 5
  2. f′(x)=4x3−2f'(x) = 4x^3 - 2
  3. f′(x)=4ex+1xf'(x) = 4e^x + \dfrac{1}{x}, for x>0x > 0
  4. f′(x)=u′v+u v′=ex+x ex=(1+x) exf'(x) = u'v + u\,v' = e^x + x\,e^x = (1 + x)\,e^x

2. The chain rule: derivatives through the layers

2.1 A network is a chain of functions

Each layer of a network is a function: it takes the output of the previous layer and computes its own. The network is the composition of its layers,

y^=f3∘f2∘f1 (x)=f3(f2(f1(x)))\hat y = f_3 \circ f_2 \circ f_1\,(x) = f_3\big(f_2(f_1(x))\big)

with f1f_1 applied first. To train it, we need the derivative of such a composed function, and the table of section 1 has no line for it. The chain rule fills the gap. For two functions:

(f(g(x)))′=g′(x)×f′(g(x))ordf(g)dx=df(g)dg dgdx\big(f(g(x))\big)' = g'(x) \times f'\big(g(x)\big) \qquad\text{or}\qquad \frac{d f(g)}{dx} = \frac{d f(g)}{dg}\,\frac{dg}{dx}

In words: the derivative of the inside, times the derivative of the outside evaluated at the inside.

For example, k(x)=e(3x+1)2k(x) = e^{(3x + 1)^2} is three layers: h(x)=3x+1h(x) = 3x + 1, then g(x)=x2g(x) = x^2, then f(x)=exf(x) = e^x. One factor per layer, each evaluated at the input of its layer:

k′(x)=f′(g(h(x)))⏟e(3x+1)2×g′(h(x))⏟2(3x+1)×h′(x)⏟3=6(3x+1) e(3x+1)2k'(x) = \underbrace{f'\big(g(h(x))\big)}_{e^{(3x + 1)^2}} \times \underbrace{g'\big(h(x)\big)}_{2(3x + 1)} \times \underbrace{h'(x)}_{3} = 6(3x + 1)\,e^{(3x + 1)^2}

2.2 With n layers: forward, then backward

Name the intermediate values of a chain of nn layers: u0=xu_0 = x, u1=f1(u0)u_1 = f_1(u_0), …, un=fn(un−1)=y^u_n = f_n(u_{n-1}) = \hat y. The chain rule gives

dy^dx=dundun−1 dun−1dun−2⋯du1du0=fn′(un−1)×fn−1′(un−2)×⋯×f1′(u0)\frac{d\hat y}{dx} = \frac{d u_n}{d u_{n-1}}\,\frac{d u_{n-1}}{d u_{n-2}} \cdots \frac{d u_1}{d u_0} = f_n'(u_{n-1}) \times f_{n-1}'(u_{n-2}) \times \cdots \times f_1'(u_0)

The order of the computation follows: first go forward and compute every uku_k (the forward pass of section 0.3), since each factor needs the input of its layer; then go backward, from the output to the input, multiplying the factors as you go. Every layer reuses the product computed by the layer after it: nothing is computed twice.

2.3 Backpropagation

Now the knobs. The loss compares the prediction with the true answer, for example L=(y^−y)2\mathcal{L} = (\hat y - y)^2, and depends on every weight. To know which way to turn one weight ww, keep all the others fixed and look at how the loss changes:

L(w+h)−L(w)h →h→0 ∂L∂w\frac{\mathcal{L}(w + h) - \mathcal{L}(w)}{h} \ \xrightarrow[h \to 0]{} \ \frac{\partial \mathcal{L}}{\partial w}

The round ∂\partial instead of dd says that we differentiate with respect to one variable, the others being fixed: a partial derivative, more in section 4. Its sign says in which direction the loss changes when ww goes up; its size says by how much.

Try it on a network with a single knob: y^=w x\hat y = w\,x with x=2x = 2, y=1y = 1, and w=1w = 1. Turning the knob by hand from w=1w = 1 to w=1.01w = 1.01 moves y^\hat y from 22 to 2.022.02 and the loss from 11 to 1.04041.0404: a rate of change of 0.04040.01≈4\frac{0.0404}{0.01} \approx 4. The chain rule gives the same number, exactly and without trying:

∂L∂w=2(y^−y)⏟∂L/∂y^×x⏟∂y^/∂w=2×1×2=4\frac{\partial \mathcal{L}}{\partial w} = \underbrace{2(\hat y - y)}_{\partial \mathcal{L} / \partial \hat y} \times \underbrace{x}_{\partial \hat y / \partial w} = 2 \times 1 \times 2 = 4

The derivative is positive: turning ww up makes the loss worse, so we should turn it down, in the direction opposite to the derivative.

Backpropagation is this computation done for every weight of a network at once: the chain rule applied recursively, from the loss back to each parameter. One forward pass computes the prediction and the loss; one backward pass gives the derivative of the loss with respect to every weight.

Forward and backward pass, step by step Open the Space ↗
Each neuron is a weighted sum Σ followed by an activation σ. Step forward to compute the loss, then step backward: each step multiplies one more factor of the chain rule. Blue: values (forward); orange: derivatives of the loss (backward).
What to look at

Step backward one node at a time and read the orange numbers: each one is the number on its right times the derivative of one operation. Then click Gradient step: every weight moves against its derivative, and the loss goes down.

Exercise 2.3a Backprop in 2 layers

A tiny network with one neuron per layer and no activation:

h=w1 x,y^=w2 h,L=(y^−y)2h = w_1\,x, \qquad \hat y = w_2\,h, \qquad \mathcal{L} = (\hat y - y)^2

with x=1x = 1, y=2y = 2 (the true answer), w1=1w_1 = 1 and w2=3w_2 = 3.

  1. Forward: compute hh, y^\hat y and the loss.
  2. Backward: compute ∂L∂y^\frac{\partial \mathcal{L}}{\partial \hat y}, then ∂L∂w2=h ∂L∂y^\frac{\partial \mathcal{L}}{\partial w_2} = h\,\frac{\partial \mathcal{L}}{\partial \hat y} and ∂L∂h=w2 ∂L∂y^\frac{\partial \mathcal{L}}{\partial h} = w_2\,\frac{\partial \mathcal{L}}{\partial \hat y}.
  3. Compute ∂L∂w1=x ∂L∂h\frac{\partial \mathcal{L}}{\partial w_1} = x\,\frac{\partial \mathcal{L}}{\partial h}.
  4. To reduce the loss, should you turn w2w_2 up or down? And w1w_1?
Hint

L=u2\mathcal{L} = u^2 with u=y^−yu = \hat y - y, so ∂L∂y^=2u=2(y^−y)\frac{\partial \mathcal{L}}{\partial \hat y} = 2u = 2(\hat y - y).

Hint

Question 3 reuses ∂L∂h\frac{\partial \mathcal{L}}{\partial h} from question 2: this reuse is what makes backpropagation cheap.

Checkpoint what you should get

The loss is 11, and the two derivatives with respect to the weights are 22 and 66.

Solution
  1. h=1×1=1h = 1 \times 1 = 1,  y^=3×1=3\ \hat y = 3 \times 1 = 3,  L=(3−2)2=1\ \mathcal{L} = (3 - 2)^2 = 1.
  2. ∂L∂y^=2(3−2)=2\frac{\partial \mathcal{L}}{\partial \hat y} = 2(3 - 2) = 2,  ∂L∂w2=1×2=2\ \frac{\partial \mathcal{L}}{\partial w_2} = 1 \times 2 = 2,  ∂L∂h=3×2=6\ \frac{\partial \mathcal{L}}{\partial h} = 3 \times 2 = 6.
  3. ∂L∂w1=1×6=6\frac{\partial \mathcal{L}}{\partial w_1} = 1 \times 6 = 6.
  4. Both derivatives are positive: turning a weight up increases the loss. Turn both down.
What to notice

The prediction y^=3\hat y = 3 is too big compared with y=2y = 2, so both weights should shrink. But the loss is three times more sensitive to w1w_1 than to w2w_2: a step against the derivative moves w1w_1 three times more.

Exercise 2.3b Activation layers

Between the weighted sums, a network applies an activation, a simple function of one number. The two classics:

ReLU(x)=max⁡(0,x)σ(x)=11+e−x (sigmoid)\text{ReLU}(x) = \max(0, x) \qquad\qquad \sigma(x) = \frac{1}{1 + e^{-x}} \ \text{(sigmoid)}
  1. Compute ReLU(−2)\text{ReLU}(-2) and ReLU(3)\text{ReLU}(3).
  2. What is ReLU′(x)\text{ReLU}'(x) for xx negative? For xx positive?
  3. Let k(x)=ReLU(2x−1)k(x) = \text{ReLU}(2x - 1). With the chain rule, compute k′(1)k'(1) and k′(0)k'(0).
  4. Compute σ(0)\sigma(0). Check that σ′(x)=σ(x) (1−σ(x))\sigma'(x) = \sigma(x)\,(1 - \sigma(x)), then compute σ′(0)\sigma'(0).
Hint

ReLU is 00 on the left of 00 and xx on its right: two straight lines, so two constant slopes.

Hint

For question 4, write σ=1u\sigma = \frac{1}{u} with u(x)=1+e−xu(x) = 1 + e^{-x}, and use (1u)′=−u′u2\left(\frac{1}{u}\right)' = -\frac{u'}{u^2}.

Checkpoint what you should get

k′(1)=2k'(1) = 2 and k′(0)=0k'(0) = 0;  σ(0)=12\ \sigma(0) = \frac{1}{2} and σ′(0)=14\sigma'(0) = \frac{1}{4}.

Solution
  1. ReLU(−2)=0\text{ReLU}(-2) = 0,  ReLU(3)=3\ \text{ReLU}(3) = 3.
  2. ReLU′(x)=0\text{ReLU}'(x) = 0 for xx negative, 11 for xx positive.
  3. k′(x)=2×ReLU′(2x−1)k'(x) = 2 \times \text{ReLU}'(2x - 1):  k′(1)=2×ReLU′(1)=2\ k'(1) = 2 \times \text{ReLU}'(1) = 2,  k′(0)=2×ReLU′(−1)=0\ k'(0) = 2 \times \text{ReLU}'(-1) = 0.
  4. σ(0)=12\sigma(0) = \frac{1}{2}. With u′=−e−xu' = -e^{-x}:
σ′(x)=e−x(1+e−x)2=11+e−x⏟σ(x)×e−x1+e−x⏟1−σ(x)soσ′(0)=14\sigma'(x) = \frac{e^{-x}}{(1 + e^{-x})^2} = \underbrace{\frac{1}{1 + e^{-x}}}_{\sigma(x)} \times \underbrace{\frac{e^{-x}}{1 + e^{-x}}}_{1 - \sigma(x)} \qquad\text{so}\qquad \sigma'(0) = \frac{1}{4}
What to notice

When the input of a ReLU is negative, its derivative is 00: the backward pass stops there, and the weights before it do not move. This is the “dead neuron” you can see in the Space above.

Bonus

At x=0x = 0 exactly, ReLU has no derivative: the slope jumps from 00 to 11. What do you think libraries like PyTorch do there?

3. Walking downhill: gradient descent

3.1 Where is the minimum?

At the bottom of a valley, the ground is flat: at a minimum of a smooth function, the tangent is horizontal and f′(x)=0f'(x) = 0. So the solutions of f′(x)=0f'(x) = 0 are the candidates. Only candidates, though: x3x^3, 1−x21 - x^2 and x2−1x^2 - 1 all have f′(0)=0f'(0) = 0, and the first one has no extremum at 00, it only pauses before going up again.

A minimum can also be local (the lowest point around it) or global (the lowest point everywhere). A curve with two valleys has two local minima, and only the deeper one is global.

Optional Sorting the candidates: sign tables and the second derivative

With the expression of ff, there are two classic ways to tell a minimum from a maximum.

The sign table of f′f'. If f′f' goes from negative to positive at the candidate, ff goes down then up: a minimum. From positive to negative: a maximum. No change of sign: no extremum, as for x3x^3 whose derivative 3x23x^2 is never negative.

The second derivative, f′′f'', the derivative of f′f'. It says whether the curve bends up, ∪\cup, convex, when f′′>0f'' > 0, or down, ∩\cap, concave, when f′′<0f'' < 0. At a candidate x0x_0:

  • f′(x0)=0f'(x_0) = 0 and f′′(x0)>0f''(x_0) > 0: a local minimum;
  • f′(x0)=0f'(x_0) = 0 and f′′(x0)<0f''(x_0) < 0: a local maximum;
  • f′(x0)=0f'(x_0) = 0 and f′′(x0)=0f''(x_0) = 0: we don’t know.

For x2−1x^2 - 1, f′′(x)=2f''(x) = 2 is positive everywhere: the minimum at 00 is global. Convexity around a point gives a local extremum; convexity everywhere gives the global one.

All of this needs the expression of ff, and equations we can solve. The loss of a network has millions of variables, and no one can solve L′(θ)=0\mathcal{L}'(\theta) = 0 for it. We need a method that only looks at the function where we are.

3.2 One step at a time

Stand on a hillside in the fog. You can’t see the valley, but you can feel the slope under your feet, so you take a step downhill, feel the slope again, take another step. The derivative is that slope: if f′(x)>0f'(x) > 0, the function goes up to the right, so the way down is to the left; if f′(x)<0f'(x) < 0, it is to the right. In both cases, move against the sign of the derivative:

xn+1=xn−η f′(xn)x_{n+1} = x_n - \eta\, f'(x_n)

This is gradient descent. The number η>0\eta > 0 is the learning rate, or step size: it sets how far each step goes. And since f′(xn)f'(x_n) is large where the slope is steep and small near the bottom, the steps shrink by themselves as we get closer: the tangent gives the direction and the magnitude of the step.

The learning rate is the one choice gradient descent leaves to you, and it matters. Play with it on the simplest valley, f(x)=x2f(x) = x^2:

The learning rate decides everything
Gradient descent on f(x) = x², from x₀ = −2.6. Each step multiplies x by (1 − 2η): small η, tiny steps; η between 0.5 and 1, the steps jump over the minimum and oscillate; η above 1, they get bigger at each step and diverge.

A too large η\eta jumps over the minimum, and can even diverge. A too small η\eta converges, but needs a large number of steps. For a network, each step costs a forward and a backward pass over the data, so the number of steps is the cost of training: choosing η\eta is a real trade-off, and much of practical deep learning is about it.

Gradient descent gets to a local minimum: the bottom of the valley it starts in, not necessarily the deepest one. The animation at the top of this page shows it: the point stops in the first valley it meets.

Exercise 3.2 Extrema by hand, then one step downhill

Let f(x)=x3−3xf(x) = x^3 - 3x.

  1. Compute f′(x)f'(x) and find the candidate extrema.
  2. Compute f′′(x)f''(x). Use it to say which candidate is a minimum and which is a maximum.
  3. Are they global extrema? Look at f(x)f(x) when x→+∞x \to +\infty and x→−∞x \to -\infty.
  4. Start at x0=2x_0 = 2 and do two steps of gradient descent with η=0.1\eta = 0.1. Which candidate are you heading to?
Hint

f′(x)=3x2−3f'(x) = 3x^2 - 3 factors as 3(x−1)(x+1)3(x - 1)(x + 1).

Hint

For question 4, apply xn+1=xn−ηf′(xn)x_{n+1} = x_n - \eta f'(x_n) twice, with f′(2)=9f'(2) = 9.

Checkpoint what you should get

Candidates −1-1 and 11;  x1=1.1\ x_1 = 1.1 and x2≈1.037x_2 \approx 1.037.

Solution
  1. f′(x)=3x2−3=3(x−1)(x+1)f'(x) = 3x^2 - 3 = 3(x - 1)(x + 1): candidates x=−1x = -1 and x=1x = 1.
  2. f′′(x)=6xf''(x) = 6x: f′′(−1)=−6<0f''(-1) = -6 < 0, a maximum, f(−1)=2f(-1) = 2;  f′′(1)=6>0\ f''(1) = 6 > 0, a minimum, f(1)=−2f(1) = -2.
  3. No: f(x)→+∞f(x) \to +\infty when x→+∞x \to +\infty and −∞-\infty when x→−∞x \to -\infty. They are local extrema only.
  4. x1=2−0.1×9=1.1x_1 = 2 - 0.1 \times 9 = 1.1, then f′(1.1)=0.63f'(1.1) = 0.63 and x2=1.1−0.063=1.037x_2 = 1.1 - 0.063 = 1.037: heading to the local minimum at x=1x = 1.
What to notice

The second step is ten times smaller than the first, with the same η\eta: the slope flattens near the minimum, and the steps shrink with it. From x0=−2x_0 = -2, the same steps would run towards −∞-\infty, since there is no valley on that side.

4. Many knobs at once: the gradient

4.1 Functions of several variables

A loss depends on all the knobs of the network, so we need functions of several variables. A function from Rn\mathbb{R}^n to Rm\mathbb{R}^m takes nn numbers and returns mm:

The names of the variables don’t matter: f(x,y)f(x, y), f(x1,x2)f(x_1, x_2) and f(w1,w2)f(w_1, w_2) are the same kind of function, and f(x)f(\mathbf{x}), with x\mathbf{x} in bold, means that the input is a vector. From now on we focus on functions from Rn\mathbb{R}^n to R\mathbb{R}: many numbers in, a single number out, like a loss.

4.2 Partial derivatives

The partial derivative ∂f∂xj\dfrac{\partial f}{\partial x_j} is the derivative of ff with respect to xjx_j, the other variables being fixed: turn the knob xjx_j only, and watch ff. In practice, treat every other variable as a constant and differentiate as usual, term by term:

f(x,y,z)=x y+x z+y z+x2+y2+z2f(x, y, z) = x\,y + x\,z + y\,z + x^2 + y^2 + z^2 ∂f∂x=y+z+0+2x+0+0=y+z+2x\frac{\partial f}{\partial x} = y + z + 0 + 2x + 0 + 0 = y + z + 2x

and in the same way ∂f∂y=x+z+2y\frac{\partial f}{\partial y} = x + z + 2y and ∂f∂z=x+y+2z\frac{\partial f}{\partial z} = x + y + 2z. Read ∂f∂y\frac{\partial f}{\partial y} as how much ff changes when yy changes.

The chain rule works with partial derivatives too. With y^=x1−x2\hat y = x_1 - x_2 and L=(y^−y)2\mathcal{L} = (\hat y - y)^2:

∂L∂x1=2(x1−x2−y)×1,∂L∂x2=2(x1−x2−y)×(−1)\frac{\partial \mathcal{L}}{\partial x_1} = 2(x_1 - x_2 - y) \times 1, \qquad \frac{\partial \mathcal{L}}{\partial x_2} = 2(x_1 - x_2 - y) \times (-1)

4.3 The gradient

Put all the partial derivatives in one vector, and you get the gradient:

∇f=(∂f∂x1, …, ∂f∂xn)\nabla f = \left( \frac{\partial f}{\partial x_1}, \ \dots, \ \frac{\partial f}{\partial x_n} \right)

One entry per variable, so a vector of size nn. The gradient is itself a function, from Rn\mathbb{R}^n to Rn\mathbb{R}^n: at each point x\mathbf{x}, it gives the vector ∇f(x)\nabla f(\mathbf{x}), which points in the direction where ff increases the fastest. For the bowl f(x1,x2)=x12+x22f(x_1, x_2) = x_1^2 + x_2^2, ∇f=(2x1,2x2)\nabla f = (2x_1, 2x_2) points away from the bottom, uphill, everywhere.

Gradient descent in several variables is the same rule as in section 3, with vectors. Each step goes against the gradient:

θk+1⏟n×1=θk⏟n×1−η⏟a number ∇L(θk)⏟n×1\underbrace{\theta_{k+1}}_{n \times 1} = \underbrace{\theta_k}_{n \times 1} - \underbrace{\eta}_{\text{a number}} \, \underbrace{\nabla \mathcal{L}(\theta_k)}_{n \times 1}

On the bowl L(θ1,θ2)=θ12+θ22\mathcal{L}(\theta_1, \theta_2) = \theta_1^2 + \theta_2^2, every step points straight at the centre, and the steps converge to θ∞=(0,0)\theta_\infty = (0, 0), the minimum.

Exercise 4.3 Partial derivatives and one step in 2D
  1. Let f(x,y)=x2+3xy+y2f(x, y) = x^2 + 3xy + y^2. Compute ∂f∂x\frac{\partial f}{\partial x}, ∂f∂y\frac{\partial f}{\partial y}, then ∇f(1,2)\nabla f(1, 2).
  2. Let g(x,y)=x2+y2g(x, y) = x^2 + y^2. Compute ∇g(x,y)\nabla g(x, y).
  3. Start at (x0,y0)=(2,1)(x_0, y_0) = (2, 1) and do one step of gradient descent on gg with η=0.25\eta = 0.25.
  4. Compute gg before and after the step. Where is the minimum of gg?
Hint

For ∂f∂x\frac{\partial f}{\partial x}, yy is a constant: 3xy3xy is ”3y3y times xx”, whose derivative is 3y3y.

Hint

A step in 2D is two steps in 1D done at the same time, one per coordinate: x1=x0−η∂g∂x(x0,y0)x_1 = x_0 - \eta \frac{\partial g}{\partial x}(x_0, y_0), and the same for yy.

Checkpoint what you should get

∇f(1,2)=(8,7)\nabla f(1, 2) = (8, 7); after the step, (x1,y1)=(1,0.5)(x_1, y_1) = (1, 0.5) and gg went from 55 to 1.251.25.

Solution
  1. ∂f∂x=2x+3y\frac{\partial f}{\partial x} = 2x + 3y (yy fixed),  ∂f∂y=3x+2y\ \frac{\partial f}{\partial y} = 3x + 2y (xx fixed),  ∇f(1,2)=(2+6, 3+4)=(8,7)\ \nabla f(1, 2) = (2 + 6, \ 3 + 4) = (8, 7).
  2. ∇g(x,y)=(2x,2y)\nabla g(x, y) = (2x, 2y).
  3. ∇g(2,1)=(4,2)\nabla g(2, 1) = (4, 2), so (x1,y1)=(2,1)−0.25×(4,2)=(1,0.5)(x_1, y_1) = (2, 1) - 0.25 \times (4, 2) = (1, 0.5).
  4. g(2,1)=5g(2, 1) = 5 and g(1,0.5)=1.25g(1, 0.5) = 1.25: the step lowered gg. The minimum is at (0,0)(0, 0), where ∇g=(0,0)\nabla g = (0, 0).
What to notice

The step went from (2,1)(2, 1) to (1,0.5)(1, 0.5): straight towards the centre, halving the distance. On this bowl, η=0.25\eta = 0.25 halves the distance at every step.

5. Training a network

5.1 The training loop

Everything is in place. Put all the weights and all the biases of the network in one vector, θ\theta, and train it by gradient descent on the loss:

θk+1=θk−η ∇L(θk)\theta_{k+1} = \theta_k - \eta\, \nabla \mathcal{L}(\theta_k)

where the gradient, one partial derivative per knob, is computed by backpropagation: the chain rule on all the layers. One step of training is always the same three moves:

  1. Forward: compute the predictions and the loss.
  2. Backward: compute ∇L\nabla \mathcal{L}, the derivative of the loss with respect to every parameter.
  3. Step: move every parameter against its derivative, θ←θ−η∇L\theta \leftarrow \theta - \eta \nabla \mathcal{L}.

Repeat until the loss stops going down.

5.2 Watch a network train

The Space below is a network with one hidden layer, learning a function from examples. Each step of gradient descent moves every weight and every bias by −η ∂L/∂θ-\eta\, \partial \mathcal{L} / \partial \theta: watch the curve fit the points, and the loss go down.

Training a neural network Open the Space ↗
Press Train, or go one step at a time. Update one parameter moves a single weight by its own step and shows the computation. Try a learning rate that is too large, and watch the loss explode as in section 3.

5.3 Train one by hand

Training a network by hand is long, but training the smallest model is not. Take two examples, (x,y)=(0,1)(x, y) = (0, 1) and (1,3)(1, 3), and the model y^=a x+b\hat y = a\,x + b: a straight line, with two knobs, aa and bb. The loss is the sum of the squared errors on the two examples:

L(a,b)=(a×0+b−1)2+(a×1+b−3)2=(b−1)2+(a+b−3)2\mathcal{L}(a, b) = (a \times 0 + b - 1)^2 + (a \times 1 + b - 3)^2 = (b - 1)^2 + (a + b - 3)^2
Exercise 5.3 Linear regression by gradient descent
  1. Compute L(0,0)\mathcal{L}(0, 0).
  2. Compute ∂L∂a\frac{\partial \mathcal{L}}{\partial a} (bb fixed) and ∂L∂b\frac{\partial \mathcal{L}}{\partial b} (aa fixed). Evaluate them at (0,0)(0, 0).
  3. Do one step of gradient descent from (0,0)(0, 0) with η=0.1\eta = 0.1, and compute the new loss.
  4. Which line goes through both points? What are aa, bb and L\mathcal{L} for this line?
Hint

The first term, (b−1)2(b - 1)^2, does not contain aa: its partial derivative with respect to aa is 00.

Hint

Chain rule on the second term: ∂∂b(a+b−3)2=2(a+b−3)×1\frac{\partial}{\partial b}(a + b - 3)^2 = 2(a + b - 3) \times 1.

Checkpoint what you should get

L(0,0)=10\mathcal{L}(0, 0) = 10,  ∇L(0,0)=(−6,−8)\ \nabla \mathcal{L}(0, 0) = (-6, -8), and after one step the loss is 2.62.6.

Solution
  1. L(0,0)=(−1)2+(−3)2=10\mathcal{L}(0, 0) = (-1)^2 + (-3)^2 = 10.
  2. ∂L∂a=2(a+b−3)\frac{\partial \mathcal{L}}{\partial a} = 2(a + b - 3) and ∂L∂b=2(b−1)+2(a+b−3)\frac{\partial \mathcal{L}}{\partial b} = 2(b - 1) + 2(a + b - 3). At (0,0)(0, 0): −6-6 and −2−6=−8-2 - 6 = -8.
  3. a←0−0.1×(−6)=0.6a \leftarrow 0 - 0.1 \times (-6) = 0.6,  b←0−0.1×(−8)=0.8\ b \leftarrow 0 - 0.1 \times (-8) = 0.8. Then L=(0.8−1)2+(1.4−3)2=0.04+2.56=2.6\mathcal{L} = (0.8 - 1)^2 + (1.4 - 3)^2 = 0.04 + 2.56 = 2.6, down from 1010.
  4. The line y=2x+1y = 2x + 1: (a,b)=(2,1)(a, b) = (2, 1), and L=0\mathcal{L} = 0, the global minimum. Each step of gradient descent gets closer to it.
What to notice

Both derivatives were negative, so both knobs went up: the line was too low everywhere. And bb moved more than aa, because it changes the predictions on both examples, while aa only changes the second one.

For a straight line, we did not need gradient descent: least squares gives the best (a,b)(a, b) with a formula, θ=(X⊤X)−1X⊤y\theta = (X^\top X)^{-1} X^\top y, a closed-form solution. That is exactly what a network does not have, and why the whole of section 3 was needed.

6. Recap