P1.C4 gave the slope toward the east and the slope toward the north. A path leads north-east. Is the slope under your feet the average of the two? It is not, and the right answer is a recipe that works for every direction. It is also what a computer measures when it checks a gradient with a single nudge.
The slope along a line
Pick a point and a unit vector (length 1), which gives a direction. Walking from along for a distance takes you to , and a negative means walking backwards. Along this line depends on one number, :
This is a slice of along the line, like the slices of P1.C4 but in any direction instead of only along the axes. The directional derivative of at in the direction is the slope of the slice at :
The fraction is a secant slope of (the slope of the straight line through the points at and , as in P1.C1). As shrinks, the secant turns into the tangent, and the limit is the slope of the tangent.
Take the P0.2 loss at , where , along the unit vector . The slice is , and expanding the loss gives
The secant slope is :
| step | secant slope |
|---|---|
| 1 | |
| 0.5 | |
| 0.1 | |
| 0.01 | |
| 0.001 |
They head for , so : going this way the loss falls by about per unit of distance.
Two small facts about the definition. Partial derivatives are special cases: for the line is horizontal and is , and for it is . (Other names for are and .) The opposite direction flips the sign: The slice along is the slice along read backwards, , so whenever the slope exists.
In the widget, turn the direction, shrink , and compare the formula (explained in the next section) with the slope measured on the slice.
Things to try with the slice widget:
- Start with the P0.2 loss. The angle is , so . The slice is the curve , the tangent has slope , and the secant for has slope . Move the slider down and watch the secant settle onto the tangent.
- Press First axis and Second axis: the slopes are and , the partial derivatives of P1.C4. Press Along −∇ℒ: the slope is , the steepest descent, and the marker on the lower plot sits at the bottom of the wave.
- Press Along the contour line. The slope is , yet the slice is a curve, not a flat line. On the stretched bowl of P1.F3 (which starts straight left, with slope , and has slope along ) the tangent is flat and the slice curves upward on both sides.
- On the saddle, press Along the contour line. The contour through is the straight line , so is exactly along it and the slice is flat everywhere.
- Tick Use a vector v that is not a unit vector and set the length to . The tangent gets twice as steep. The readout shows the slope per unit distance, which has not changed.
- Choose the last function, at the origin. The formula says , but the measured slope is not. A later section explains why.
Why the slope is ∇f · u
The first-order approximation of P1.C5 says that for a differentiable at ,
where the error is much smaller than the length of the step. (That is what “differentiable at ” means: the tilted plane fits better than any fixed multiple of the step.) Take the step and divide by :
The error term goes to as , so the limit is
The chain rule gives the same formula as a picture. The slice is with and , so and . The value reaches by two routes, through and through . Multiply along each route and add the routes (the same rule that P1.C3 previewed for one input feeding two routes):
This version also needs to be differentiable at (the failing example below shows why).
Check it. For the loss at with and : , the limit of the table. For at , where , along the same : .
What the formula tells us:
- The two partials give every slope. The slope along is a weighted sum of the two partial derivatives, with the entries of as weights. It is not their average: along the loss slope is .
- The slope is linear in the direction. and , because dot products are linear (P1.B3). Using these with vectors that are not of length 1 comes next.
- The condition. The proof used differentiability at . Continuous partial derivatives near are enough (the standard theorem of P1.C4 and P1.C5), and the losses of this course have them away from corners. Without the condition the formula can fail: see the section after next.
Vectors that are not unit vectors
The slice makes sense for any vector , and its slope at is
If with a unit vector and , the new slice is the old one speeded up: . One unit of now covers a distance , and the chain rule gives :
So there are two different rates. is the slope per unit of , and dividing by gives the slope per unit distance. Take , which has length , on the loss at :
and .
The vector points the same way as , so the slope per unit distance is the found before. The same also comes from linearity: three times the slope along the first axis plus four times the slope along the second.
Why do books insist on unit vectors? Because the question “which direction is steepest?” compares directions fairly only per unit distance. If longer vectors were allowed, doubling would double the number and no direction would be the best. A gradient-descent step fits the other reading: the step is the vector at , so the first-order change in is , the number of P1.C5. The zero vector gives no direction, and it is left out.
The widget’s checkbox for a longer or shorter shows both rates side by side.
The slope as a function of the direction
Recall from P1.C5 that the slope in a unit direction at angle is , where is the angle of the gradient (when ; with a zero gradient there is no , and every slope is ). It is the cosine wave on the lower plot of the widget. Three things are new here.
- Two directions per slope. Each value strictly between and occurs for exactly two directions, mirror images across the gradient. For the loss at : and , and the slope occurs at (the above) and at , where and .
- Any number of inputs. The bound holds in every dimension: (the Cauchy–Schwarz inequality), with equality, when , only if is along or against it. So the steepest-ascent fact of P1.C5 holds for any number of weights.
- The stretched bowl of P1.F3. At , has length and . Straight left () the slope is , and against the gradient it is : the pair of rates in P1.F3.
Zero slope and the contour line. When , the slope is when is perpendicular to , which is the direction of the contour line through (P1.C5). But does not mean the slice is constant. For at , the contour is a circle and the straight line along its tangent leaves the circle: . The slope at is , and rises on both sides at second order. On the saddle the contour through is itself a straight line, and there . The first derivative alone cannot tell these cases apart.
Which directions go downhill. If , then and the slice falls for small : is a descent direction. In 2-D these are the directions less than from , the half of the wave below zero. For the loss at , the direction (slope ) and the direction (slope ) both go downhill, is the best one, and (slope ) goes uphill. If the first derivative is silent, as the circle shows. This holds for small steps only.
When the formula fails
The proof needed to be differentiable. Here is a function that has a slope in every direction at the origin, and for which the formula is wrong in every direction except the two axes:
and .
Along the line the value is , so
as , when .
If the function is along the whole line, and the slope is . So every direction has a directional derivative: for , and for . The two partial derivatives are the slopes along the two axes, both , so and the formula says for every direction. But along the true slope is , and along the diagonal it is . The slope is not even linear in .
The reason is that is not continuous at the origin: along the parabola it equals for every , while . Straight lines through the origin never follow that curve, so they miss the jump. Having every directional derivative is therefore weaker than being differentiable, and the formula needs the stronger condition. This is the last preset of the widget: the formula row stays at while the measured slope changes with the angle, except along the two axes, where both are .
The functions of deep learning are differentiable except on thin sets, such as the kinks of ReLU (P4.4), so the formula is the working tool. The failure shows why a proof needs its condition. P1.C4’s is worse: along the diagonal its quotient is , which has no limit, so it has directional derivatives only along the two axes.
Where this shows up in machine learning
- Moving along a chosen direction. Along from the loss is the one-variable function , with . The best is , giving a loss of , while P0.2’s step reached . Choosing how far to go is the step-size question of P1.F3.
- Forward-mode automatic differentiation. P1.C10 seeds one input with derivative and the others with , which gives one partial derivative per pass. Seed with instead, and one pass gives , the Jacobian-vector product of that lesson (for one output, is the row ). The second code cell does it.
- Gradient checks along a random direction. Nudging every weight costs evaluations. The slope along one random unit direction costs two, and it should match from backpropagation. This is a cheaper variant of the gradient check of P4.8 (and P1.C5), taught here. In dimensions a random unit direction gives of root-mean-square size (a typical order of magnitude, not an exact value), so a bug in one entry shows as a small difference: check several directions. This is evidence, not proof.
- Other step directions. Momentum and Adam (P1.F5, P4.13) step along directions other than . For any step direction the first-order change is per unit of , and a negative number means downhill.
Go deeper Corners: slopes from one side only
For at the origin the slice is , a V with its point at . The two-sided limit does not exist, so there is no directional derivative in the sense above, and no gradient. Looking only forward ( with ) gives a one-sided directional derivative . It is positive in a direction and in the opposite direction, so , and it is not linear in . The ReLU function of P4.4 has the same kind of corner, and training software picks one convention for the slope at that single point.
Go deeper More inputs, and the bend of the slice
With inputs the proof is unchanged. The directions of zero slope are those perpendicular to : two in 2-D, a whole circle of directions in 3-D.
The slice has a second derivative too. For the loss at along the slice has : it bends upward, which is why the secants in the table sit above the tangent. This number is the curvature of the loss along the direction, and P1.C8 shows that it comes from the matrix of second derivatives (the Hessian).
Directional derivatives in three depths
Intuition
Slice the surface with a vertical sheet along a line through your point. The edge of the sheet is the slice , and its slope at your point is the slope you feel walking that way. Turn the sheet and the slope changes like a cosine, from the steepest climb to the steepest drop.
If the surface is smooth, a tilted plane fits it near and all the slopes come from that plane. A jump or a corner spoils the plane, and the shortcut is not allowed.
Math
If is differentiable at : , and for any vector , .
For in 2-D: . In any dimension . Descent direction: . Forward mode with seed returns , which is for a scalar .
Code
def dir_deriv(f, p, v, h=1e-5):
"""Slope of f at p along v, by a tiny step each way (2 evaluations of f)."""
plus = [pi + h * vi for pi, vi in zip(p, v)]
minus = [pi - h * vi for pi, vi in zip(p, v)]
return (f(plus) - f(minus)) / (2 * h)
f = lambda p: p[0]**2 + 3 * p[0] * p[1]
dir_deriv(f, [2, 1], [0.6, 0.8]) # about 9.0In PyTorch, forward mode is torch.func.jvp, which returns the value and the derivative along the direction in one call (Colab or your machine, not in the browser here):
import torch
from torch.func import jvp
f = lambda p: p[0]**2 + 3 * p[0] * p[1]
value, slope = jvp(f, (torch.tensor([2.0, 1.0]),), (torch.tensor([0.6, 0.8]),))
print(value, slope) # about 10 and 9 (float32 may print extra digits)Try it: slopes in code
The first cell cuts the loss along a line, finds the slope from secants, tries a vector that is not a unit vector, and measures the function along several directions. The second builds forward mode from a small class of pairs (a value and its derivative along ) and checks a gradient along random directions with inputs. Predict the output before you run.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: on the stretched bowl at , loop over the angles and print the whole-degree directions whose slope is within of (there are two).
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: run the check again with the bug in a different entry, or with instead of . Does the buggy gradient get easier or harder to catch?
Common mistakes
Check your understanding
At a point . What is the directional derivative along the unit vector ?
It is the dot product . The value treats the second entry as . The pair lists the products without adding them, but a slope is one number. The value is the slope along .
On the loss at , . For the vector , what are the slope per unit of along and the slope per unit distance?
The slope per unit of is . One unit of moves units of distance, so the slope per unit distance is . Reporting for both rates ignores that is not a unit vector, and swapping them is backwards. The values and add the gradient entries instead of weighting them by the entries of .
At a point . Which unit vector gives a directional derivative of exactly ?
We need , and . This direction is perpendicular to the gradient, along the contour line. The vector points along the gradient, with slope . The other two give and , which are not zero.
The function with has a directional derivative at the origin in every direction, yet gives the wrong answer for most of them. Why?
The function equals along the parabola but at the origin, so it is not continuous there, and no tilted plane fits it. The formula is proved only for differentiable functions. The function does have a slope in every direction, so the claim that it has slopes along the axes only is false. The formula is stated for unit vectors, so the claim that it works only for vectors that are not unit vectors has it backwards. And the two partial derivatives at the origin are both , not large.
Exercises
- For at , find the slope along and along the unit vector .
Show answer
. Along the slope is (the partial derivative with respect to ). Along it is . - The slice of the P0.2 loss is a parabola. Find without expanding it.
Show answer
. - A gradient has length . What are the smallest and largest slopes over all unit directions, and which angle from the gradient gives the slope ?
Show answer
The slopes lie between and . For we need , so , on either side of the gradient (two directions). - For , is a descent direction? Is ?
Show answer
, so goes uphill. , so goes downhill. - For at the origin, find along . What would the formula give?
Show answer
. The formula gives , because both partial derivatives are . - For from along , find the slice, the best and the lowest value of along the line.
Show answer
. The minimum is at , where .
Next: P1.C7 collects the partial derivatives of functions with several outputs into a matrix, the Jacobian, and its product with a vector is the directional derivative of this lesson in one more guise. P1.C8 adds second derivatives, which measure how a slice bends. Gradient descent proper, with the learning rate, is P1.F3.