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
- Builds on
- 2 concepts →
- Quiz
- 5 questions ↓
This leads to
Gradient DescentThe full path from zero — 2 concepts before this one
- Derivatives and Slopes
- Vectors
- 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 , see how 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 . 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 () and north–south (), and the ground height 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 . "How steep if I walk due north?" That is the partial derivative with respect to . 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 , 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:
At the point its value is . The lowest point is , where . Drawn as a contour map, the contour lines are ellipses, squeezed in the direction because is multiplied by 3 and the bowl rises faster that way.
Partial derivatives: freeze everything else
To get the partial derivative with respect to , pretend is a fixed number and differentiate as usual. The term then behaves like a constant, and a constant's slope is 0:
The curly ("partial", or just "d") signals that has other inputs that were held fixed. Likewise, freezing :
At the point : and .
Geometrically, freezing means slicing through the landscape along the line . The slice is the ordinary curve , and its slope at is 4. Freezing gives the curve , with slope 6 at .
You can check with nudges. , a change of 0.004 for a nudge of 0.001: slope 4. ✓ : slope 6. ✓
The gradient
The gradient stacks all the partial derivatives into one vector:
is called "nabla" or "del". At , . With inputs, the gradient has 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:
- It points in the direction of steepest increase. Of all the directions you could step in, stepping along raises fastest.
- Its length is the steepness in that direction. At , .
- 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.
Why the gradient points uphill: directional derivatives
Suppose you walk from a point in some direction given by a unit vector . How steep is the ground in that direction? The answer, the directional derivative, is a dot product:
Intuitively: moving a little in direction changes by a fraction and by a fraction of the step, and each change contributes its own partial slope. So the total slope is .
Walking north-east from , with , the slope is .
Now recall that a dot product equals . With of length 1, this is largest when , that is, when points the same way as . So the gradient is the steepest uphill direction, and the slope that way is exactly , a little more than the 7.07 going north-east. Stepping the opposite way, along , gives the steepest downhill slope, . 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:
From with : the new point is , and drops from 7 to .
Notice in the picture that does not aim straight at the minimum at . 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 to data points with the mean squared error loss:
Treat as fixed and differentiate with respect to using the The Chain Rule: the outer square gives and the inner slope with respect to is . Then treat as fixed for , where the inner slope is 1:
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 is large push 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 holds the gradient of output .
For :
The chain rule for vector functions says: multiply the Jacobians of the steps, in order. For a linear layer , the Jacobian is simply 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 of , the answer is , not 0 and not . 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, 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
- Gradient Descent: the update rule that walks against the gradient, with learning rates, mini-batches and convergence.
- Backpropagation: computing the gradient of a neural network's loss with respect to every weight in one backward pass, by chaining Jacobians.
- Optimizers: SGD, Momentum and Adam: Momentum and Adam reshape the raw gradient to move faster through ravines and plateaus.
- Linear Regression and Logistic Regression: the first models whose gradients you derive in full.
- Maximum Likelihood Estimation: setting the gradient of the log-likelihood to zero recovers many classic formulas.
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 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 , 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
- By hand, find both partial derivatives of and evaluate the gradient at . Check with
numerical_gradient.- For , start at and take 20 gradient-descent steps with . Print the path. Does it head straight for ? Try and and explain what changes.
- Using the formulas for and , compute the gradient by hand for the three points at , . Which way should each parameter move?
Hint for 2: the -direction has slope factor 6, so steps of overshoot back and forth across the valley. That happens once .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Multivariable Calculus
Partial derivatives, gradients, directional derivatives and Jacobians, with many visualisations (several taught by Grant Sanderson of 3Blue1Brown).
Essence of Calculus
Derivatives, the chain rule and integrals, explained visually in short videos.
The Matrix Calculus You Need For Deep Learning
Builds from single-variable derivatives to gradients, Jacobians and the vector chain rule, exactly as needed to understand backpropagation.
Mathematics for Machine Learning
The linear algebra, calculus, probability and optimisation that ML uses, in one free book.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Machine Learning Crash Course
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