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 had two knobs, and P1.C4 found the slope for each: for and for . 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 of inputs. Its gradient is the vector of all its partial derivatives (P1.C4), one for each input:
The symbol is called “nabla” (or “del”), and is often read “grad ”. This site writes the gradient as a column, and in a line of text as a list such as . When a function has several kinds of inputs, a subscript says which ones are meant: is the vector of the partials of the loss with respect to the weights only.
Three examples, all computed in P1.C4:
- has and . At these are and , so .
- The P0.2 loss at has and , so .
- The linear function has for every , so . For the gradient is at every .
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 belongs to input . So it has the same shape as the input. If the inputs are the entries of a weight matrix , the gradient is a matrix of the same shape, with entry at position . A small example: for and , each entry has partial derivative , so the gradient is . 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 is the function . At it is , and at it is . 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 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 is the set of points where has one fixed value, such as . 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.
Things to try with the contour map:
- Start with the loss at . The arrow shows : it points left and a little down, because the loss rises when is lowered. The angle readout says the arrow meets the thick contour line at . Turn on : it points the way P0.2 moved and .
- Switch to the round bowl . The arrows point straight away from the centre, and they get longer with the distance from it ( the distance). The contour lines are circles that crowd together as you go out.
- Switch to the stretched bowl at . The gradient is : almost straight up the narrow direction. Turn on 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.
- On the saddle at the point sits on the line , 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.
- On the tilted plane the arrow is the same everywhere, and the contour lines are straight, parallel and equally spaced.
- On the loss, turn on “Preview a descent step” with : the ring is the next point, , where , the step of P0.2. Press “Take a step” a few times. Then raise to and watch what happens.
The rest of the lesson explains each of these observations.
Small steps: the first-order approximation
Move from a point by a small step . P1.C4 found that the effects of nudges add: . The right-hand side is a dot product (P1.B3) of the gradient with the step:
This is the first-order approximation. It says that close to 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 (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 , where and . Take steps against the gradient, , of three sizes:
- : . Predicted change . Actual change: . Close.
- : . Predicted . Actual , since (the step of P0.2). The loss fell, but less than predicted.
- : . Predicted , which would put the loss at . A squared error cannot be negative, so the prediction is wrong. Actual: , a rise of .
The estimate is good for small steps and useless for big ones. Halve the first step to and the error (actual minus predicted) falls from to , 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 , take a tiny step of length in a direction given by a unit vector (length 1), so . The first-order approximation gives
So the slope in the direction , the change in per unit of distance, is . P1.B3 says a dot product equals the product of the lengths and the cosine of the angle between the vectors. With :
where is the angle between and . Now only changes with the direction, and it lies between and :
- ( along the gradient): the slope is , the largest possible. The gradient points in the direction of steepest ascent.
- ( against the gradient): the slope is , the most negative possible. The direction is the direction of steepest descent.
- : the slope is to first order. The function does not change.
The condition “unit vector” matters. Without it you could double and double the change, so “steepest” compares directions at the same step length. The argument also needs : with a zero gradient there is no direction to name. And the steepest slope itself, , is the length of the gradient (P1.B4).
Check it on the P0.2 loss at , where and . The unit vector along is about .
- Along the axis, : slope . This is just .
- Along the axis, : slope .
- Along : slope .
- Along : slope , the steepest descent. Nudging a tiny step each way along this direction gives the same number.
So moving along the 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 at the gradient is , with length . Along the function falls at a rate of about per unit distance. Straight left, , the slope is , a fall of only per unit distance. P1.F3 used this fact, and this is where it comes from.
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 .
“Steepest” is a statement about tiny steps. A long step along can overshoot, as the loss did for 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 along the contour line through . By the definition of a contour line, does not change, so . A dot product of zero means a right angle (P1.B3). So wherever 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 , where . The vector has , so it is perpendicular to the gradient, and it should run along the contour line. A step of in that direction (scaled to length 1) changes by only . The same step along the gradient changes it by , close to the predicted .
This also explains the spacing of the lines. Suppose neighbouring lines differ by a fixed amount in . Going straight across from one to the next changes by , where is the distance between the lines. So : close lines mean a long gradient.
Where the gradient is zero
If , every slope 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 of the P0.2 loss, where ;
- a top (a maximum), such as the origin of ;
- a saddle, such as the origin of , 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 is the steepest way down, a natural move is to step that way. This is gradient descent (P0.2, P1.F3):
with learning rate . Each input moves against its own partial derivative, all at once. The first-order approximation gives the change: with , we get , which is below zero whenever . So for a small enough the function goes down. For the P0.2 loss at and this predicts , and the real change was . For a larger the prediction breaks down, as the step showed. How to choose is the topic of P1.F3.
The gradient does not point at the minimum. On the stretched bowl at the direction is 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 goes to , which raises , although the best line has : here is away from the direction of the bottom at .
The gradient depends on the scale of the inputs
Take the round bowl at . The gradient is , at . Now measure the second input in units ten times smaller, so that (think of metres and decimetres). The same landscape is , and the same spot is . Its gradient is , only 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 is a much shorter step than a unit of , so the direction looks much flatter. The same effect stretches the bowl of P1.F3: is a round bowl in which the second input has been multiplied by . 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 and . The loss over examples is an average, , so
The gradient of the average loss is the average of the per-example gradients. Check it on the P0.2 model at . One example has , with partial derivatives and , where is the error (P1.C4; the chain rule of P1.C3 gives the factor ). For the data the errors are , and the per-example gradients are:
- for the example ,
- for ,
- for .
Their average is , the gradient of the loss. If only the first and third examples were used, the average would be : a cheaper estimate, pointing within 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 be the vector with a in position and elsewhere. Entry of the gradient is estimated by
two evaluations of per input, so in all (the cost problem that backpropagation solves, P4.8). With 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 is , and a nudge along 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 to be differentiable. A corner breaks it. For the slice along the axis at is , which has a corner at (P1.C1), so 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 has both partial derivatives equal to at the origin, so its “gradient” there would be , yet the function is 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 inputs is naturally a row of numbers (the one-row Jacobian of P1.C7). This site writes it as a column, in the same shape as the input , so that the update makes sense without any transposing. In the first-order approximation, is the same number as , 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 inputs the gradient has entries, the slope in a unit direction is still , and the gradient is still the direction of steepest ascent. What changes is the picture: a contour line becomes a level set with dimensions (a surface for ), 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
Steepest direction: for a unit vector ,
largest at , where the slope is , and zero for . Along a contour line , so wherever it is perpendicular to the line.
Descent: changes by about . Sum rule: . Numerical check: entry is .
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.
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 (closest to zero) and compare it with the gradient direction plus .
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: use the stretched bowl with the gradient . Start at , take 5 steps with , and print the point after each step.
Common mistakes
Check your understanding
Let . What is the gradient at the point ?
The first entry is and the second is , in the order of the inputs. The pair has the two entries swapped. The pair forgets the factor in the first entry, and gets the second entry wrong, since it is , not .
At a point the gradient of is . Along which unit direction does fall fastest, and at what rate per unit distance?
Steepest descent is opposite to the gradient, and the unit vector there is . The slope along it is , a fall of per unit distance. The unit vector along the gradient is the direction of steepest rise, not fall. The vector has the right direction but is not a unit vector, so is not a rate per unit distance. The vector is perpendicular to the gradient, along the contour line, where does not change.
On a contour map with lines at equally spaced values of , the lines are close together near point and far apart near point . Where is the gradient longer?
Going from one line to the next changes by a fixed amount, so the slope is that amount divided by the distance between the lines, which is larger where the lines are close. The gradient length is not the same everywhere (a hill steepens and flattens), and the contour lines alone are enough to compare the slopes.
At a point . You take a tiny step of length in the direction . About how much does change?
The change is about with , and . This direction is perpendicular to the gradient, so it runs along the contour line. The value would be the change along the gradient, the change against it, and forgets the second term of the dot product.
At the P0.2 loss is the average of three per-example losses whose gradients are , and . What is the gradient of the loss?
The loss is an average, so its gradient is the average of the per-example gradients: . The pair is the sum, which would be the gradient of the sum of the losses. The other two pairs are the gradient of one single example, which is not the loss over all three.
Exercises
- Find for at .
Show answer
and , so . - For at , find the gradient, the steepest slope, and the unit direction of steepest ascent.
Show answer
. The steepest slope is , in the direction . - For at with , use the first-order approximation to estimate the change for the step . Then compute the actual change.
Show answer
Estimate: . Actual: . - For the P0.2 loss, and . Take one gradient-descent step with . Where do you land, what is the new loss, and what did the first-order approximation predict?
Show answer
The new point is , with , a change of . The approximation predicts . The loss fell, but less than predicted. - At a point . Find a unit direction in which does not change to first order.
Show answer
A direction perpendicular to the gradient: , since . The opposite vector also works. - For at , find the gradient and check that it is perpendicular to the circle through the point.
Show answer
. The circle has tangent direction at (perpendicular to the radius ), and . - On the stretched bowl at , find the gradient and the angle between and the direction from the point to the bottom .
Show answer
. The vector and the direction to the bottom are about apart. The gradient does not point at the bottom. - Two examples have loss gradients and at the current weights. What is the gradient of the loss that is their sum, and of the loss that is their average?
Show answer
Sum: . Average: . - Let . This is with . Find at and compare it with of at the same spot .
Show answer
, while . The same spot and the same heights give different gradients because the second input is measured in different units. - For the function with a matrix , what shape does the gradient have, and what is it in terms of ?
Show answer
It has shape , the same as , and equals , since each entry has partial derivative .
Next: P1.C6 studies slopes in any direction, the directional derivatives, and develops the formula 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.