◆ AI All-in-One

Level 3 In-Depth AI · Math Foundations

Partial Derivatives and Gradients

When a function has many inputs, such as a loss that depends on millions of weights, you take its slope one input at a time. Those partial derivatives, collected into a vector, form the gradient — an arrow pointing straight uphill that training follows downhill.

Level
●●●●● Easy
Reading
12 min
To learn it well
50 minutes to read, an hour to practise
↗ Plan a path here

Read first

Derivatives and SlopesVectors

This leads to

Gradient Descent
The full path from zero — 2 concepts before this one
  1. Derivatives and Slopes
  2. Vectors
  3. Partial Derivatives and Gradients

Read them roughly in this order. See it on the concept map →

Why it matters

The Derivatives and Slopes chapter dealt with functions of one input: nudge xx, see how f(x)f(x) changes. But a machine-learning loss depends on every parameter of the model at once. A Linear Regression model of house prices might have 10 weights. A small image classifier has a few million. GPT-3 has 175 billion. The loss is a single number computed from all of them.

To improve the model you need to know, for each parameter separately, which way to move it and how much it matters. The tool for that is the partial derivative: the slope with respect to one input while all the others are held still. Collect all those slopes into one vector and you have the gradient, written ∇L\nabla L. The gradient is what Gradient Descent follows, what Backpropagation computes, and what PyTorch stores in every parameter's .grad.

This chapter shows what partial derivatives and gradients are, why the gradient points uphill, and how to compute one by hand, numerically and with PyTorch.

The intuition

Think of a landscape. Your position is given by two numbers, east–west (xx) and north–south (yy), and the ground height f(x,y)f(x, y) depends on both. A hiking map shows this with contour lines: curves joining points of equal height. Where the lines are close together, the ground is steep.

Now stand at one spot and ask: "How steep is it if I walk due east?" That is the partial derivative with respect to xx. "How steep if I walk due north?" That is the partial derivative with respect to yy. Each one is an ordinary one-dimensional slope, measured along a single direction while you keep the other coordinate fixed.

Those two numbers, put together as an arrow [east slope,north slope][\text{east slope}, \text{north slope}], turn out to point in the direction of steepest climb. That arrow is the gradient. Turn around and walk the opposite way, and you are going downhill as fast as possible. That is all gradient descent does: in a fog, with a loss landscape instead of a hill, and with millions of directions instead of two.

Key idea A partial derivative is the slope along one input with all the others frozen. The gradient collects every partial derivative into a vector. It points in the direction of steepest increase, and its length says how steep that is. Training moves the parameters against it.

How it works

Functions of several inputs

Take a simple bowl-shaped function of two inputs:

f(x,y)=x2+3y2f(x, y) = x^2 + 3y^2

At the point (2,1)(2, 1) its value is 4+3=74 + 3 = 7. The lowest point is (0,0)(0, 0), where f=0f = 0. Drawn as a contour map, the contour lines are ellipses, squeezed in the yy direction because yy is multiplied by 3 and the bowl rises faster that way.

Partial derivatives: freeze everything else

To get the partial derivative with respect to xx, pretend yy is a fixed number and differentiate as usual. The term 3y23y^2 then behaves like a constant, and a constant's slope is 0:

∂f∂x=2x\frac{\partial f}{\partial x} = 2x

The curly ∂\partial ("partial", or just "d") signals that ff has other inputs that were held fixed. Likewise, freezing xx:

∂f∂y=6y\frac{\partial f}{\partial y} = 6y

At the point (2,1)(2, 1): ∂f∂x=4\frac{\partial f}{\partial x} = 4 and ∂f∂y=6\frac{\partial f}{\partial y} = 6.

Geometrically, freezing y=1y = 1 means slicing through the landscape along the line y=1y = 1. The slice is the ordinary curve x2+3x^2 + 3, and its slope at x=2x = 2 is 4. Freezing x=2x = 2 gives the curve 4+3y24 + 3y^2, with slope 6 at y=1y = 1.

Left: a contour map of f(x, y) = x² + 3y², with two dashed slices through the point (2, 1), one holding y = 1 and one holding x = 2. Right: each slice is an ordinary curve. The slope of the first at x = 2 is ∂f/∂x = 4, and the slope of the second at y = 1 is ∂f/∂y = 6. Together they make the gradient [4, 6].

You can check with nudges. f(2.001,1)=7.004001f(2.001, 1) = 7.004001, a change of 0.004 for a nudge of 0.001: slope 4. ✓ f(2,1.001)=7.006003f(2, 1.001) = 7.006003: slope 6. ✓

The gradient

The gradient stacks all the partial derivatives into one vector:

∇f(x,y)=[∂f∂x,  ∂f∂y]=[2x,  6y]\nabla f(x, y) = \left[ \frac{\partial f}{\partial x}, \; \frac{\partial f}{\partial y} \right] = [2x, \; 6y]

∇\nabla is called "nabla" or "del". At (2,1)(2, 1), ∇f=[4,6]\nabla f = [4, 6]. With nn inputs, the gradient has nn components. For a loss with a billion parameters, the gradient is a vector of a billion numbers, one slope per parameter, and it has exactly the same shape as the parameters.

Three facts make the gradient so useful:

  1. It points in the direction of steepest increase. Of all the directions you could step in, stepping along ∇f\nabla f raises ff fastest.
  2. Its length is the steepness in that direction. At (2,1)(2, 1), ∥∇f∥=42+62≈7.21\lVert \nabla f \rVert = \sqrt{4^2 + 6^2} \approx 7.21.
  3. It is perpendicular to the contour lines. Walking along a contour line keeps your height the same, so the steepest direction must cut straight across them.

At a minimum (or maximum, or saddle point) the gradient is the zero vector: the ground is flat in every direction.

Gradient arrows drawn at many points of the same contour map. Each red arrow points straight across the contour lines, away from the minimum, and is longer where the bowl is steeper. At (2, 1) the gradient [4, 6] points uphill and its negative points steepest downhill. Note that −∇f does not aim straight at the minimum.

Why the gradient points uphill: directional derivatives

Suppose you walk from a point in some direction given by a unit vector u\mathbf{u}. How steep is the ground in that direction? The answer, the directional derivative, is a dot product:

slope in direction u=∇f⋅u\text{slope in direction } \mathbf{u} = \nabla f \cdot \mathbf{u}

Intuitively: moving a little in direction u=[u1,u2]\mathbf{u} = [u_1, u_2] changes xx by a fraction u1u_1 and yy by a fraction u2u_2 of the step, and each change contributes its own partial slope. So the total slope is ∂f∂xu1+∂f∂yu2\frac{\partial f}{\partial x} u_1 + \frac{\partial f}{\partial y} u_2.

Walking north-east from (2,1)(2, 1), with u=[0.707,0.707]\mathbf{u} = [0.707, 0.707], the slope is 4×0.707+6×0.707≈7.074 \times 0.707 + 6 \times 0.707 \approx 7.07.

Now recall that a dot product equals ∥∇f∥ ∥u∥cos⁡θ\lVert \nabla f \rVert \, \lVert \mathbf{u} \rVert \cos\theta. With u\mathbf{u} of length 1, this is largest when cos⁡θ=1\cos\theta = 1, that is, when u\mathbf{u} points the same way as ∇f\nabla f. So the gradient is the steepest uphill direction, and the slope that way is exactly ∥∇f∥≈7.21\lVert \nabla f \rVert \approx 7.21, a little more than the 7.07 going north-east. Stepping the opposite way, along −∇f-\nabla f, gives the steepest downhill slope, −7.21-7.21. Stepping at right angles to the gradient gives slope 0: you're walking along a contour line.

This explains the update rule of Gradient Descent:

θ←θ−η ∇L(θ)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta \, \nabla L(\boldsymbol{\theta})

From (2,1)(2, 1) with η=0.05\eta = 0.05: the new point is (2,1)−0.05×[4,6]=(1.8,0.7)(2, 1) - 0.05 \times [4, 6] = (1.8, 0.7), and ff drops from 7 to 3.24+1.47=4.713.24 + 1.47 = 4.71.

Notice in the picture that −∇f-\nabla f does not aim straight at the minimum at (0,0)(0, 0). It points across the contours, which in a stretched bowl means it overshoots in the steep direction and undershoots in the shallow one. That is why plain gradient descent zig-zags in long, narrow valleys, and why scaling your input features and using optimisers such as Adam helps.

The gradient of a real loss

Here is the gradient you need for fitting a line y^=wx+b\hat{y} = wx + b to NN data points with the mean squared error loss:

L(w,b)=1N∑i=1N(wxi+b−yi)2L(w, b) = \frac{1}{N} \sum_{i=1}^{N} (w x_i + b - y_i)^2

Treat bb as fixed and differentiate with respect to ww using the The Chain Rule: the outer square gives 2(…)2(\ldots) and the inner slope with respect to ww is xix_i. Then treat ww as fixed for bb, where the inner slope is 1:

∂L∂w=2N∑i=1N(wxi+b−yi) xi,∂L∂b=2N∑i=1N(wxi+b−yi)\frac{\partial L}{\partial w} = \frac{2}{N} \sum_{i=1}^{N} (w x_i + b - y_i)\, x_i, \qquad \frac{\partial L}{\partial b} = \frac{2}{N} \sum_{i=1}^{N} (w x_i + b - y_i)

These are exactly the dw and db lines in the from-scratch code of the Gradient Descent chapter. Each term is "error times how much this parameter influenced the prediction". Large errors on examples where xix_i is large push ww hard. That pattern, error times input, appears again in Logistic Regression and at every layer of Backpropagation.

Jacobians: when the output is a vector too

So far the function produced one number. A neural network layer takes a vector in and gives a vector out. Its slopes form a table: how each output changes with each input. That table is the Jacobian matrix, named after Carl Jacobi. Row ii holds the gradient of output ii.

For g(x,y)=[ xy,  x2+y ]\mathbf{g}(x, y) = [\,xy, \; x^2 + y\,]:

J=[∂g1∂x∂g1∂y∂g2∂x∂g2∂y]=[yx2x1]=[1241] at (2,1)\mathbf{J} = \begin{bmatrix} \frac{\partial g_1}{\partial x} & \frac{\partial g_1}{\partial y} \\[4pt] \frac{\partial g_2}{\partial x} & \frac{\partial g_2}{\partial y} \end{bmatrix} = \begin{bmatrix} y & x \\ 2x & 1 \end{bmatrix} = \begin{bmatrix} 1 & 2 \\ 4 & 1 \end{bmatrix} \text{ at } (2, 1)

The chain rule for vector functions says: multiply the Jacobians of the steps, in order. For a linear layer y=Wx\mathbf{y} = \mathbf{W}\mathbf{x}, the Jacobian is simply W\mathbf{W} itself. Backpropagation is a long product of Jacobians, computed from the loss backwards so that every product is a vector times a matrix rather than a matrix times a matrix. That ordering is what makes it cheap. You will rarely compute a Jacobian by hand, but the word appears often in papers and documentation.

In code

import numpy as np

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

def grad_f(p):                       # worked out by hand
    x, y = p
    return np.array([2 * x, 6 * y])

def numerical_gradient(f, p, h=1e-5):
    g = np.zeros_like(p)
    for i in range(len(p)):          # nudge one input at a time, others frozen
        step = np.zeros_like(p)
        step[i] = h
        g[i] = (f(p + step) - f(p - step)) / (2 * h)
    return g

p = np.array([2.0, 1.0])
print(grad_f(p), numerical_gradient(f, p))   # [4. 6.] [4. 6.]
print(np.linalg.norm(grad_f(p)))             # 7.211102550927978  steepest slope

# Directional derivative: slope when walking north-east
u = np.array([1.0, 1.0]) / np.sqrt(2)
print(grad_f(p) @ u)                         # 7.071067811865475

# One small step against the gradient lowers f
print(f(p), f(p - 0.05 * grad_f(p)))         # 7.0 4.71

The numerical_gradient loop makes the meaning of "partial" concrete: it changes one input at a time. It is also why this method is useless for training. It needs two loss evaluations per parameter, while backpropagation gets all of them in one backward pass. In PyTorch:

import torch

p = torch.tensor([2.0, 1.0], requires_grad=True)
f = p[0] ** 2 + 3 * p[1] ** 2
f.backward()
print(p.grad)                                # tensor([4., 6.])  the whole gradient

# Jacobian of a function with 2 inputs and 2 outputs
g = lambda v: torch.stack([v[0] * v[1], v[0] ** 2 + v[1]])
print(torch.autograd.functional.jacobian(g, torch.tensor([2.0, 1.0])))
# tensor([[1., 2.],
#         [4., 1.]])

Common pitfalls

  • Forgetting to freeze. When taking ∂∂x\frac{\partial}{\partial x} of 3xy3xy, the answer is 3y3y, not 0 and not 3xy3xy. Terms containing only other variables vanish, and terms mixing them keep the other variables as constants.
  • Thinking the gradient points at the minimum. It points steepest uphill locally. In stretched valleys, −∇L-\nabla L points mostly across the valley rather than along it. Rescaling features and momentum-based Optimizers: SGD, Momentum and Adam fix much of this.
  • Mismatched feature scales. If one input is measured in thousands and another in fractions, the loss landscape becomes a long thin ravine, and the gradient is dominated by one parameter. Standardise your inputs.
  • Shape confusion. The gradient of a loss with respect to a weight matrix of shape (512, 768) is also a (512, 768) matrix. If your hand-written gradient has a different shape, it is wrong.
  • Calling .backward() on a non-scalar. In PyTorch, backward() with no arguments only works when the output is a single number, like a loss. For a vector output you want a Jacobian, or first reduce it to a scalar with .sum() or .mean().

Watch out A gradient of zero does not prove you found the best parameters. In many dimensions most flat points are saddle points, uphill in some directions and downhill in others, and gradient descent can stall near them for a long time. Check the loss on held-out data, not just the gradient size.

Where it leads

A bit of history

Partial derivatives were developed in the 18th century by Leonhard Euler, Alexis Clairaut and Jean le Rond d'Alembert, who needed them for problems in physics such as vibrating strings and fluids. The curly ∂\partial symbol was used by Adrien-Marie Legendre in 1786 and made standard by Carl Gustav Jacobi in the 1840s, whose name the Jacobian matrix also carries. The gradient as a vector, and the nabla symbol ∇\nabla, came from William Rowan Hamilton and from Josiah Willard Gibbs and Oliver Heaviside's vector analysis later in the 19th century. In 1847 Augustin-Louis Cauchy proposed the method of steepest descent, stepping against the gradient, which machine learning adopted a century later.

Try it

  1. By hand, find both partial derivatives of f(x,y)=3x2y+y3f(x, y) = 3x^2 y + y^3 and evaluate the gradient at (1,2)(1, 2). Check with numerical_gradient.
  2. For f(x,y)=x2+3y2f(x, y) = x^2 + 3y^2, start at (2,1)(2, 1) and take 20 gradient-descent steps with η=0.1\eta = 0.1. Print the path. Does it head straight for (0,0)(0, 0)? Try η=0.3\eta = 0.3 and η=0.34\eta = 0.34 and explain what changes.
  3. Using the formulas for ∂L∂w\frac{\partial L}{\partial w} and ∂L∂b\frac{\partial L}{\partial b}, compute the gradient by hand for the three points (x,y)=(0,1),(1,3),(2,5)(x, y) = (0, 1), (1, 3), (2, 5) at w=0w = 0, b=0b = 0. Which way should each parameter move?

Hint for 2: the yy-direction has slope factor 6, so steps of η×6>2\eta \times 6 > 2 overshoot back and forth across the valley. That happens once η>1/3\eta > 1/3.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. For f(x, y) = x² + 4xy, what is ∂f/∂x?

  2. At some point the gradient of the loss is [4, −2]. Which direction does a gradient-descent step move the two parameters?

  3. On a stretched, bowl-shaped loss, plain gradient descent zig-zags across the valley. Why?

  4. A weight matrix has shape (512, 768). What shape is the gradient of the loss with respect to it?

  5. The gradient at a point is [3, 4]. What is the steepest possible uphill slope there, and in which direction is the slope zero?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Multivariable Calculus

Khan Academy · Intermediate · Free

Partial derivatives, gradients, directional derivatives and Jacobians, with many visualisations (several taught by Grant Sanderson of 3Blue1Brown).

Video

Essence of Calculus

3Blue1Brown · Beginner · Free

Derivatives, the chain rule and integrals, explained visually in short videos.

Article

The Matrix Calculus You Need For Deep Learning

Terence Parr & Jeremy Howard · 2018 · Intermediate · Free

Builds from single-variable derivatives to gradients, Jacobians and the vector chain rule, exactly as needed to understand backpropagation.

Book

Mathematics for Machine Learning

Deisenroth, Faisal & Ong · 2020 · Intermediate · Free

The linear algebra, calculus, probability and optimisation that ML uses, in one free book.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/partial-derivatives-and-gradients.md