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

Directional derivatives

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

Why this matters for machine learning

The loss of a model depends on all its weights, and training keeps asking how fast the loss changes if the weights move along some direction. That rate is a directional derivative, and the gradient is the tool that computes it for every direction at once.

  • Choosing how far to move along a direction is a one-variable problem about the slice of the loss along that line, which is the step-size question of gradient descent. (P1.F3: Gradient descent)
  • Forward-mode automatic differentiation computes a directional derivative (a Jacobian-vector product) in a single pass through the computation. (P1.C10: Computational graphs and automatic differentiation)
  • A gradient check compares the slope along a random direction with ∇f⋅u\nabla f\cdot\mathbf{u}, using only two evaluations of the loss however many weights there are. (P4.8: Backpropagation: step by step with numbers)
  • Optimizers that do not step exactly along −∇L-\nabla\mathcal{L} still go downhill, to first order, when the slope along their step direction is negative. (P1.F5: Momentum and adaptive steps (preview), coming soon)

Before this: The gradient, The chain rule, Dot product and cosine similarity

After this lesson you can

  • Define the directional derivative Duf(p)D_{\mathbf{u}}f(\mathbf{p}) as a limit, as the slope at t=0t=0 of the one-variable slice g(t)=f(p+tu)g(t)=f(\mathbf{p}+t\mathbf{u}), and estimate it from secant slopes
  • Show that Duf=∇f⋅uD_{\mathbf{u}}f=\nabla f\cdot\mathbf{u} when ff is differentiable, say what can go wrong when it is not, and compute with a vector that is not a unit vector (slope per unit of tt against slope per unit distance)
  • Describe the slope as a function of the direction, ∥∇f∥cos⁡(θ−φ)\lVert\nabla f\rVert\cos(\theta-\varphi): its range, the two directions for each slope, the directions of zero slope, and which directions go downhill

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 p\mathbf{p} and a unit vector u\mathbf{u} (length 1), which gives a direction. Walking from p\mathbf{p} along u\mathbf{u} for a distance tt takes you to p+tu\mathbf{p}+t\mathbf{u}, and a negative tt means walking backwards. Along this line ff depends on one number, tt:

g(t)=f(p+tu).g(t)=f(\mathbf{p}+t\mathbf{u}).

This is a slice of ff along the line, like the slices of P1.C4 but in any direction instead of only along the axes. The directional derivative of ff at p\mathbf{p} in the direction u\mathbf{u} is the slope of the slice at t=0t=0:

Duf(p)=g′(0)=lim⁡h→0f(p+hu)−f(p)h.\begin{aligned} D_{\mathbf{u}}f(\mathbf{p})&=g'(0) \\ &=\lim_{h\to0}\frac{f(\mathbf{p}+h\mathbf{u})-f(\mathbf{p})}{h}. \end{aligned}

The fraction is a secant slope of gg (the slope of the straight line through the points at t=0t=0 and t=ht=h, as in P1.C1). As hh shrinks, the secant turns into the tangent, and the limit is the slope of the tangent.

Take the P0.2 loss at (w,b)=(1,0)(w,b)=(1,0), where L=6\mathcal{L}=6, along the unit vector u=(0.6,0.8)\mathbf{u}=(0.6,0.8). The slice is g(t)=L(1+0.6t, 0.8t)g(t)=\mathcal{L}(1+0.6t,\,0.8t), and expanding the loss gives

g(t)=6−9.2 t+4.24 t2.g(t)=6-9.2\,t+4.24\,t^2 .

The secant slope is g(h)−g(0)h=−9.2+4.24h\frac{g(h)-g(0)}{h}=-9.2+4.24h:

step hhsecant slope
1−4.96-4.96
0.5−7.08-7.08
0.1−8.776-8.776
0.01−9.1576-9.1576
0.001−9.19576-9.19576

They head for −9.2-9.2, so DuL(1,0)=−9.2D_{\mathbf{u}}\mathcal{L}(1,0)=-9.2: going this way the loss falls by about 9.29.2 per unit of distance.

Two small facts about the definition. Partial derivatives are special cases: for u=(1,0)\mathbf{u}=(1,0) the line is horizontal and DufD_{\mathbf{u}}f is ∂f∂x\frac{\partial f}{\partial x}, and for u=(0,1)\mathbf{u}=(0,1) it is ∂f∂y\frac{\partial f}{\partial y}. (Other names for DufD_{\mathbf{u}}f are ∂f∂u\frac{\partial f}{\partial\mathbf{u}} and ∇uf\nabla_{\mathbf{u}}f.) The opposite direction flips the sign: The slice along −u-\mathbf{u} is the slice along u\mathbf{u} read backwards, g−u(t)=gu(−t)g_{-\mathbf{u}}(t)=g_{\mathbf{u}}(-t), so D−uf=−DufD_{-\mathbf{u}}f=-D_{\mathbf{u}}f whenever the slope exists.

In the widget, turn the direction, shrink hh, and compare the formula ∇f⋅u\nabla f\cdot\mathbf{u} (explained in the next section) with the slope measured on the slice.

Cut the surface along a line and read its slope

ℒ(w, b) = the mean squared error of P0.2, at (w, b) = (1, 0)

−10123−2−1012u∇ℒp

The slice: g(t) = ℒ(p + t u)

−2−1.5−1−0.500.511.52010203040t

tangent at t = 0 (the slope we want) secant from t = 0 to t = h

Slope for every direction of u (the angle of u, in degrees, runs along the bottom)

050100150200250300350−10010

formula ∇ℒ·u measured on the slice

u = (0.6, 0.8)
∇ℒ = (−10, −4), from the partial derivatives
formula ∇ℒ·u = −9.2
measured: slope of g at 0 = −9.2
secant slope (g(h) − g(0)) / h with h = 0.5: −7.08

The slope is negative: ℒ falls along this line, less steeply than the best direction (10.77 per unit distance).

With h = 0.5, the secant slope is −7.08, which is 2.12 above the slope of the slice, −9.2. A smaller h brings it closer.

The thin lines are contour lines and the thick one passes through p (blue). The pink arrow is the unit vector u; drag its tip, use the slider, or press the arrow keys on the tip (Shift for bigger steps). The dashed pink line is the line along which the slice is taken, and the hollow dot on it is the point p + hu. The orange arrow shows only the direction of ∇ℒ; its length is not drawn to scale.

Cut the surface along a line. Left: a contour map around the blue point p, the pink arrow u (drag its tip), the dashed line along which the slice is cut, and the direction of the gradient in orange (not to scale). Right, top: the slice g(t), its orange tangent at t = 0 and the grey secant to t = h (the hollow dot, also shown on the map). Right, bottom: the slope for every direction, from the formula (orange dashed) and measured on the slice (pink).

Things to try with the slice widget:

  1. Start with the P0.2 loss. The angle is 53.1∘53.1^\circ, so u=(0.6,0.8)\mathbf{u}=(0.6,0.8). The slice is the curve 6−9.2t+4.24t26-9.2t+4.24t^2, the tangent has slope −9.2-9.2, and the secant for h=0.5h=0.5 has slope −7.08-7.08. Move the hh slider down and watch the secant settle onto the tangent.
  2. Press First axis and Second axis: the slopes are −10-10 and −4-4, the partial derivatives of P1.C4. Press Along −∇ℒ: the slope is −10.77-10.77, the steepest descent, and the marker on the lower plot sits at the bottom of the wave.
  3. Press Along the contour line. The slope is 00, yet the slice is a curve, not a flat line. On the stretched bowl of P1.F3 (which starts straight left, with slope −2-2, and has slope −20.1-20.1 along −∇f-\nabla f) the tangent is flat and the slice curves upward on both sides.
  4. On the saddle, press Along the contour line. The contour through (1,1)(1,1) is the straight line y=xy=x, so ff is exactly 00 along it and the slice is flat everywhere.
  5. Tick Use a vector v that is not a unit vector and set the length to 22. The tangent gets twice as steep. The readout shows the slope per unit distance, which has not changed.
  6. Choose the last function, x2yx4+y2\frac{x^2y}{x^4+y^2} at the origin. The formula says 00, 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 ff at p\mathbf{p},

f(p+Δ)=  f(p)+∇f(p)⋅Δ+(error),\begin{aligned} f(\mathbf{p}+\boldsymbol{\Delta})=\;&f(\mathbf{p})+\nabla f(\mathbf{p})\cdot\boldsymbol{\Delta}\\&+(\text{error}), \end{aligned}

where the error is much smaller than the length ∥Δ∥\lVert\boldsymbol{\Delta}\rVert of the step. (That is what “differentiable at p\mathbf{p}” means: the tilted plane fits better than any fixed multiple of the step.) Take the step Δ=hu\boldsymbol{\Delta}=h\mathbf{u} and divide by hh:

f(p+hu)−f(p)h=  ∇f(p)⋅u+errorh.\begin{aligned} \frac{f(\mathbf{p}+h\mathbf{u})-f(\mathbf{p})}{h}=\;&\nabla f(\mathbf{p})\cdot\mathbf{u}\\&+\frac{\text{error}}{h}. \end{aligned}

The error term goes to 00 as h→0h\to0, so the limit is

Duf(p)=∇f(p)⋅u.D_{\mathbf{u}}f(\mathbf{p})=\nabla f(\mathbf{p})\cdot\mathbf{u}.

The chain rule gives the same formula as a picture. The slice is g(t)=f(x(t),y(t))g(t)=f(x(t),y(t)) with x(t)=p1+tu1x(t)=p_1+tu_1 and y(t)=p2+tu2y(t)=p_2+tu_2, so x′(t)=u1x'(t)=u_1 and y′(t)=u2y'(t)=u_2. The value tt reaches ff by two routes, through xx and through yy. Multiply along each route and add the routes (the same rule that P1.C3 previewed for one input feeding two routes):

g′(0)=∂f∂x u1+∂f∂y u2=∇f⋅u.g'(0)=\frac{\partial f}{\partial x}\,u_1+\frac{\partial f}{\partial y}\,u_2=\nabla f\cdot\mathbf{u}.

This version also needs ff to be differentiable at p\mathbf{p} (the failing example below shows why).

Check it. For the loss at (1,0)(1,0) with ∇L=(−10,−4)\nabla\mathcal{L}=(-10,-4) and u=(0.6,0.8)\mathbf{u}=(0.6,0.8): −10(0.6)−4(0.8)=−9.2-10(0.6)-4(0.8)=-9.2, the limit of the table. For f=x2+3xyf=x^2+3xy at (2,1)(2,1), where ∇f=(7,6)\nabla f=(7,6), along the same u\mathbf{u}: 7(0.6)+6(0.8)=97(0.6)+6(0.8)=9.

What the formula tells us:

  • The two partials give every slope. The slope along u\mathbf{u} is a weighted sum of the two partial derivatives, with the entries of u\mathbf{u} as weights. It is not their average: along (0.707,0.707)(0.707,0.707) the loss slope is −10(0.707)−4(0.707)≈−9.9-10(0.707)-4(0.707)\approx-9.9.
  • The slope is linear in the direction. Dv+wf=Dvf+DwfD_{\mathbf{v}+\mathbf{w}}f=D_{\mathbf{v}}f+D_{\mathbf{w}}f and Dcvf=c DvfD_{c\mathbf{v}}f=c\,D_{\mathbf{v}}f, 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 p\mathbf{p}. Continuous partial derivatives near p\mathbf{p} 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 g(t)=f(p+tv)g(t)=f(\mathbf{p}+t\mathbf{v}) makes sense for any vector v\mathbf{v}, and its slope at 00 is

g′(0)=∇f⋅v.g'(0)=\nabla f\cdot\mathbf{v}.

If v=c u\mathbf{v}=c\,\mathbf{u} with u\mathbf{u} a unit vector and c=∥v∥c=\lVert\mathbf{v}\rVert, the new slice is the old one speeded up: gv(t)=gu(ct)g_{\mathbf{v}}(t)=g_{\mathbf{u}}(ct). One unit of tt now covers a distance cc, and the chain rule gives gv′(0)=c gu′(0)g_{\mathbf{v}}'(0)=c\,g_{\mathbf{u}}'(0):

∇f⋅v=∥v∥  Dv/∥v∥f.\nabla f\cdot\mathbf{v}=\lVert\mathbf{v}\rVert\;D_{\mathbf{v}/\lVert\mathbf{v}\rVert}f .

So there are two different rates. ∇f⋅v\nabla f\cdot\mathbf{v} is the slope per unit of tt, and dividing by ∥v∥\lVert\mathbf{v}\rVert gives the slope per unit distance. Take v=(3,4)\mathbf{v}=(3,4), which has length 55, on the loss at (1,0)(1,0):

∇L⋅v=(−10)(3)+(−4)(4)=−46,\nabla\mathcal{L}\cdot\mathbf{v}=(-10)(3)+(-4)(4)=-46,

and −46/5=−9.2-46/5=-9.2.

The vector (3,4)(3,4) points the same way as (0.6,0.8)(0.6,0.8), so the slope per unit distance is the −9.2-9.2 found before. The same −46-46 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 v\mathbf{v} would double the number and no direction would be the best. A gradient-descent step fits the other reading: the step −η∇f-\eta\nabla f is the vector v\mathbf{v} at t=1t=1, so the first-order change in ff is ∇f⋅v=−η∥∇f∥2\nabla f\cdot\mathbf{v}=-\eta\lVert\nabla f\rVert^2, 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 v\mathbf{v} 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 θ\theta is ∥∇f∥cos⁡(θ−φ)\lVert\nabla f\rVert\cos(\theta-\varphi), where φ\varphi is the angle of the gradient (when ∇f≠0\nabla f\neq\mathbf{0}; with a zero gradient there is no φ\varphi, and every slope is 00). 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 −∥∇f∥-\lVert\nabla f\rVert and ∥∇f∥\lVert\nabla f\rVert occurs for exactly two directions, mirror images across the gradient. For the loss at (1,0)(1,0): ∥∇L∥=10.77\lVert\nabla\mathcal{L}\rVert=10.77 and φ=201.80∘\varphi=201.80^\circ, and the slope −9.2-9.2 occurs at 53.13∘53.13^\circ (the (0.6,0.8)(0.6,0.8) above) and at 350.47∘350.47^\circ, where u≈(0.986,−0.166)\mathbf{u}\approx(0.986,-0.166) and −10(0.986)−4(−0.166)≈−9.2-10(0.986)-4(-0.166)\approx-9.2.
  • Any number of inputs. The bound holds in every dimension: ∣∇f⋅u∣≤∥∇f∥∥u∥=∥∇f∥\lvert\nabla f\cdot\mathbf{u}\rvert\le\lVert\nabla f\rVert\lVert\mathbf{u}\rVert=\lVert\nabla f\rVert (the Cauchy–Schwarz inequality), with equality, when ∇f≠0\nabla f\neq\mathbf{0}, only if u\mathbf{u} is along ∇f\nabla f or against it. So the steepest-ascent fact of P1.C5 holds for any number of weights.
  • The stretched bowl of P1.F3. At (1,1)(1,1), ∇f=(2,20)\nabla f=(2,20) has length 20.120.1 and φ=84.29∘\varphi=84.29^\circ. Straight left (θ=180∘\theta=180^\circ) the slope is 20.1cos⁡(95.71∘)=−220.1\cos(95.71^\circ)=-2, and against the gradient it is −20.1-20.1: the pair of rates in P1.F3.

Zero slope and the contour line. When ∇f≠0\nabla f\neq\mathbf{0}, the slope is 00 when u\mathbf{u} is perpendicular to ∇f\nabla f, which is the direction of the contour line through p\mathbf{p} (P1.C5). But g′(0)=0g'(0)=0 does not mean the slice is constant. For f=x2+y2f=x^2+y^2 at (3,4)(3,4), the contour is a circle and the straight line along its tangent u=(−0.8,0.6)\mathbf{u}=(-0.8,0.6) leaves the circle: g(t)=(3−0.8t)2+(4+0.6t)2=25+t2g(t)=(3-0.8t)^2+(4+0.6t)^2=25+t^2. The slope at t=0t=0 is 00, and ff rises on both sides at second order. On the saddle x2−y2x^2-y^2 the contour through (1,1)(1,1) is itself a straight line, and there g≡0g\equiv0. The first derivative alone cannot tell these cases apart.

Which directions go downhill. If ∇f⋅d<0\nabla f\cdot\mathbf{d}<0, then g′(0)<0g'(0)<0 and the slice falls for small t>0t>0: d\mathbf{d} is a descent direction. In 2-D these are the directions less than 90∘90^\circ from −∇f-\nabla f, the half of the wave below zero. For the loss at (1,0)(1,0), the direction (0,1)(0,1) (slope −4-4) and the direction (1,0)(1,0) (slope −10-10) both go downhill, −∇L-\nabla\mathcal{L} is the best one, and (−1,0)(-1,0) (slope +10+10) goes uphill. If ∇f⋅d=0\nabla f\cdot\mathbf{d}=0 the first derivative is silent, as the circle shows. This holds for small steps only.

When the formula fails

The proof needed ff 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:

f(x,y)=x2yx4+y2  for (x,y)≠(0,0),f(x,y)=\frac{x^2y}{x^4+y^2}\ \text{ for }(x,y)\neq(0,0),

and f(0,0)=0f(0,0)=0.

Along the line (tu1,tu2)(tu_1,tu_2) the value is f=t u12u2t2u14+u22f=\dfrac{t\,u_1^2u_2}{t^2u_1^4+u_2^2}, so

f(tu)−f(0)t=u12u2t2u14+u22  ⟶  u12u2\frac{f(t\mathbf{u})-f(\mathbf{0})}{t}=\frac{u_1^2u_2}{t^2u_1^4+u_2^2}\;\longrightarrow\;\frac{u_1^2}{u_2}

as t→0t\to0, when u2≠0u_2\neq0.

If u2=0u_2=0 the function is 00 along the whole line, and the slope is 00. So every direction has a directional derivative: Duf(0)=u12/u2D_{\mathbf{u}}f(\mathbf{0})=u_1^2/u_2 for u2≠0u_2\neq0, and 00 for u2=0u_2=0. The two partial derivatives are the slopes along the two axes, both 00, so ∇f=(0,0)\nabla f=(0,0) and the formula ∇f⋅u\nabla f\cdot\mathbf{u} says 00 for every direction. But along (0.6,0.8)(0.6,0.8) the true slope is 0.36/0.8=0.450.36/0.8=0.45, and along the diagonal (0.707,0.707)(0.707,0.707) it is 0.7070.707. The slope is not even linear in u\mathbf{u}.

The reason is that ff is not continuous at the origin: along the parabola y=x2y=x^2 it equals x42x4=12\frac{x^4}{2x^4}=\frac12 for every x≠0x\neq0, while f(0,0)=0f(0,0)=0. 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 00 while the measured slope changes with the angle, except along the two axes, where both are 00.

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 xyx2+y2\frac{xy}{x^2+y^2} is worse: along the diagonal its quotient is 1/2h\frac{1/2}{h}, 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 d=−∇L=(10,4)\mathbf{d}=-\nabla\mathcal{L}=(10,4) from (1,0)(1,0) the loss is the one-variable function g(t)=6−116t+642.67t2g(t)=6-116t+642.67t^2, with g′(0)=−116=−∥∇L∥2g'(0)=-116=-\lVert\nabla\mathcal{L}\rVert^2. The best tt is 0.09020.0902, giving a loss of 0.76560.7656, while P0.2’s step t=0.05t=0.05 reached 1.80671.8067. Choosing how far to go is the step-size question of P1.F3.
  • Forward-mode automatic differentiation. P1.C10 seeds one input with derivative 11 and the others with 00, which gives one partial derivative per pass. Seed with v\mathbf{v} instead, and one pass gives ∇f⋅v\nabla f\cdot\mathbf{v}, the Jacobian-vector product Jv\mathbf{J}\mathbf{v} of that lesson (for one output, J\mathbf{J} is the row (∇f)⊤(\nabla f)^\top). The second code cell does it.
  • Gradient checks along a random direction. Nudging every weight costs 2n2n evaluations. The slope along one random unit direction costs two, and it should match ∇f⋅u\nabla f\cdot\mathbf{u} from backpropagation. This is a cheaper variant of the gradient check of P4.8 (and P1.C5), taught here. In nn dimensions a random unit direction gives ∇f⋅u\nabla f\cdot\mathbf{u} of root-mean-square size ∥∇f∥/n\lVert\nabla f\rVert/\sqrt n (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 −∇f-\nabla f. For any step direction d\mathbf{d} the first-order change is ∇L⋅d\nabla\mathcal{L}\cdot\mathbf{d} per unit of tt, and a negative number means downhill.
Go deeper Corners: slopes from one side only

For f(x,y)=∣x∣+∣y∣f(x,y)=\lvert x\rvert+\lvert y\rvert at the origin the slice is g(t)=∣t∣(∣u1∣+∣u2∣)g(t)=\lvert t\rvert(\lvert u_1\rvert+\lvert u_2\rvert), a V with its point at t=0t=0. The two-sided limit does not exist, so there is no directional derivative in the sense above, and no gradient. Looking only forward (h→0h\to0 with h>0h>0) gives a one-sided directional derivative ∣u1∣+∣u2∣\lvert u_1\rvert+\lvert u_2\rvert. It is positive in a direction and in the opposite direction, so D−u≠−DuD_{-\mathbf{u}}\neq-D_{\mathbf{u}}, and it is not linear in u\mathbf{u}. 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 nn inputs the proof is unchanged. The directions of zero slope are those perpendicular to ∇f\nabla f: two in 2-D, a whole circle of directions in 3-D.

The slice has a second derivative too. For the loss at (1,0)(1,0) along (0.6,0.8)(0.6,0.8) the slice 6−9.2t+4.24t26-9.2t+4.24t^2 has g′′(0)=8.48g''(0)=8.48: 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 g(t)g(t), 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 p\mathbf{p} and all the slopes come from that plane. A jump or a corner spoils the plane, and the shortcut ∇f⋅u\nabla f\cdot\mathbf{u} is not allowed.

Math

Duf(p)=lim⁡h→0f(p+hu)−f(p)h=ddtf(p+tu)∣t=0.\begin{gathered} D_{\mathbf{u}}f(\mathbf{p}) \\ \quad=\lim_{h\to0}\frac{f(\mathbf{p}+h\mathbf{u})-f(\mathbf{p})}{h} \\ \quad=\frac{\mathrm{d}}{\mathrm{d}t}f(\mathbf{p}+t\mathbf{u})\Big|_{t=0}. \end{gathered}

If ff is differentiable at p\mathbf{p}: Duf=∇f(p)⋅uD_{\mathbf{u}}f=\nabla f(\mathbf{p})\cdot\mathbf{u}, and for any vector v\mathbf{v}, ddtf(p+tv)∣0=∇f⋅v=∥v∥ Dv/∥v∥f\frac{\mathrm{d}}{\mathrm{d}t}f(\mathbf{p}+t\mathbf{v})\big|_{0}=\nabla f\cdot\mathbf{v}=\lVert\mathbf{v}\rVert\,D_{\mathbf{v}/\lVert\mathbf{v}\rVert}f.

For ∥u∥=1\lVert\mathbf{u}\rVert=1 in 2-D: Duf=∥∇f∥cos⁡(θ−φ)∈[−∥∇f∥,∥∇f∥]D_{\mathbf{u}}f=\lVert\nabla f\rVert\cos(\theta-\varphi)\in[-\lVert\nabla f\rVert,\lVert\nabla f\rVert]. In any dimension ∣∇f⋅u∣≤∥∇f∥\lvert\nabla f\cdot\mathbf{u}\rvert\le\lVert\nabla f\rVert. Descent direction: ∇f⋅d<0\nabla f\cdot\mathbf{d}<0. Forward mode with seed v\mathbf{v} returns Jv\mathbf{J}\mathbf{v}, which is ∇f⋅v\nabla f\cdot\mathbf{v} for a scalar ff.

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.0

In 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 x2yx4+y2\frac{x^2y}{x^4+y^2} along several directions. The second builds forward mode from a small class of pairs (a value and its derivative along v\mathbf{v}) and checks a gradient along random directions with 10001000 inputs. Predict the output before you run.

Try it: slices, secants and the failing function

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

Challenge: on the stretched bowl f=x2+10y2f=x^2+10y^2 at (1,1)(1,1), loop over the angles 0,…,3590,\dots,359 and print the whole-degree directions whose slope is within 0.20.2 of 55 (there are two).

Try it: forward mode and a random-direction check

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 n=10n=10 instead of 10001000. Does the buggy gradient get easier or harder to catch?

Common mistakes

Check your understanding

  1. At a point ∇f=(3,−1)\nabla f=(3,-1). What is the directional derivative along the unit vector u=(0.6,0.8)\mathbf{u}=(0.6,0.8)?

  2. On the loss at (1,0)(1,0), ∇L=(−10,−4)\nabla\mathcal{L}=(-10,-4). For the vector v=(3,4)\mathbf{v}=(3,4), what are the slope per unit of tt along p+tv\mathbf{p}+t\mathbf{v} and the slope per unit distance?

  3. At a point ∇f=(3,4)\nabla f=(3,4). Which unit vector gives a directional derivative of exactly 00?

  4. The function f=x2yx4+y2f=\dfrac{x^2y}{x^4+y^2} with f(0,0)=0f(0,0)=0 has a directional derivative at the origin in every direction, yet ∇f⋅u\nabla f\cdot\mathbf{u} gives the wrong answer for most of them. Why?

Exercises

  1. For f(x,y)=x2+3xyf(x,y)=x^2+3xy at (1,2)(1,2), find the slope along (0,1)(0,1) and along the unit vector (0.8,0.6)(0.8,0.6).
    Show answer∇f=(2x+3y,  3x)=(8,3)\nabla f=(2x+3y,\;3x)=(8,3). Along (0,1)(0,1) the slope is 33 (the partial derivative with respect to yy). Along (0.8,0.6)(0.8,0.6) it is 8(0.8)+3(0.6)=8.28(0.8)+3(0.6)=8.2.
  2. The slice g(t)=L(1+3t,4t)g(t)=\mathcal{L}(1+3t,4t) of the P0.2 loss is a parabola. Find g′(0)g'(0) without expanding it.
    Show answerg′(0)=∇L⋅(3,4)=−30−16=−46g'(0)=\nabla\mathcal{L}\cdot(3,4)=-30-16=-46.
  3. A gradient has length 55. What are the smallest and largest slopes over all unit directions, and which angle from the gradient gives the slope 2.52.5?
    Show answerThe slopes lie between −5-5 and 55. For 2.52.5 we need 5cos⁡θ=2.55\cos\theta=2.5, so θ=60∘\theta=60^\circ, on either side of the gradient (two directions).
  4. For ∇f=(3,−1)\nabla f=(3,-1), is (1,1)(1,1) a descent direction? Is (−1,0)(-1,0)?
    Show answer∇f⋅(1,1)=2>0\nabla f\cdot(1,1)=2>0, so (1,1)(1,1) goes uphill. ∇f⋅(−1,0)=−3<0\nabla f\cdot(-1,0)=-3<0, so (−1,0)(-1,0) goes downhill.
  5. For f=x2yx4+y2f=\frac{x^2y}{x^4+y^2} at the origin, find DufD_{\mathbf{u}}f along u=(0.8,0.6)\mathbf{u}=(0.8,0.6). What would the formula ∇f⋅u\nabla f\cdot\mathbf{u} give?
    Show answeru12/u2=0.64/0.6≈1.067u_1^2/u_2=0.64/0.6\approx1.067. The formula gives 00, because both partial derivatives are 00.
  6. For f=x2+10y2f=x^2+10y^2 from (1,1)(1,1) along −∇f=(−2,−20)-\nabla f=(-2,-20), find the slice, the best tt and the lowest value of ff along the line.
    Show answerg(t)=(1−2t)2+10(1−20t)2=11−404t+4004t2g(t)=(1-2t)^2+10(1-20t)^2=11-404t+4004t^2. The minimum is at t=4042⋅4004≈0.0504t=\frac{404}{2\cdot4004}\approx0.0504, where g=11−40424⋅4004≈0.809g=11-\frac{404^2}{4\cdot4004}\approx0.809.

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.

Key takeaways

  • The directional derivative Duf(p)D_{\mathbf{u}}f(\mathbf{p}) is the slope of ff along a line: lim⁡h→0f(p+hu)−f(p)h\lim_{h\to0}\frac{f(\mathbf{p}+h\mathbf{u})-f(\mathbf{p})}{h}, the slope at t=0t=0 of the one-variable slice g(t)=f(p+tu)g(t)=f(\mathbf{p}+t\mathbf{u}). Partial derivatives are the special cases along the axes.
  • If ff is differentiable at p\mathbf{p}, then Duf(p)=∇f(p)⋅uD_{\mathbf{u}}f(\mathbf{p})=\nabla f(\mathbf{p})\cdot\mathbf{u} for every u\mathbf{u}. So the partial derivatives give the slope in every direction, and the slope is linear in the direction.
  • For a vector v\mathbf{v} that is not a unit vector, ∇f⋅v\nabla f\cdot\mathbf{v} is the slope per unit of tt along p+tv\mathbf{p}+t\mathbf{v}. It equals ∥v∥\lVert\mathbf{v}\rVert times the slope per unit distance. Books use unit vectors so that directions are compared per unit distance.
  • In 2-D the slope against the direction angle is a cosine wave, ∥∇f∥cos⁡(θ−φ)\lVert\nabla f\rVert\cos(\theta-\varphi). It runs from −∥∇f∥-\lVert\nabla f\rVert to ∥∇f∥\lVert\nabla f\rVert, each value in between is reached by two directions, and it is 00 along the contour line. A direction d\mathbf{d} goes downhill, to first order, when ∇f⋅d<0\nabla f\cdot\mathbf{d}<0.
  • A slope in every direction does not make ff differentiable: x2yx4+y2\frac{x^2y}{x^4+y^2} has one at the origin, yet the formula ∇f⋅u\nabla f\cdot\mathbf{u} gives 00 for all of them. Forward-mode autodiff and one-nudge gradient checks both use ∇f⋅v\nabla f\cdot\mathbf{v}.
Found a mistake? Tell us