All courses

Gradients and Jacobians

Compute the gradient of a scalar function of many variables and the Jacobian of a vector function. Explain the gradient as the direction of steepest increase.

Builds on: What training does

▶ Watch this lesson Start the whole course

What the animation says

Wiggle one input

Training shrinks one number, the loss, which depends on billions of weights. For every weight, we need to know how a tiny nudge changes it. Start small: x squared times y, plus three y. At two, one it equals seven. Freeze y at one and wiggle only x. What's left is x squared plus three. Its slope is two x, so four. One input wiggled, the rest frozen: that slope is a partial derivative. Now freeze x at two and wiggle only y. What's the slope?

Stack them: the gradient

Seven. With x frozen at two, f becomes four y plus three y, which is seven y. Stack the two partials and you get the gradient: four, seven. It has one entry per input, so it has the same shape as the input. It predicts small changes. Nudge x by a hundredth, and the prediction is seven plus four hundredths: seven point zero four. The real value is seven point zero four zero one. Very close.

Which way is steepest?

Which direction raises f fastest? Point a unit arrow at some angle to the gradient. The rate along that arrow is the gradient's length times the cosine of the angle. When the arrow lines up with the gradient, the cosine is one. That's the steepest climb: root sixty-five, about eight. At a right angle the rate is zero, because you're walking along a level line. Training wants the loss to fall. Drag the arrow to where f drops fastest.

Many outputs: the Jacobian

Some functions output several numbers. Here g gives x times y, and x plus y squared. Each output gets its own gradient. At two, three, the first output's gradient is three, two. The second output's gradient is one, six. Stack those gradients as rows. That's the Jacobian: each row is an output, each column is an input. Code can build it by nudging only x, up and down a little. Which part does that fill?

Code fills it column by column

A column. Nudging x moves both outputs, so you learn both rates for x at once. This line nudges input j by a tiny epsilon, both up and down. This line divides the change by two epsilon and writes it into column j. Two passes give two columns: three, one, then two, six. That matches the hand result. Remember: the gradient points uphill, and its length is the steepest rate. To lower a loss, step against it.

One object for 'which nudge lowers the loss'?

The loss is one number that depends on billions of weights. Training needs to know, for **every weight at once**, how a tiny nudge would change that number, and which combined nudge changes it fastest. What exactly is that object, how do you compute it, and why does it point in the best direction? Later you will also need the same idea for functions that output a whole vector, not just one number.

Wiggle one input, then stack

Hold all inputs fixed except one and ask how fast the output changes as you wiggle it. That rate is a **partial derivative**. List one per input and you get the **gradient**, a vector with the same shape as the input. On a hillside, the gradient points straight uphill and its length is the steepness. If the function outputs several numbers, each output gets its own gradient. Stack them as rows to get the **Jacobian**.

Gradient, steepest ascent, Jacobian

For $f:\mathbb R^n\to\mathbb R$: $\nabla f = (\partial f/\partial x_1,\dots,\partial f/\partial x_n)$, and $f(x+\delta)\approx f(x)+\nabla f\cdot\delta$ for small $\delta$. In a unit direction $u$ the rate of change is $\nabla f\cdot u=\|\nabla f\|\cos\alpha$, where $\alpha$ is the angle between $u$ and $\nabla f$. This is largest when $u$ points along $\nabla f$ ($\alpha=0$), with rate $\|\nabla f\|$. It is zero for $u\perp\nabla f$ (perpendicular). For $f:\mathbb R^n\to\mathbb R^m$: $J\in\mathbb R^{m\times n}$, $J_{ij}=\partial f_i/\partial x_j$ (row = output, column = input).

Gradient of x²y + 3y at (2, 1)

$f(x,y)=x^2y+3y$, so $f(2,1)=7$. - $\partial f/\partial x=2xy=4$ - $\partial f/\partial y=x^2+3=7$ So $\nabla f=(4,7)$. The steepest uphill direction is $(4,7)/\sqrt{65}$, with slope $\sqrt{65}\approx 8.06$. Check with $\delta=(0.01,0)$. The prediction is $7+4(0.01)=7.04$. The actual value is $f(2.01,1)=4.0401+3=7.0401$. ✓

Jacobian by finite differences

Take $g(x,y)=(xy,\;x+y^2)$. By hand, $J=\begin{bmatrix}y&x\\1&2y\end{bmatrix}$, which is $\begin{bmatrix}3&2\\1&6\end{bmatrix}$ at $(2,3)$. The code builds the Jacobian numerically. It nudges one input at a time, and each nudge fills one **column**.
import numpy as np
def g(v):
    x, y = v
    return np.array([x*y, x + y**2])
v = np.array([2.0, 3.0]); eps = 1e-6
J = np.zeros((2, 2))
for j in range(2):
    e = np.zeros(2); e[j] = eps
    J[:, j] = (g(v + e) - g(v - e)) / (2 * eps)
print(J.round(4))  # [[3. 2.] [1. 6.]]  rows=outputs

Remember

The gradient lists every partial derivative of a scalar function. It points in the direction of steepest increase, its length is that steepest rate, and $f(x+\delta)\approx f(x)+\nabla f\cdot\delta$. The Jacobian stacks the gradients of each output as rows, $J_{ij}=\partial f_i/\partial x_j$. To lower a loss, step against the gradient.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.