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 or :
The symbol is read "nabla" or "del". The gradient is a vector at each point: for , , so at it is and at it is .
Directional derivatives
Partial derivatives give the rate of change along the and axes. For any other direction, given as a unit vector , the directional derivative is
Why a dot product? For a small step the linear approximation gives . Dividing by gives the rate.
Note: must have length 1. If you are given a direction like , normalise it first to , otherwise the rate is scaled by the vector's length.
Steepest ascent
Since , where is the angle between and :
| Direction | ||
|---|---|---|
| along | 0° | , the largest possible rate (steepest ascent) |
| opposite to | 180° | , steepest descent |
| perpendicular to | 90° | 0: 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 is a normal vector of the surface , a handy way to get normals of implicit surfaces and signed distance fields.
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 , start somewhere and repeatedly take a small step against the gradient:
Near a minimum gets small, so the steps shrink on their own. If 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.
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 by , so flips sign every step (the zig-zag) while shrinking; 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 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 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 for and evaluate it at .
Answer
at .
Solution
Exercise 2: Directional derivative
For , find the rate of change at in the direction of .
Answer
.
Solution
Exercise 3: Steepest ascent
A hill has height . Standing at , in which unit direction is the climb steepest, and how steep is it?
Answer
Direction , slope 5 (height units per unit of horizontal distance).
Solution
The steepest way up points back toward the summit at , and the slope there is .
Exercise 4: Learning rate experiment (code)
Run gradient descent on from for 25 steps with , 0.11 and 0.13. Which one diverges, and why?
Answer
diverges: the y-factor has size above 1. converges without zig-zag but slowly in ; converges with zig-zag.
Solution
Each step multiplies by and by . The iteration converges only if both factors lie strictly between −1 and 1, i.e. .
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 increase fastest?
- Perpendicular to
- Along
- Along
- Along the x-axis
The gradient of at a point is perpendicular to…
- the level curve of through that point
- the x-axis
- every other gradient
- the tangent plane's normal
The gradient of at is . What is the largest possible rate of change of there?
- 3
- 7
- −4
- 5