TExcelTAD
Home › Calculus Essentials › Gradient and Directional Derivative

Gradient and Directional Derivative

The gradient collects all the partial derivatives of a function into one vector. That vector points in the direction in which the function increases fastest, and its length is that fastest rate. Turn it around and you have the direction of steepest descent, the idea behind gradient descent, which trains almost every machine-learning model.

The gradient vector

For f(x,y)f(x, y) or f(x,y,z)f(x, y, z):

∇f=⟨∂f∂x,∂f∂y⟩or∇f=⟨∂f∂x,∂f∂y,∂f∂z⟩\nabla f = \left\langle \frac{\partial f}{\partial x}, \frac{\partial f}{\partial y} \right\rangle \qquad\text{or}\qquad \nabla f = \left\langle \frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}, \frac{\partial f}{\partial z} \right\rangle

The symbol ∇\nabla is read "nabla" or "del". The gradient is a vector at each point: for f(x,y)=x2+3y2f(x, y) = x^2 + 3y^2, ∇f=⟨2x,6y⟩\nabla f = \langle 2x, 6y \rangle, so at (1,1)(1, 1) it is ⟨2,6⟩\langle 2, 6 \rangle and at (2,0)(2, 0) it is ⟨4,0⟩\langle 4, 0 \rangle.

Directional derivatives

Partial derivatives give the rate of change along the xx and yy axes. For any other direction, given as a unit vector u\mathbf{u}, the directional derivative is

Duf=∇f⋅uD_{\mathbf{u}} f = \nabla f \cdot \mathbf{u}

Why a dot product? For a small step h⋅uh \cdot \mathbf{u} the linear approximation gives f(p+h⋅u)−f(p)≈fx⋅h⋅u1+fy⋅h⋅u2=h⋅(∇f⋅u)f(\mathbf{p} + h \cdot \mathbf{u}) - f(\mathbf{p}) \approx f_x \cdot h \cdot u_1 + f_y \cdot h \cdot u_2 = h \cdot (\nabla f \cdot \mathbf{u}). Dividing by hh gives the rate.

Note: u\mathbf{u} must have length 1. If you are given a direction like ⟨3,4⟩\langle 3, 4 \rangle, normalise it first to ⟨0.6,0.8⟩\langle 0.6, 0.8 \rangle, otherwise the rate is scaled by the vector's length.

Steepest ascent

Since Duf=∇f⋅u=∥∇f∥cos⁡θD_{\mathbf{u}} f = \nabla f \cdot \mathbf{u} = \lVert \nabla f \rVert \cos\theta, where θ\theta is the angle between u\mathbf{u} and ∇f\nabla f:

Direction u\mathbf{u} θ\theta DufD_{\mathbf{u}} f
along ∇f\nabla f 0° ∥∇f∥\lVert \nabla f \rVert, the largest possible rate (steepest ascent)
opposite to ∇f\nabla f 180° −∥∇f∥-\lVert \nabla f \rVert, steepest descent
perpendicular to ∇f\nabla f 90° 0: ff does not change, you walk along a level curve

The last row means that the gradient is perpendicular to the level curves (in 3D, to the level surfaces). This is also why ∇F\nabla F is a normal vector of the surface F(x,y,z)=cF(x, y, z) = c, a handy way to get normals of implicit surfaces and signed distance fields.

python · try it yourself
import numpy as np

def f(p):
    x, y = p
    return x**2 + 3 * y**2 + x * y

def grad(p):
    x, y = p
    return np.array([2 * x + y, 6 * y + x])

p = np.array([1.0, 2.0])
g = grad(p)
print("gradient at (1, 2):", g, " length", round(float(np.linalg.norm(g)), 4))

for name, d in [("along +x   ", [1, 0]), ("toward (3,4)", [3, 4]), ("along grad ", g), ("perp. grad ", [-g[1], g[0]])]:
    u = np.array(d, dtype=float) / np.linalg.norm(d)
    h = 1e-6
    numeric = (f(p + h * u) - f(p - h * u)) / (2 * h)
    print(f"{name}: grad·u = {np.dot(g, u):8.4f}   numeric {numeric:8.4f}")
gradient at (1, 2): [ 4. 13.]  length 13.6015
along +x   : grad·u =   4.0000   numeric   4.0000
toward (3,4): grad·u =  12.8000   numeric  12.8000
along grad : grad·u =  13.6015   numeric  13.6015
perp. grad : grad·u =   0.0000   numeric   0.0000

No direction beats the gradient direction's 13.6015, and the perpendicular direction gives zero change, as the table predicts.

Gradient descent

To find a minimum of ff, start somewhere and repeatedly take a small step against the gradient:

p←p−η⋅∇f(p)η=learning rate (step size)\mathbf{p} \leftarrow \mathbf{p} - \eta \cdot \nabla f(\mathbf{p}) \qquad \eta = \text{learning rate (step size)}

Near a minimum ∇f\nabla f gets small, so the steps shrink on their own. If η\eta is too large the iteration overshoots and can diverge; if it is too small, progress is slow. On a long narrow valley the gradient points mostly across the valley, not along it, so the path zig-zags. Momentum and Adam were invented to fix that; see Gradient Descent.

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

f = lambda x, y: x**2 + 8 * y**2           # a narrow valley
grad = lambda p: np.array([2 * p[0], 16 * p[1]])

p, eta = np.array([-4.0, 1.5]), 0.11
path = [p.copy()]
for _ in range(25):
    p = p - eta * grad(p)
    path.append(p.copy())
path = np.array(path)
print("after  5 steps:", np.round(path[5], 4), " f =", round(float(f(*path[5])), 4))
print("after 25 steps:", np.round(path[25], 4), " f =", round(float(f(*path[25])), 6))

X, Y = np.meshgrid(np.linspace(-5, 5, 200), np.linspace(-2, 2, 200))
plt.figure(figsize=(6, 4))
plt.contour(X, Y, f(X, Y), levels=12, cmap="viridis")
plt.plot(path[:, 0], path[:, 1], "o-", color="crimson", markersize=3)
plt.title("Gradient descent zig-zags across a narrow valley"); plt.xlabel("x"); plt.ylabel("y")
after  5 steps: [-1.1549 -0.3803]  f = 2.4909
after 25 steps: [-0.008  -0.0016]  f = 8.4e-05

Each step multiplies yy by (1−16⋅0.11)=−0.76(1 - 16 \cdot 0.11) = -0.76, so yy flips sign every step (the zig-zag) while shrinking; xx is multiplied by 0.78 per step and creeps toward 0.

In software

  • Training neural networks. The loss is a function of all the weights, and ∇L\nabla L is a vector with one entry per weight, computed by backpropagation. Stochastic gradient descent estimates it on a small batch of data each step.
  • Graphics. The gradient of a signed distance field gives surface normals for lighting; the gradient of a heightmap gives slopes for terrain shading and for deciding where water flows.
  • Games and robotics. "Potential field" navigation moves an agent along −∇-\nabla of a cost that is high near obstacles and low at the goal.
  • Edge detection. The gradient of image brightness (Sobel filters) is large at edges and points across them.

Exercises

Exercise 1: Compute a gradient

Find ∇f\nabla f for f(x,y,z)=x2y+yz3f(x, y, z) = x^2y + yz^3 and evaluate it at (1,−2,1)(1, -2, 1).

Answer

∇f=⟨2xy,x2+z3,3yz2⟩=⟨−4,2,−6⟩\nabla f = \langle 2xy, x^2 + z^3, 3yz^2 \rangle = \langle -4, 2, -6 \rangle at (1,−2,1)(1, -2, 1).

Solution
fx=2xy→2⋅1⋅(−2)=−4fy=x2+z3→1+1=2fz=3yz2→3⋅(−2)⋅1=−6\begin{aligned} f_x &= 2xy && \to 2 \cdot 1 \cdot (-2) = -4 \\ f_y &= x^2 + z^3 && \to 1 + 1 = 2 \\ f_z &= 3yz^2 && \to 3 \cdot (-2) \cdot 1 = -6 \end{aligned}

Exercise 2: Directional derivative

For f(x,y)=xeyf(x, y) = x e^y, find the rate of change at (2,0)(2, 0) in the direction of ⟨1,1⟩\langle 1, 1 \rangle.

Answer

3/2≈2.1213/\sqrt{2} \approx 2.121.

Solution
∇f=⟨ey,xey⟩=⟨1,2⟩at (2,0)u=⟨1,1⟩/2Duf=(1+2)/2=3/2≈2.121\begin{aligned} \nabla f &= \langle e^y, x e^y \rangle = \langle 1, 2 \rangle \quad \text{at } (2, 0) \\ \mathbf{u} &= \langle 1, 1 \rangle / \sqrt{2} \\ D_{\mathbf{u}} f &= (1 + 2)/\sqrt{2} = 3/\sqrt{2} \approx 2.121 \end{aligned}

Exercise 3: Steepest ascent

A hill has height h(x,y)=100−0.5x2−y2h(x, y) = 100 - 0.5x^2 - y^2. Standing at (4,1.5)(4, 1.5), in which unit direction is the climb steepest, and how steep is it?

Answer

Direction ⟨−0.8,−0.6⟩\langle -0.8, -0.6 \rangle, slope 5 (height units per unit of horizontal distance).

Solution
∇h=⟨−x,−2y⟩=⟨−4,−3⟩at (4,1.5)∥∇h∥=16+9=5direction=∇h/∥∇h∥=⟨−0.8,−0.6⟩\begin{aligned} \nabla h &= \langle -x, -2y \rangle = \langle -4, -3 \rangle \quad \text{at } (4, 1.5) \\ \lVert \nabla h \rVert &= \sqrt{16 + 9} = 5 \\ \text{direction} &= \nabla h / \lVert \nabla h \rVert = \langle -0.8, -0.6 \rangle \end{aligned}

The steepest way up points back toward the summit at (0,0)(0, 0), and the slope there is ∥∇h∥=5\lVert \nabla h \rVert = 5.

Exercise 4: Learning rate experiment (code)

Run gradient descent on f(x,y)=x2+8y2f(x, y) = x^2 + 8y^2 from (−4,1.5)(-4, 1.5) for 25 steps with η=0.05\eta = 0.05, 0.11 and 0.13. Which one diverges, and why?

Answer

η=0.13\eta = 0.13 diverges: the y-factor 1−16η=−1.081 - 16\eta = -1.08 has size above 1. η=0.05\eta = 0.05 converges without zig-zag but slowly in xx; η=0.11\eta = 0.11 converges with zig-zag.

Solution

Each step multiplies xx by (1−2η)(1 - 2\eta) and yy by (1−16η)(1 - 16\eta). The iteration converges only if both factors lie strictly between −1 and 1, i.e. η<2/16=0.125\eta < 2/16 = 0.125.

python · try it yourself
import numpy as np
for eta in [0.05, 0.11, 0.13]:
    p = np.array([-4.0, 1.5])
    for _ in range(25):
        p = p - eta * np.array([2 * p[0], 16 * p[1]])
    print(eta, [round(float(c), 4) for c in p])
0.05 [-0.2872, 0.0]
0.11 [-0.008, -0.0016]
0.13 [-0.0022, -10.2727]

Test yourself

In which direction does ff increase fastest?

  1. Perpendicular to ∇f\nabla f
  2. Along ∇f\nabla f
  3. Along −∇f-\nabla f
  4. Along the x-axis

The gradient of ff at a point is perpendicular to…

  1. the level curve of ff through that point
  2. the x-axis
  3. every other gradient
  4. the tangent plane's normal

The gradient of ff at (1,2)(1, 2) is ⟨3,−4⟩\langle 3, -4 \rangle. What is the largest possible rate of change of ff there?

  1. 3
  2. 7
  3. −4
  4. 5