Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsCalculus

The gradient

P1.C540 min●●○ IntermediateReviewed Nov 30, 2026

Why this matters for machine learning

Training a model means moving all its weights at once so that the loss falls. The gradient stacks one partial derivative per weight into a single vector, and that vector says which way to move all the weights together to raise the loss fastest, so its opposite lowers the loss fastest.

  • Gradient descent updates all the weights with one rule: new θ\boldsymbol{\theta} = old θ−η ∇L\boldsymbol{\theta}-\eta\,\nabla\mathcal{L}. (P1.F3: Gradient descent)
  • Backpropagation computes the gradient of the loss with respect to every weight of a network, and its output is checked against a nudging estimate. (P4.8: Backpropagation: step by step with numbers)
  • Mini-batch training estimates the gradient of the average loss by averaging the gradients of a few examples. (P1.F4: Stochastic and mini-batch gradient descent, coming soon)
  • The gradient of the loss with respect to a weight matrix is a matrix of the same shape, which is how deep-learning libraries store gradients. (P1.C11: Matrix calculus for ML)
  • Features on very different scales stretch the loss bowl and bend the gradient away from the bottom, which is why features are rescaled before training. (P3.A11: Features, scaling and data leakage, coming soon)

Before this: Partial derivatives, Dot product and cosine similarity, Norms and distances

After this lesson you can

  • Write the gradient ∇f\nabla f as the vector of all partial derivatives, compute it for functions such as x2+3xyx^2+3xy, the P0.2 loss L(w,b)\mathcal{L}(w,b) (giving (−10,−4)(-10,-4) at (1,0)(1,0)) and w⋅x\mathbf{w}\cdot\mathbf{x} (giving x\mathbf{x}), and say why it has the same shape as the input
  • Use the first-order approximation f(p+Δ)≈f(p)+∇f⋅Δf(\mathbf{p}+\boldsymbol{\Delta})\approx f(\mathbf{p})+\nabla f\cdot\boldsymbol{\Delta} to estimate a change, and say when it stops being accurate
  • Explain with ∇f⋅u=∥∇f∥cos⁡θ\nabla f\cdot\mathbf{u}=\lVert\nabla f\rVert\cos\theta why ∇f\nabla f is the direction of steepest ascent, −∇f-\nabla f of steepest descent, and the steepest slope is ∥∇f∥\lVert\nabla f\rVert
  • Explain why the gradient is perpendicular to the contour line, is zero at flat points (bottoms, tops and saddles), and depends on the scale of the inputs
  • Take a gradient-descent step p−η∇f\mathbf{p}-\eta\nabla f, and see that the gradient of an average loss is the average of the per-example gradients

Stand in thick fog on a hillside. You cannot see the valley, but your feet can tell you two things: how steeply the ground rises if you step east, and how steeply it rises if you step north. Which way should you walk to climb as fast as possible? Probably neither east nor north, but a mix of the two. This lesson shows how to find the mix, with one arrow built from the two slopes.

In P0.2 the line y^=wx+b\hat{y}=wx+b had two knobs, and P1.C4 found the slope for each: −10-10 for ww and −4-4 for bb. If you could turn both knobs at once, which combination would lower the loss fastest? The answer is the gradient.

The gradient: all the partial derivatives in one vector

Take a function ff of nn inputs. Its gradient is the vector of all its partial derivatives (P1.C4), one for each input:

∇f=(∂f∂x1∂f∂x2⋮∂f∂xn)\nabla f=\begin{pmatrix}\dfrac{\partial f}{\partial x_1}\\[12pt] \dfrac{\partial f}{\partial x_2}\\[12pt] \vdots\\[6pt] \dfrac{\partial f}{\partial x_n}\end{pmatrix}

The symbol ∇\nabla is called “nabla” (or “del”), and ∇f\nabla f is often read “grad ff”. This site writes the gradient as a column, and in a line of text as a list such as (7,6)(7,6). When a function has several kinds of inputs, a subscript says which ones are meant: ∇wL\nabla_{\mathbf{w}}\mathcal{L} is the vector of the partials of the loss with respect to the weights w\mathbf{w} only.

Three examples, all computed in P1.C4:

  • f(x,y)=x2+3xyf(x,y)=x^2+3xy has ∂f∂x=2x+3y\frac{\partial f}{\partial x}=2x+3y and ∂f∂y=3x\frac{\partial f}{\partial y}=3x. At (2,1)(2,1) these are 77 and 66, so ∇f(2,1)=(7,6)\nabla f(2,1)=(7,6).
  • The P0.2 loss at (w,b)=(1,0)(w,b)=(1,0) has ∂L∂w=−10\frac{\partial \mathcal{L}}{\partial w}=-10 and ∂L∂b=−4\frac{\partial \mathcal{L}}{\partial b}=-4, so ∇L(1,0)=(−10,−4)\nabla\mathcal{L}(1,0)=(-10,-4).
  • The linear function f(w)=w⋅xf(\mathbf{w})=\mathbf{w}\cdot\mathbf{x} has ∂f∂wi=xi\frac{\partial f}{\partial w_i}=x_i for every ii, so ∇w(w⋅x)=x\nabla_{\mathbf{w}}(\mathbf{w}\cdot\mathbf{x})=\mathbf{x}. For x=(2,−1,3)\mathbf{x}=(2,-1,3) the gradient is (2,−1,3)(2,-1,3) at every w\mathbf{w}.

Three things to notice.

One entry per input. The gradient lives in the input space: it has exactly as many entries as there are inputs, and entry ii belongs to input ii. So it has the same shape as the input. If the inputs are the entries of a weight matrix W\mathbf{W}, the gradient is a matrix of the same shape, with entry ∂L∂Wij\frac{\partial \mathcal{L}}{\partial W_{ij}} at position (i,j)(i,j). A small example: for f(W)=∑i,jWij2f(\mathbf{W})=\sum_{i,j}W_{ij}^2 and W=(1234)\mathbf{W}=\begin{pmatrix}1&2\\3&4\end{pmatrix}, each entry has partial derivative 2Wij2W_{ij}, so the gradient is (2468)\begin{pmatrix}2&4\\6&8\end{pmatrix}. Listing the entries of a matrix in one long column is only bookkeeping. P1.C11 gives the shape rules.

A new vector at every point. The gradient of x2+3xyx^2+3xy is the function ∇f(x,y)=(2x+3y,  3x)\nabla f(x,y)=(2x+3y,\;3x). At (2,1)(2,1) it is (7,6)(7,6), and at (1,2)(1,2) it is (8,3)(8,3). Moving the point changes the arrow.

It is not drawn on the surface. For a function of two inputs, the gradient is an arrow in the flat plane of the inputs (the floor under the surface), not an arrow that climbs the surface. Its two entries are slopes (change in ff per unit of an input), but together they point in a direction of the input plane.

Seeing the gradient on a contour map

A hiking map shows hills with contour lines: each line joins the points of the same height. A contour line (also called a level set) of a function f(x,y)f(x,y) is the set of points where ff has one fixed value, such as f=3f=3. Draw the lines at equally spaced values and you see the landscape from above: lines that crowd together mean steep ground, lines far apart mean gentle ground.

In the widget the point is blue and the gradient arrow is orange. Drag the point, tap the map, or focus the point and use the arrow keys.

Drag the point over the contour map

ℒ(w, b) = mean squared error of ŷ = w·x + b (P0.2). ∇ℒ = ((28w + 12b − 58)/3, (12w + 6b − 24)/3)

01234−2−1012wb∇ℒℒ = 6
point (w, b) = (1, 0)
ℒ(w, b) = 6
∇ℒ = (−10, −4)
length ‖∇ℒ‖ = 10.77
angle between the arrow and the contour line, measured on a short piece of the drawn line: 90°

The orange arrow points uphill and crosses the contour line at a right angle. Its length, ‖∇ℒ‖ = 10.77, is the steepest slope at this point.

Thin lines are contour lines at equally spaced values (ℒ = 2, 6, 10, …, 38); the thick line is the one through your point. The arrow length is drawn in proportion to ‖∇ℒ‖ (the same scale everywhere on this map), so it is not a distance on the map. The dashed ring and the blue trail use true map distances.

A contour map with the gradient at your point. The thin lines are contour lines at equally spaced values, and the thick line is the contour line through the point. The orange arrow is the gradient: its direction is exact, its length is drawn in proportion to the true length (long arrows are cut short at the edge of the map; the number below the map gives the true length). Show −∇f to see the opposite arrow, preview or take a gradient-descent step with the learning rate η, or press “Go to the flat spot”. Both axes use the same scale, so right angles look like right angles.

Things to try with the contour map:

  1. Start with the loss L(w,b)\mathcal{L}(w,b) at (1,0)(1,0). The arrow shows (−10,−4)(-10,-4): it points left and a little down, because the loss rises when ww is lowered. The angle readout says the arrow meets the thick contour line at 90∘90^\circ. Turn on −∇f-\nabla f: it points the way P0.2 moved ww and bb.
  2. Switch to the round bowl x2+y2x^2+y^2. The arrows point straight away from the centre, and they get longer with the distance from it (∥∇f∥=2×\lVert\nabla f\rVert=2\times the distance). The contour lines are circles that crowd together as you go out.
  3. Switch to the stretched bowl x2+10y2x^2+10y^2 at (1,1)(1,1). The gradient is (2,20)(2,20): almost straight up the narrow direction. Turn on −∇f-\nabla f and compare with the bottom of the bowl at the origin: the arrow does not point at it. Turn on “Arrows everywhere” to see the same on the whole map.
  4. On the saddle x2−y2x^2-y^2 at (1,1)(1,1) the point sits on the line f=0f=0, and the arrow crosses it at a right angle. Press “Go to the flat spot”: the arrow disappears, because the gradient there is exactly zero.
  5. On the tilted plane the arrow is the same everywhere, and the contour lines are straight, parallel and equally spaced.
  6. On the loss, turn on “Preview a descent step” with η=0.05\eta=0.05: the ring is the next point, (1.5,0.2)(1.5,0.2), where L≈1.8067\mathcal{L}\approx1.8067, the step of P0.2. Press “Take a step” a few times. Then raise η\eta to 0.20.2 and watch what happens.

The rest of the lesson explains each of these observations.

Small steps: the first-order approximation

Move from a point p\mathbf{p} by a small step Δ=(Δx,Δy)\boldsymbol{\Delta}=(\Delta x,\Delta y). P1.C4 found that the effects of nudges add: Δf≈fx Δx+fy Δy\Delta f\approx f_x\,\Delta x+f_y\,\Delta y. The right-hand side is a dot product (P1.B3) of the gradient with the step:

f(p+Δ)  ≈  f(p)+∇f(p)⋅Δ.f(\mathbf{p}+\boldsymbol{\Delta})\;\approx\;f(\mathbf{p})+\nabla f(\mathbf{p})\cdot\boldsymbol{\Delta}.

This is the first-order approximation. It says that close to p\mathbf{p} the surface looks like a flat tilted plane, the same zoom-in picture as in P1.C1, and the gradient holds the tilt of that plane. It holds for a differentiable ff (P1.C4 mentioned that continuous partial derivatives are enough) and a small step. The tilted-plane function of the widget is its own approximation, exactly, because it already is a plane.

Test it on the P0.2 loss at (1,0)(1,0), where ∇L=(−10,−4)\nabla\mathcal{L}=(-10,-4) and L=6\mathcal{L}=6. Take steps against the gradient, Δ=−η∇L\boldsymbol{\Delta}=-\eta\nabla\mathcal{L}, of three sizes:

  • η=0.005\eta=0.005: Δ=(0.05,0.02)\boldsymbol{\Delta}=(0.05,0.02). Predicted change −10(0.05)−4(0.02)=−0.58-10(0.05)-4(0.02)=-0.58. Actual change: L(1.05,0.02)−6=−0.5639\mathcal{L}(1.05,0.02)-6=-0.5639. Close.
  • η=0.05\eta=0.05: Δ=(0.5,0.2)\boldsymbol{\Delta}=(0.5,0.2). Predicted −5.8-5.8. Actual −4.1933-4.1933, since L=1.8067\mathcal{L}=1.8067 (the step of P0.2). The loss fell, but less than predicted.
  • η=0.2\eta=0.2: Δ=(2,0.8)\boldsymbol{\Delta}=(2,0.8). Predicted −23.2-23.2, which would put the loss at −17.2-17.2. A squared error cannot be negative, so the prediction is wrong. Actual: L(3,0.8)=8.5067\mathcal{L}(3,0.8)=8.5067, a rise of 2.50672.5067.

The estimate is good for small steps and useless for big ones. Halve the first step to (0.025,0.01)(0.025,0.01) and the error (actual minus predicted) falls from 0.01610.0161 to 0.00400.0040, about a quarter. For smooth functions the error typically shrinks with the square of the step, and P1.C8 measures it with second derivatives.

Why the gradient points uphill

Now the main question. From p\mathbf{p}, take a tiny step of length hh in a direction given by a unit vector u\mathbf{u} (length 1), so Δ=hu\boldsymbol{\Delta}=h\mathbf{u}. The first-order approximation gives

f(p+hu)−f(p)≈h ∇f⋅u.f(\mathbf{p}+h\mathbf{u})-f(\mathbf{p})\approx h\,\nabla f\cdot\mathbf{u}.

So the slope in the direction u\mathbf{u}, the change in ff per unit of distance, is ∇f⋅u\nabla f\cdot\mathbf{u}. P1.B3 says a dot product equals the product of the lengths and the cosine of the angle between the vectors. With ∥u∥=1\lVert\mathbf{u}\rVert=1:

∇f⋅u=∥∇f∥cos⁡θ,\nabla f\cdot\mathbf{u}=\lVert\nabla f\rVert\cos\theta,

where θ\theta is the angle between u\mathbf{u} and ∇f\nabla f. Now only cos⁡θ\cos\theta changes with the direction, and it lies between −1-1 and 11:

  • θ=0∘\theta=0^\circ (u\mathbf{u} along the gradient): the slope is +∥∇f∥+\lVert\nabla f\rVert, the largest possible. The gradient points in the direction of steepest ascent.
  • θ=180∘\theta=180^\circ (u\mathbf{u} against the gradient): the slope is −∥∇f∥-\lVert\nabla f\rVert, the most negative possible. The direction −∇f-\nabla f is the direction of steepest descent.
  • θ=90∘\theta=90^\circ: the slope is 00 to first order. The function does not change.

The condition “unit vector” matters. Without it you could double u\mathbf{u} and double the change, so “steepest” compares directions at the same step length. The argument also needs ∇f≠0\nabla f\neq\mathbf{0}: with a zero gradient there is no direction to name. And the steepest slope itself, ∥∇f∥\lVert\nabla f\rVert, is the length of the gradient (P1.B4).

Check it on the P0.2 loss at (1,0)(1,0), where ∇L=(−10,−4)\nabla\mathcal{L}=(-10,-4) and ∥∇L∥=116≈10.77\lVert\nabla\mathcal{L}\rVert=\sqrt{116}\approx10.77. The unit vector along −∇L-\nabla\mathcal{L} is about (0.928,0.371)(0.928,0.371).

  • Along the ww axis, u=(1,0)\mathbf{u}=(1,0): slope −10-10. This is just ∂L∂w\frac{\partial \mathcal{L}}{\partial w}.
  • Along the bb axis, u=(0,1)\mathbf{u}=(0,1): slope −4-4.
  • Along u=(0.6,0.8)\mathbf{u}=(0.6,0.8): slope −10(0.6)−4(0.8)=−9.2-10(0.6)-4(0.8)=-9.2.
  • Along (0.928,0.371)(0.928,0.371): slope −10.77-10.77, the steepest descent. Nudging L\mathcal{L} a tiny step each way along this direction gives the same number.

So moving along the ww axis alone lowers the loss at the rate of 10 per unit distance, and the best mix of the two knobs lowers it at 10.77. The partial derivatives look only along the axes, and the gradient finds the best direction.

On P1.F3’s stretched bowl f=x2+10y2f=x^2+10y^2 at (1,1)(1,1) the gradient is (2,20)(2,20), with length 404≈20.1\sqrt{404}\approx20.1. Along −∇f-\nabla f the function falls at a rate of about 20.120.1 per unit distance. Straight left, u=(−1,0)\mathbf{u}=(-1,0), the slope is ∇f⋅u=−2\nabla f\cdot\mathbf{u}=-2, a fall of only 22 per unit distance. P1.F3 used this fact, and this is where it comes from.

Turn the direction and read the slope

−1.5−1−0.500.511.5−101∇ℒu
050100150200250300350−10010slope+‖∇ℒ‖ = 10.77−‖∇ℒ‖ = −10.77
∇ℒ = (−10, −4)
‖∇ℒ‖ = 10.77
u = (cos 0°, sin 0°) = (1, 0)
slope = ∇ℒ·u = −10
checked by nudging a tiny step each way along u: −10

The slope is negative: ℒ falls along u, but less steeply than the best direction (−10.77).

The orange arrow is the gradient (drawn to a fixed length; its true length is in the readout), the pink arrow is your direction u (always length 1), and the dotted line is the contour line through the point. The wave is the slope for every possible direction (the horizontal axis is the angle of u in degrees).

Turn the direction u and read the slope. The orange arrow is the gradient (drawn to a fixed length), the pink arrow is your unit direction u, and the dotted line is the contour line through the point. The wave plots the slope for every direction: it peaks at the length of the gradient when u points along it, is zero along the contour line, and bottoms out when u points the opposite way. The number below is also measured by nudging a tiny step each way, to check the dot product.

Try the buttons: “Along ∇” reaches the top of the wave, “Along −∇” the bottom, and “Along the contour line” the zero. P1.C6 develops slopes in any direction in full (directional derivatives). Here we only need the formula ∇f⋅u\nabla f\cdot\mathbf{u}.

“Steepest” is a statement about tiny steps. A long step along ∇f\nabla f can overshoot, as the loss did for η=0.2\eta=0.2 above. And steepest is not the same as “straight to the minimum”, as the next sections show.

The gradient is perpendicular to the contour line

Walk a tiny step Δ\boldsymbol{\Delta} along the contour line through p\mathbf{p}. By the definition of a contour line, ff does not change, so ∇f⋅Δ≈0\nabla f\cdot\boldsymbol{\Delta}\approx0. A dot product of zero means a right angle (P1.B3). So wherever ∇f≠0\nabla f\neq\mathbf{0} the gradient is perpendicular to the contour line, which is what the widget’s angle readout shows (measured on a very short piece of the drawn line; it shows a dash where the gradient is zero or nearly zero, since a zero vector has no direction).

A number check on the stretched bowl at (1,1)(1,1), where ∇f=(2,20)\nabla f=(2,20). The vector (−10,1)(-10,1) has 2(−10)+20(1)=02(-10)+20(1)=0, so it is perpendicular to the gradient, and it should run along the contour line. A step of 0.010.01 in that direction (scaled to length 1) changes ff by only 0.000110.00011. The same step along the gradient changes it by 0.20200.2020, close to the predicted 0.01×20.1=0.2010.01\times20.1=0.201.

This also explains the spacing of the lines. Suppose neighbouring lines differ by a fixed amount cc in ff. Going straight across from one to the next changes ff by c≈d ∥∇f∥c\approx d\,\lVert\nabla f\rVert, where dd is the distance between the lines. So d≈c/∥∇f∥d\approx c/\lVert\nabla f\rVert: close lines mean a long gradient.

Where the gradient is zero

If ∇f=0\nabla f=\mathbf{0}, every slope ∇f⋅u\nabla f\cdot\mathbf{u} is zero: to first order the ground is flat in every direction. Such a point can be:

  • a bottom (a minimum), such as the origin of the bowls and the point (2.5,−1)(2.5,-1) of the P0.2 loss, where L=0.5\mathcal{L}=0.5;
  • a top (a maximum), such as the origin of −x2−y2-x^2-y^2;
  • a saddle, such as the origin of x2−y2x^2-y^2, which rises in one direction and falls in another.

The gradient alone cannot tell them apart. Look at the contour lines in the widget at each flat spot: around a bottom they shrink to a point, and at a saddle they cross. Telling the cases apart needs second derivatives (P1.C8), and P1.F2 looks at their consequences for optimization. A gradient that is only close to zero may also be a plateau, where the ground is nearly flat but not at a bottom.

Gradient descent: step against the gradient

Since −∇f-\nabla f is the steepest way down, a natural move is to step that way. This is gradient descent (P0.2, P1.F3):

pnew=p−η ∇f(p),\mathbf{p}_{\text{new}}=\mathbf{p}-\eta\,\nabla f(\mathbf{p}),

with learning rate η\eta. Each input moves against its own partial derivative, all at once. The first-order approximation gives the change: with Δ=−η∇f\boldsymbol{\Delta}=-\eta\nabla f, we get ∇f⋅Δ=−η∥∇f∥2\nabla f\cdot\boldsymbol{\Delta}=-\eta\lVert\nabla f\rVert^2, which is below zero whenever ∇f≠0\nabla f\neq\mathbf{0}. So for a small enough η\eta the function goes down. For the P0.2 loss at (1,0)(1,0) and η=0.05\eta=0.05 this predicts −0.05×116=−5.8-0.05\times116=-5.8, and the real change was −4.19-4.19. For a larger η\eta the prediction breaks down, as the η=0.2\eta=0.2 step showed. How to choose η\eta is the topic of P1.F3.

The gradient does not point at the minimum. On the stretched bowl at (1,1)(1,1) the direction −∇f-\nabla f is 39∘39^\circ away from the direction of the bottom: the arrow mostly aims down the steep side, not along the valley. That is the zig-zag of P1.F3. On the P0.2 loss the first step from (1,0)(1,0) goes to (1.5,0.2)(1.5,0.2), which raises bb, although the best line has b=−1b=-1: here −∇L-\nabla\mathcal{L} is 55∘55^\circ away from the direction of the bottom at (2.5,−1)(2.5,-1).

The gradient depends on the scale of the inputs

Take the round bowl x2+y2x^2+y^2 at (1,1)(1,1). The gradient is (2,2)(2,2), at 45∘45^\circ. Now measure the second input in units ten times smaller, so that v=10yv=10y (think of metres and decimetres). The same landscape is g(x,v)=x2+(v/10)2g(x,v)=x^2+(v/10)^2, and the same spot is (x,v)=(1,10)(x,v)=(1,10). Its gradient is (2, 0.2)(2,\,0.2), only 5.7∘5.7^\circ from the first axis. Same hill, same spot, different gradient direction.

The reason is that “steepest” is measured per unit of distance in the coordinates you use. A unit of vv is a much shorter step than a unit of xx, so the vv direction looks much flatter. The same effect stretches the bowl of P1.F3: x2+10y2=x2+(10 y)2x^2+10y^2=x^2+(\sqrt{10}\,y)^2 is a round bowl in which the second input has been multiplied by 10\sqrt{10}. In a model, a feature with much bigger values makes the loss change faster when its weight changes, so the slope along that weight is steeper and the loss bowl is stretched the same way. Rescaling the features (P3.A11) usually makes the bowl rounder (correlated features can still leave it oval), so that the gradient points more nearly at the bottom.

Gradients add: the loss over many examples

Partial derivatives follow the sum rule of P1.C2, so ∇(f+g)=∇f+∇g\nabla(f+g)=\nabla f+\nabla g and ∇(cf)=c ∇f\nabla(cf)=c\,\nabla f. The loss over NN examples is an average, L=1N∑iLi\mathcal{L}=\frac1N\sum_i L_i, so

∇L=1N∑i=1N∇Li.\nabla\mathcal{L}=\frac1N\sum_{i=1}^{N}\nabla L_i.

The gradient of the average loss is the average of the per-example gradients. Check it on the P0.2 model y^=wx+b\hat{y}=wx+b at (1,0)(1,0). One example has Li=(wxi+b−yi)2L_i=(wx_i+b-y_i)^2, with partial derivatives 2e xi2e\,x_i and 2e2e, where e=wxi+b−yie=wx_i+b-y_i is the error (P1.C4; the chain rule of P1.C3 gives the factor 2e2e). For the data (1,2),(2,3),(3,7)(1,2),(2,3),(3,7) the errors are −1,−1,−4-1,-1,-4, and the per-example gradients are:

  • (−2,−2)(-2,-2) for the example (1,2)(1,2),
  • (−4,−2)(-4,-2) for (2,3)(2,3),
  • (−24,−8)(-24,-8) for (3,7)(3,7).

Their average is (−303,−123)=(−10,−4)\left(\frac{-30}{3},\frac{-12}{3}\right)=(-10,-4), the gradient of the loss. If only the first and third examples were used, the average would be (−13,−5)(-13,-5): a cheaper estimate, pointing within 1∘1^\circ of the true gradient. Estimating the gradient from a few examples is the mini-batch idea of P1.F4.

Checking a gradient numerically

P1.C4’s nudging check works for the whole vector. Let ei\mathbf{e}_i be the vector with a 11 in position ii and 00 elsewhere. Entry ii of the gradient is estimated by

f(p+hei)−f(p−hei)2h,\frac{f(\mathbf{p}+h\mathbf{e}_i)-f(\mathbf{p}-h\mathbf{e}_i)}{2h},

two evaluations of ff per input, so 2n2n in all (the cost problem that backpropagation solves, P4.8). With h=10−5h=10^{-5} the estimate usually agrees with a correct formula to many digits. A cheap extra test uses this lesson’s formula: the slope along a random unit direction u\mathbf{u} is ∇f⋅u\nabla f\cdot\mathbf{u}, and a nudge along u\mathbf{u} measures it with only two evaluations. If the two agree for several random directions, the gradient is very likely right. That is evidence, not a proof, and the first cell below tries it.

Go deeper When the gradient does not exist

Everything above needs ff to be differentiable. A corner breaks it. For f(x,y)=∣x∣+∣y∣f(x,y)=|x|+|y| the slice along the xx axis at y=0y=0 is ∣x∣|x|, which has a corner at 00 (P1.C1), so ∂f∂x\frac{\partial f}{\partial x} does not exist at the origin and there is no gradient there. The ReLU function of P4.4 has the same kind of corner, and training software simply picks a convention at that single point.

The opposite trap is a function whose partial derivatives exist but are not continuous. P1.C4’s example xyx2+y2\frac{xy}{x^2+y^2} has both partial derivatives equal to 00 at the origin, so its “gradient” there would be (0,0)(0,0), yet the function is 12\frac12 at every point of the diagonal except the origin, so it is not even continuous at the origin. The first-order approximation fails for it. A standard theorem says that continuous partial derivatives near a point are enough for the formulas of this lesson to hold, and the losses of this course are of that kind away from isolated corners.

Go deeper Rows, columns and the dot product

Some books write the gradient as a row, because the derivative of a function of nn inputs is naturally a row of nn numbers (the one-row Jacobian of P1.C7). This site writes it as a column, in the same shape as the input p\mathbf{p}, so that the update p−η∇f\mathbf{p}-\eta\nabla f makes sense without any transposing. In the first-order approximation, ∇f⋅Δ\nabla f\cdot\boldsymbol{\Delta} is the same number as (∇f)⊤Δ(\nabla f)^\top\boldsymbol{\Delta}, a row times a column. Both conventions give the same numbers.

Go deeper More than two inputs

Nothing in the arguments above used two inputs. With nn inputs the gradient has nn entries, the slope in a unit direction is still ∇f⋅u=∥∇f∥cos⁡θ\nabla f\cdot\mathbf{u}=\lVert\nabla f\rVert\cos\theta, and the gradient is still the direction of steepest ascent. What changes is the picture: a contour line becomes a level set with n−1n-1 dimensions (a surface for n=3n=3), and the gradient is still perpendicular to it, by the same argument. A loss with a million weights lives in this space, and we cannot draw it, but the two-input maps above show the pattern.

The gradient in three depths

Intuition

In the fog, you feel the slope in every direction. One direction is steepest uphill: that is where the gradient points, and how steep it is there is the length of the gradient. Step the opposite way to go down fastest. Walk along the contour line and you neither climb nor fall.

The gradient is a local fact. It is only the best direction for a tiny step from where you stand, so you recompute it after each step. It need not point at the valley, which may be around a bend.

Math

∇f(p)=(∂f∂x1,…,∂f∂xn) ⁣⊤ ⁣∣p,f(p+Δ)≈f(p)+∇f(p)⋅Δ.\begin{gathered} \nabla f(\mathbf{p}) \\ \quad=\left(\frac{\partial f}{\partial x_1},\dots,\frac{\partial f}{\partial x_n}\right)^{\!\top}\!\Bigg|_{\mathbf{p}}, \\ f(\mathbf{p}+\boldsymbol{\Delta})\approx f(\mathbf{p})+\nabla f(\mathbf{p})\cdot\boldsymbol{\Delta}. \end{gathered}

Steepest direction: for a unit vector u\mathbf{u},

f(p+hu)−f(p)≈h ∇f⋅u=h ∥∇f∥cos⁡θ,\begin{gathered} f(\mathbf{p}+h\mathbf{u})-f(\mathbf{p}) \\ \quad\approx h\,\nabla f\cdot\mathbf{u} \\ \quad=h\,\lVert\nabla f\rVert\cos\theta, \end{gathered}

largest at θ=0\theta=0, where the slope is ∥∇f∥\lVert\nabla f\rVert, and zero for θ=90∘\theta=90^\circ. Along a contour line ∇f⋅Δ≈0\nabla f\cdot\boldsymbol{\Delta}\approx0, so wherever ∇f≠0\nabla f\neq\mathbf{0} it is perpendicular to the line.

Descent: p←p−η∇f(p)\mathbf{p}\leftarrow\mathbf{p}-\eta\nabla f(\mathbf{p}) changes ff by about −η∥∇f∥2-\eta\lVert\nabla f\rVert^2. Sum rule: ∇ ⁣(1N∑iLi)=1N∑i∇Li\nabla\!\left(\frac1N\sum_iL_i\right)=\frac1N\sum_i\nabla L_i. Numerical check: entry ii is f(p+hei)−f(p−hei)2h\frac{f(\mathbf{p}+h\mathbf{e}_i)-f(\mathbf{p}-h\mathbf{e}_i)}{2h}.

Code

import numpy as np

def num_grad(f, p, h=1e-5):
    """Central-difference gradient of f at p (a NumPy array): 2 evaluations per input."""
    p = np.asarray(p, dtype=float)
    g = np.zeros_like(p)
    for i in range(p.size):
        e = np.zeros_like(p)
        e[i] = h
        g[i] = (f(p + e) - f(p - e)) / (2 * h)
    return g

f = lambda p: p[0]**2 + 3 * p[0] * p[1]
num_grad(f, [2, 1])          # about [7, 6]

PyTorch returns the whole gradient with one backward() call (automatic differentiation, P1.C10). This runs in Colab or on your machine, not in the browser here:

import torch
p = torch.tensor([2.0, 1.0], requires_grad=True)
f = p[0]**2 + 3 * p[0] * p[1]
f.backward()
print(p.grad)    # tensor([7., 6.])

Try it: gradients in code

The first cell computes gradients by nudging, checks them against the formulas of this lesson, tests the slope along random directions, and scans all directions to find the steepest one. The second computes the per-example gradients of the P0.2 loss and takes gradient-descent steps of different sizes. Predict the output before you run.

Try it: the numerical gradient and the steepest direction

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Challenge: scan for the direction in which the slope is 00 (closest to zero) and compare it with the gradient direction plus 90∘90^\circ.

Try it: per-example gradients, averaging and descent steps

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Challenge: use the stretched bowl f=x2+10y2f=x^2+10y^2 with the gradient (2x, 20y)(2x,\,20y). Start at (1,1)(1,1), take 5 steps with η=0.095\eta=0.095, and print the point after each step.

Common mistakes

Check your understanding

  1. Let f(x,y)=x2yf(x,y)=x^2y. What is the gradient ∇f\nabla f at the point (3,2)(3,2)?

  2. At a point the gradient of ff is (3,4)(3,4). Along which unit direction does ff fall fastest, and at what rate per unit distance?

  3. On a contour map with lines at equally spaced values of ff, the lines are close together near point AA and far apart near point BB. Where is the gradient longer?

  4. At a point ∇f=(3,4)\nabla f=(3,4). You take a tiny step of length hh in the direction (0.8,−0.6)(0.8,-0.6). About how much does ff change?

  5. At (1,0)(1,0) the P0.2 loss is the average of three per-example losses whose gradients are (−2,−2)(-2,-2), (−4,−2)(-4,-2) and (−24,−8)(-24,-8). What is the gradient of the loss?

Exercises

  1. Find ∇f\nabla f for f(x,y)=x2+3xyf(x,y)=x^2+3xy at (1,2)(1,2).
    Show answer∂f∂x=2x+3y=8\frac{\partial f}{\partial x}=2x+3y=8 and ∂f∂y=3x=3\frac{\partial f}{\partial y}=3x=3, so ∇f(1,2)=(8,3)\nabla f(1,2)=(8,3).
  2. For f(x,y)=x eyf(x,y)=x\,\mathrm{e}^{y} at (2,0)(2,0), find the gradient, the steepest slope, and the unit direction of steepest ascent.
    Show answer∇f=(ey,  x ey)=(1,2)\nabla f=(\mathrm{e}^y,\;x\,\mathrm{e}^y)=(1,2). The steepest slope is ∥∇f∥=5≈2.236\lVert\nabla f\rVert=\sqrt5\approx2.236, in the direction (1,2)/5≈(0.447,0.894)(1,2)/\sqrt5\approx(0.447,0.894).
  3. For f=x2+3xyf=x^2+3xy at (2,1)(2,1) with ∇f=(7,6)\nabla f=(7,6), use the first-order approximation to estimate the change for the step (−0.1, 0.1)(-0.1,\,0.1). Then compute the actual change.
    Show answerEstimate: 7(−0.1)+6(0.1)=−0.17(-0.1)+6(0.1)=-0.1. Actual: f(1.9,1.1)−f(2,1)=9.88−10=−0.12f(1.9,1.1)-f(2,1)=9.88-10=-0.12.
  4. For the P0.2 loss, ∇L(2,1)=(103, 2)\nabla\mathcal{L}(2,1)=\left(\frac{10}{3},\,2\right) and L(2,1)=53≈1.667\mathcal{L}(2,1)=\frac53\approx1.667. Take one gradient-descent step with η=0.05\eta=0.05. Where do you land, what is the new loss, and what did the first-order approximation predict?
    Show answerThe new point is (2−0.05⋅103,  1−0.05⋅2)=(1.8333, 0.9)(2-0.05\cdot\frac{10}{3},\;1-0.05\cdot2)=(1.8333,\,0.9), with L≈1.1174\mathcal{L}\approx1.1174, a change of −0.5493-0.5493. The approximation predicts −η∥∇L∥2=−0.05(1009+4)≈−0.7556-\eta\lVert\nabla\mathcal{L}\rVert^2=-0.05\left(\frac{100}{9}+4\right)\approx-0.7556. The loss fell, but less than predicted.
  5. At a point ∇f=(3,−4)\nabla f=(3,-4). Find a unit direction in which ff does not change to first order.
    Show answerA direction perpendicular to the gradient: (4,3)/5=(0.8,0.6)(4,3)/5=(0.8,0.6), since 3(0.8)−4(0.6)=03(0.8)-4(0.6)=0. The opposite vector (−0.8,−0.6)(-0.8,-0.6) also works.
  6. For f=x2+y2f=x^2+y^2 at (3,4)(3,4), find the gradient and check that it is perpendicular to the circle through the point.
    Show answer∇f=(6,8)\nabla f=(6,8). The circle x2+y2=25x^2+y^2=25 has tangent direction (−4,3)(-4,3) at (3,4)(3,4) (perpendicular to the radius (3,4)(3,4)), and 6(−4)+8(3)=06(-4)+8(3)=0.
  7. On the stretched bowl f=x2+10y2f=x^2+10y^2 at (2,0.5)(2,0.5), find the gradient and the angle between −∇f-\nabla f and the direction from the point to the bottom (0,0)(0,0).
    Show answer∇f=(4,10)\nabla f=(4,10). The vector −∇f=(−4,−10)-\nabla f=(-4,-10) and the direction to the bottom (−2,−0.5)(-2,-0.5) are about 54∘54^\circ apart. The gradient does not point at the bottom.
  8. Two examples have loss gradients (1,2)(1,2) and (3,−1)(3,-1) at the current weights. What is the gradient of the loss that is their sum, and of the loss that is their average?
    Show answerSum: (1,2)+(3,−1)=(4,1)(1,2)+(3,-1)=(4,1). Average: (2, 0.5)(2,\,0.5).
  9. Let g(x,u)=x2+(u/2)2g(x,u)=x^2+(u/2)^2. This is x2+y2x^2+y^2 with y=u/2y=u/2. Find ∇g\nabla g at (x,u)=(1,2)(x,u)=(1,2) and compare it with ∇f\nabla f of f=x2+y2f=x^2+y^2 at the same spot (1,1)(1,1).
    Show answer∇g=(2x,  u/2)=(2,1)\nabla g=(2x,\;u/2)=(2,1), while ∇f(1,1)=(2,2)\nabla f(1,1)=(2,2). The same spot and the same heights give different gradients because the second input is measured in different units.
  10. For the function f(W)=∑i,jWij2f(\mathbf{W})=\sum_{i,j}W_{ij}^2 with a 3×43\times4 matrix W\mathbf{W}, what shape does the gradient have, and what is it in terms of W\mathbf{W}?
    Show answerIt has shape 3×43\times4, the same as W\mathbf{W}, and equals 2W2\mathbf{W}, since each entry has partial derivative 2Wij2W_{ij}.

Next: P1.C6 studies slopes in any direction, the directional derivatives, and develops the formula ∇f⋅u\nabla f\cdot\mathbf{u} that this lesson used. P1.C7 collects the partial derivatives of functions with several outputs into a matrix, the Jacobian, and P1.C8 adds second derivatives, which tell bowls from saddles. Gradient descent proper, with the learning rate, is P1.F3.

Key takeaways

  • The gradient ∇f\nabla f is the vector of all partial derivatives of ff. It has one entry per input, so it has the same shape as the input (a weight matrix has a gradient matrix). It is a new vector at every point: ∇f(2,1)=(7,6)\nabla f(2,1)=(7,6) for x2+3xyx^2+3xy, and ∇L(1,0)=(−10,−4)\nabla\mathcal{L}(1,0)=(-10,-4) for the P0.2 loss.
  • Close up, ff looks flat: f(p+Δ)≈f(p)+∇f(p)⋅Δf(\mathbf{p}+\boldsymbol{\Delta})\approx f(\mathbf{p})+\nabla f(\mathbf{p})\cdot\boldsymbol{\Delta}, for a small step Δ\boldsymbol{\Delta} and a differentiable ff. This is the first-order approximation. It is good for small steps and fails for big ones.
  • In a unit direction u\mathbf{u} the slope is ∇f⋅u=∥∇f∥cos⁡θ\nabla f\cdot\mathbf{u}=\lVert\nabla f\rVert\cos\theta. So the gradient points in the direction of steepest ascent, −∇f-\nabla f is steepest descent, and the steepest slope equals the length ∥∇f∥\lVert\nabla f\rVert. This is about tiny steps, and it needs ∇f≠0\nabla f\neq\mathbf{0}.
  • Wherever ∇f≠0\nabla f\neq\mathbf{0}, the gradient is perpendicular to the contour line through the point (no first-order change along the line). Where contour lines are close together the gradient is long. It does not point at the minimum: at (1,1)(1,1) on x2+10y2x^2+10y^2 the steepest descent direction is 39∘39^\circ away from the direction of the bottom.
  • ∇f=0\nabla f=\mathbf{0} at a flat point, which can be a bottom, a top or a saddle. The gradient also depends on the scale of the inputs: stretching one input changes its direction, which is why the bowls of P1.F3 are stretched and feature scaling helps.
  • Gradient descent steps against the gradient: p←p−η∇f(p)\mathbf{p}\leftarrow\mathbf{p}-\eta\nabla f(\mathbf{p}). The gradient of an average loss is the average of the per-example gradients, which is what mini-batches estimate. Gradients are checked numerically with two evaluations per input.
Found a mistake? Tell us