Module 4 · Intermediate · Many variables

The gradient explained visually

The gradient explained with pictures and Python: the partial derivatives in one arrow that points uphill, crosses contours, and guides gradient descent.

By theprogrammers team · · 14 min read

Back on the hillside. You know the slope if you step east, and the slope if you step north: two partial derivatives. But you can walk in any direction, not just those two. Which direction is steepest uphill? And which is steepest down, the quickest way to the valley?

The answer is one arrow, built from the partial derivatives: the gradient. It points in the direction where the function rises fastest, and its length says how steep that is. Turn it around and it points steepest downhill. That one idea is how almost every machine learning model is trained: compute the gradient of the loss, take a small step the opposite way, repeat.

What you need first: partial derivatives explained and functions of several variables. Knowing what a vector is helps.

Key terms

  • Gradient: the vector of all the partial derivatives of a function, written ∇f (read "grad f" or "del f"). For f(x, y), ∇f = (∂f/∂x, ∂f/∂y).
  • Direction of steepest ascent: the direction in which a small step raises the function the most. The gradient points this way.
  • Magnitude (or length) of the gradient: how steep the function is in that steepest direction.
  • Directional derivative: the slope of the function in any chosen direction, not just along an axis.
  • Gradient descent: repeatedly stepping a little in the direction opposite to the gradient, to find a minimum.

Two slopes, one arrow

Take a simple bowl: f(x, y) = x² + y². Its partial derivatives are ∂f/∂x = 2*x* and ∂f/∂y = 2*y*. At the point (1, 2), they're 2 and 4. Put them together as a vector:

∇f(1, 2) = (2, 4)

Draw that as an arrow starting at (1, 2): 2 units to the right and 4 units up. It points away from the bottom of the bowl at (0, 0), directly uphill. Here are gradient arrows at many points, drawn on the contour map:

import numpy as np
import matplotlib.pyplot as plt

def bowl(x, y):
    return x ** 2 + y ** 2

def bowl_gradient(x, y):
    return np.array([2 * x, 2 * y])     # (∂f/∂x, ∂f/∂y)

X, Y = np.meshgrid(np.linspace(-3, 3, 200), np.linspace(-3, 3, 200))
fig, ax = plt.subplots(figsize=(5.8, 5.4))
cs = ax.contour(X, Y, bowl(X, Y), levels=[1, 2, 4, 6, 9], colors="#78716c")
ax.clabel(cs, fontsize=9)
for x0, y0 in [(1, 2), (-2, 1), (2, -1), (-1, -1.5), (0.5, 0.5), (0.6, -2.5), (2.5, 1.2)]:
    gx, gy = bowl_gradient(x0, y0)
    ax.arrow(x0, y0, 0.25 * gx, 0.25 * gy, head_width=0.12, color="#c2410c", length_includes_head=True)
    ax.plot(x0, y0, "o", color="#1c1917", markersize=5)
ax.set_aspect("equal")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Gradient arrows (shortened to a quarter)")
plt.show()
A contour map of the bowl x² + y², drawn as grey circles around the origin labelled 1, 2, 4, 6 and 9. Orange arrows start at seven points; each points straight outwards, away from the centre, crossing the circles at right angles. Arrows further from the centre are longer.

ax.arrow(x, y, dx, dy) draws an arrow from (x, y) to (x + dx, y + dy). The arrows are drawn at a quarter of their real length so they fit.

Three things to notice:

  1. Every arrow points uphill, away from the bottom of the bowl.
  2. Every arrow crosses the contour lines at a right angle. Along a contour line the function doesn't change, so the steepest direction must be straight across the lines.
  3. Arrows further out are longer. The bowl gets steeper as you move away from the centre, and the gradient's length measures that steepness.

Why the gradient points steepest uphill

Stand at a point and pick a direction to step: a short arrow u of length 1. How much does the function rise per unit step in that direction? For a small step, the rise is about:

(∂f/∂x) × uₓ + (∂f/∂y) × uᵧ

That's the slope in the x direction times how much of the step goes that way, plus the same for y. In vector language it's the dot product ∇f · u, called the directional derivative.

A dot product of two arrows is largest when they point the same way. So the direction that rises fastest is the direction of ∇f itself, and the rise per unit step in that direction is the gradient's length. The direction that falls fastest is −∇f. And any direction at a right angle to ∇f gives a dot product of zero: no rise at all, which is the direction along a contour line.

Check it numerically at (1, 2): try 360 directions, measure the slope in each, and see which is steepest:

x0, y0 = 1.0, 2.0
h = 1e-5
angles = np.radians(np.arange(360))
slopes = [(bowl(x0 + h * np.cos(a), y0 + h * np.sin(a)) - bowl(x0, y0)) / h for a in angles]

steepest = np.degrees(angles[np.argmax(slopes)])
g = bowl_gradient(x0, y0)
print(f"steepest direction found: {steepest:.0f}°, slope {max(slopes):.3f}")
print(f"gradient direction:       {np.degrees(np.arctan2(g[1], g[0])):.0f}°, length {np.linalg.norm(g):.3f}")
steepest direction found: 63°, slope 4.472
gradient direction:       63°, length 4.472
  • np.cos(a) and np.sin(a) turn an angle into a step of length 1 in that direction.
  • np.arctan2(gy, gx) turns the gradient back into an angle, and np.linalg.norm(g) gives its length, √(2² + 4²).

The search over 360 directions and the gradient agree: the gradient is the steepest way up, and its length is the steepest slope.

Walking downhill: gradient descent

Now use the gradient to find a minimum, on the study-hours model from the earlier lessons: predicted marks = w × hours + b. In partial derivatives explained you derived:

  • ∂L/∂w = −2 × mean(hours × error)
  • ∂L/∂b = −2 × mean(error)

So the gradient of the loss is ∇L = (∂L/∂w, ∂L/∂b). To go downhill, step against it:

(w, b) ← (w, b) − learning rate × ∇L

The learning rate sets how big each step is. Repeat that many times, starting from a poor guess, and record the path:

hours = np.array([2, 3, 5, 6, 8, 9, 11, 12])
marks = np.array([45, 52, 50, 60, 68, 75, 74, 84])

def loss(w, b):
    return np.mean((marks - (w * hours + b)) ** 2)

def gradient(w, b):
    error = marks - (w * hours + b)
    return np.array([-2 * np.mean(hours * error), -2 * np.mean(error)])

def descend(start, learning_rate, steps):
    point = np.array(start, dtype=float)
    path = [point.copy()]
    for _ in range(steps):
        point = point - learning_rate * gradient(*point)
        path.append(point.copy())
    return np.array(path)

path = descend(start=(1.5, 25), learning_rate=0.01, steps=2000)
for step in [0, 1, 10, 100, 500, 2000]:
    w, b = path[step]
    print(f"step {step:>4}: w = {w:6.3f}, b = {b:6.3f}, loss = {loss(w, b):8.2f}")
step    0: w =  1.500, b = 25.000, loss =   851.00
step    1: w =  5.928, b = 25.560, loss =    80.36
step   10: w =  5.063, b = 25.867, loss =    36.97
step  100: w =  4.674, b = 29.221, loss =    24.21
step  500: w =  3.922, b = 35.701, loss =    11.66
step 2000: w =  3.707, b = 37.548, loss =    11.01

gradient(*point) unpacks the two numbers in point into the two arguments w and b.

The loss drops fast at first, then slowly. The first step alone cuts it from 851 to 80, yet it takes hundreds more steps to creep from 24 down to 11. By step 2,000 the point has reached the best line from the last lesson (w ≈ 3.71, b ≈ 37.55). Draw the path on the contour map to see why the middle part was so slow:

W, B = np.meshgrid(np.linspace(0.5, 6.5, 150), np.linspace(20, 55, 150))
L = np.vectorize(loss)(W, B)
fig, ax = plt.subplots(figsize=(7, 5))
cs = ax.contour(W, B, L, levels=[12, 20, 40, 80, 160, 320, 640], cmap="viridis")
ax.clabel(cs, fontsize=9)
ax.plot(path[:, 0], path[:, 1], "-", color="#c2410c", linewidth=2)
ax.plot(path[::10, 0], path[::10, 1], "o", color="#c2410c", markersize=3)
ax.plot(*path[0], "o", color="#1c1917", markersize=8)
ax.plot(3.707, 37.554, "*", color="#1c1917", markersize=14)
ax.set_xlabel("w (slope)")
ax.set_ylabel("b (intercept)")
ax.set_title("Gradient descent on the study-hours loss")
plt.show()
The tilted, elongated contour ellipses of the study-hours loss over w from 0.5 to 6.5 and b from 20 to 55. An orange path starts at a black dot at w = 1.5, b = 25. Its first step jumps almost horizontally right across the valley to about w = 5.9, overshooting the floor; it then settles back onto the valley floor near w = 5.1, b = 25.6, and from there creeps up the long diagonal floor in many small, closely spaced steps to the black star at the minimum, w = 3.71, b = 37.55.

path[::10] takes every tenth point, so the dots show the speed: far apart means big steps, crowded means small ones.

The first step heads straight across the valley, because that's where the gradient points: at the steep walls. It's so steep there that the step overshoots the floor, and the next few steps come back. Once on the valley floor, the slope along the floor is gentle, so the gradient is short and the steps are tiny. This is the long, thin valley from functions of several variables causing slow training.

Experiment: that lesson showed that centring the hours (subtracting their mean, 7) makes the valley line up with the axes. Predict: with centred hours, will gradient descent need more or fewer steps? Change the data and run it:

centred = hours - hours.mean()

def gradient_centred(w, b):
    error = marks - (w * centred + b)
    return np.array([-2 * np.mean(centred * error), -2 * np.mean(error)])

def steps_until_flat(grad, start=(1.5, 25.0), learning_rate=0.01):
    point = np.array(start)
    for step in range(1, 20_001):
        point = point - learning_rate * grad(*point)
        if np.abs(grad(*point)).max() < 0.01:     # both partials nearly zero: flat ground
            break
    return step, point

for name, grad in [("original hours", gradient), ("centred hours ", gradient_centred)]:
    step, (w, b) = steps_until_flat(grad)
    print(f"{name}: flat after {step:>4} steps, at w = {w:.3f}, b = {b:.3f}")
original hours: flat after 1629 steps, at w = 3.710, b = 37.528
centred hours : flat after  443 steps, at w = 3.707, b = 63.495

Far fewer: 443 instead of 1,629, nearly four times faster. The best slope is still about 3.71 (centring doesn't change the slope of the line), and b is now the predicted mark at the average study time, 63.5. With the valley no longer tilted, each partial derivative points almost straight at the minimum along its own axis, so the walk is short. This is the reason feature scaling speeds up gradient descent.

The learning rate matters

The step size is a choice, and a bad one breaks training. Run the original problem with three learning rates:

for lr in [0.001, 0.01, 0.03]:
    final = descend(start=(1.5, 25), learning_rate=lr, steps=200)[-1]
    print(f"learning rate {lr:<5}: after 200 steps, loss = {loss(*final):.4g}")
learning rate 0.001: after 200 steps, loss = 35.1
learning rate 0.01 : after 200 steps, loss = 17.23
learning rate 0.03 : after 200 steps, loss = 1.208e+174

Too small and the walk barely moves. Too large and each step overshoots the valley floor, landing higher up the opposite wall, and the loss explodes. The gradient descent lesson explores learning rates in detail.

The gradient with many weights

Nothing above depends on there being two inputs. A model with n weights has a loss L(w₁, …, wₙ), and its gradient is the list of all n partial derivatives:

∇L = (∂L/∂w₁, ∂L/∂w₂, …, ∂L/∂wₙ)

You can't draw a million-dimensional landscape, but the rules still hold: the gradient points steepest uphill, −∇L points steepest downhill, and at a minimum every entry is zero. Gradient descent updates every weight at once with the same line: weights ← weights − learning rate × gradient.

IdeaOne inputMany inputs
SlopeDerivative f′(x), a numberGradient ∇f, a vector
Which way is uphillSign of f′(x)Direction of ∇f
How steepSize of f′(x)Length of ∇f
At a minimumf′(x) = 0∇f = 0 (every entry)
Downhill stepx ← x − lr × f′(x)w ← w − lr × ∇L

Where machine learning uses the gradient

  • Training: gradient descent and its variants (SGD, Adam) all step against the gradient of the loss.
  • Backpropagation is a fast way to compute the gradient of a neural network's loss with respect to every weight, using the chain rule.
  • Stopping rules: training often stops when the gradient becomes very short, meaning the ground is nearly flat.
  • Explaining predictions: the gradient of a model's output with respect to its input shows which input values the prediction is most sensitive to (for images, a "saliency map").

Common mistakes

  • Stepping with the gradient instead of against it. +∇L climbs the loss. Training subtracts it.
  • Thinking the gradient points at the minimum. It points steepest downhill from where you are. In a tilted valley, that's mostly across the valley, not along it.
  • Forgetting it's a vector. "The gradient is 5" only makes sense for one input. With several, it has one entry per input, and a direction.
  • Expecting a fixed step to be safe. Steps are learning rate × gradient, so they shrink near a minimum, but too large a learning rate overshoots and diverges.

Practice

  1. Find ∇f for f(x, y) = 3*x* + y², and evaluate it at (2, −1). Which way does it point?
Show the answer

∇f = (3, 2*y*), so ∇f(2, −1) = (3, −2): 3 units right and 2 down. Increasing x raises f, and so does decreasing y (making y more negative makes y² larger).

  1. At a point, ∇f = (0, 0). What does that tell you, and what doesn't it?
Show the answer

The ground is flat there: no direction goes up or down to first order. It's a stationary point. It doesn't tell you whether it's a minimum, a maximum, or a saddle (up in one direction, down in another).

  1. Predict, then check: starting the study-hours descent from (6, 50) instead of (1.5, 25), with learning rate 0.01 and 2,000 steps, will it end near the same point?
Show the answer
w, b = descend(start=(6, 50), learning_rate=0.01, steps=2000)[-1]
print(f"w = {w:.3f}, b = {b:.3f}")
w = 3.706, b = 37.561

Yes: it ends at the same minimum, coming from the other side of the valley. The loss of a linear regression is a single bowl (it's convex), so there's only one bottom to find, wherever you start.

  1. Why do the gradient arrows on a contour map cross the contour lines at right angles?
Show the answer

Moving along a contour line doesn't change the function, so the directional derivative along it is zero. The directional derivative is ∇f · u, which is zero only when u is at a right angle to ∇f. So the gradient must be at right angles to the contour line.

  1. A friend's gradient descent loss goes 120, 340, 2,100, 15,000. What's the most likely cause, and the fix?
Show the answer

The learning rate is too large: each step overshoots the minimum and lands further up the other side. Lower the learning rate (for example, by a factor of 10), and consider scaling the features so the valley is rounder.

Interview questions

What is the gradient, and why does gradient descent move against it?

The gradient is the vector of partial derivatives of a function with respect to all its inputs. It points in the direction of steepest increase, with length equal to that rate of increase. To minimise a loss, gradient descent moves the parameters in the opposite direction, −∇L, scaled by a learning rate, which is the locally steepest way down.

Why is the gradient perpendicular to level sets (contour lines)?

The directional derivative in a unit direction u is ∇f · u. Along a level set, f doesn't change, so ∇f · u = 0 for any u tangent to it. That means ∇f is perpendicular to the level set.

Why does feature scaling speed up gradient descent?

Unscaled or uncentred features make the loss surface an elongated, often tilted valley (poorly conditioned). The gradient then points mostly across the valley rather than along it, so descent zig-zags or crawls along the floor. Standardising features makes the contours rounder, so the gradient points closer to the minimum and fewer steps are needed.

Key takeaways

  • The gradient ∇f collects all the partial derivatives into one vector.
  • It points in the direction of steepest increase; its length is how steep that is; −∇f points steepest downhill.
  • It crosses contour lines at right angles, and it's zero at a minimum, maximum or saddle.
  • Gradient descent repeats: weights ← weights − learning rate × gradient.
  • Long, thin valleys make descent slow; scaling features and choosing a good learning rate fix most problems.

Frequently asked questions

What's the difference between the gradient and the derivative?

For a function of one input, they're the same number. For several inputs, the gradient is a vector with one partial derivative per input. People often say "the derivative" loosely to mean the gradient.

What does ∇ mean?

∇ is called "nabla" or "del". ∇f means "the gradient of f". You'll also see ∇_w L, meaning the gradient of L with respect to the weights w only.

Does the gradient point straight at the minimum?

Only when the contours are circles, as in the bowl x² + y². In general it points steepest downhill from where you are, which may be at an angle to the direction of the minimum.

What to learn next

  1. Gradient descent explained: put the gradient to work training a full model.
  2. Feature scaling: the data step that makes the valley round.
  3. Go back over partial derivatives explained if the formulas felt fast.