From Slopes to Gradients: Derivatives, the Chain Rule and Jacobians
See a derivative as a slope you can estimate by nudging, compute the partial derivatives of a loss with the chain rule, vectorise the gradient of logistic regression, and get an intuition for Jacobians and Hessians.
Contentsand lesson path
On this page
- Why it matters
- A derivative is a slope you can estimate
- Partial derivatives and the gradient
- The chain rule on a real loss
- Jacobians and Hessians: the intuition
- Check your understanding
- Apply it
- Review prompt
Lessons of Linear Algebra & Calculus for ML
- Data as Arrays: Vectors, Matrices and Shapes Concept · 20 min
- Similarity and Structure: Distances, Eigenvectors and the SVD Concept · 30 min
- From Slopes to Gradients: Derivatives, the Chain Rule and Jacobians Concept · 25 min
- Worked Example: Checking a Gradient Numerically Worked example · 15 min
- Lab: Fit a Linear Model with Hand-Written Gradient Descent Lab · 30 min
- Check: Shapes, Gradients and Step Sizes Knowledge check · 10 questions
What you will learn
- Compute partial derivatives of a composed function with the chain rule and verify them with a numerical gradient check.
01. Why it matters
Training a model means changing its parameters so that a loss gets smaller. To know which way to change each parameter, you need the slope of the loss with respect to that parameter. Collect those slopes and you have the gradient, the quantity every gradient-descent optimiser uses, from the hand-written loop in the lab of this skill to the optimisers in PyTorch.
Libraries compute gradients for you with automatic differentiation, so why learn to do it by hand? Because you will write custom losses, read papers that state gradients, and debug training runs whose loss does not fall. All three need you to apply the chain rule to a function built from simple steps, and to check your result numerically. This lesson covers the first part; the next lesson, a worked example, covers the check in depth.
The examples use plain Python and NumPy 2.5. You need no calculus beyond the idea that x² has slope 2x; everything else is built here.
02. A derivative is a slope you can estimate
The derivative of a function f at a point x tells you how fast f changes when x changes a little. Take a small step h, measure the rise f(x + h) − f(x), and divide by the run h. As h shrinks, this ratio approaches the derivative, written f′(x) or df/dx. For f(x) = x² the exact derivative is 2x, so at x = 3 the slope is 6: near that point, increasing x by 0.001 increases f by about 0.006.
def f(x):
return x ** 2
x = 3.0
for h in [0.1, 0.01, 0.001]:
slope = (f(x + h) - f(x)) / h # rise over run across a small step h
print(f"h = {h:<6} slope ≈ {slope:.4f}")
print("exact derivative 2x =", 2 * x)h = 0.1 slope ≈ 6.1000
h = 0.01 slope ≈ 6.0100
h = 0.001 slope ≈ 6.0010
exact derivative 2x = 6.0The estimate is off by exactly h each time, because (x + h)² − x² = 2xh + h². This one-sided ratio is called the forward difference. Its error shrinks in proportion to h, which is why the worked example in the next lesson uses a more accurate version. The sign of the derivative matters as much as its size: a positive slope means "increase x and f goes up", a negative slope means "increase x and f goes down".
03. Partial derivatives and the gradient
A loss usually depends on several parameters. A partial derivative is the slope with respect to one of them while all the others are held fixed; it is written with a curly d, as in ∂L/∂w. The gradient is the vector of all partial derivatives, written ∇L. It points in the direction in which the loss rises fastest, so gradient descent moves the parameters a small step in the opposite direction.
Take one training example with feature x = 3 and target y = 10, and a model that predicts w·x + b. The squared-error loss is L(w, b) = (w·x + b − y)². Call the residual r = w·x + b − y, the prediction minus the target. The loss is r², whose derivative with respect to r is 2r. The residual changes by x when w changes by 1, and by 1 when b changes by 1. Multiplying these slopes gives ∂L/∂w = 2r·x and ∂L/∂b = 2r. That multiplication is the chain rule, explained properly in the next section. At w = 2 and b = 1 the prediction is 7, the residual is −3, and the gradient is (−18, −6).
def loss(w, b, x=3.0, y=10.0):
return (w * x + b - y) ** 2
w, b, x, y = 2.0, 1.0, 3.0, 10.0
r = w * x + b - y # residual: prediction minus target
dL_dw = 2 * r * x # chain rule: d(r²)/dr = 2r, dr/dw = x
dL_db = 2 * r # dr/db = 1
print("loss:", loss(w, b), "residual:", r)
print("gradient (dL/dw, dL/db):", (dL_dw, dL_db))
# Nudge each parameter on its own and watch the loss
h = 1e-4
print("loss change for w + h:", round((loss(w + h, b) - loss(w, b)) / h, 3))
print("loss change for b + h:", round((loss(w, b + h) - loss(w, b)) / h, 3))
# One small step against the gradient lowers the loss
step = 0.01
print("after a step:", round(loss(w - step * dL_dw, b - step * dL_db), 4))loss: 9.0 residual: -3.0
gradient (dL/dw, dL/db): (-18.0, -6.0)
loss change for w + h: -17.999
loss change for b + h: -6.0
after a step: 5.76Both partial derivatives are negative: the model predicts too low, so raising w or b lowers the loss. The slope for w is three times larger than for b because w is multiplied by x = 3, so a change in w moves the prediction three times as much. One step of size 0.01 against the gradient drops the loss from 9 to 5.76. The nudges agree with the formulas; the small gap for w (−17.999 instead of −18) is the forward-difference error you saw above.
04. The chain rule on a real loss
Most losses are compositions: the output of one simple function is the input of the next. The chain rule says that the slope of a composition is the product of the slopes of its steps. If y = f(g(x)), then dy/dx = f′(g(x)) · g′(x). A practical way to use it is to write the forward computation as named steps, find the derivative of each step on its own, and multiply them from the loss backwards. This is exactly what backpropagation does in a neural network.
Logistic regression is a good example. For one example with features x and label y (0 or 1) it computes three steps:
- a score z = w·x + b;
- a probability p = σ(z), where the sigmoid σ(z) = 1 / (1 + e^(−z)) squeezes any score into the range 0 to 1;
- the log-loss L = −[y·log p + (1 − y)·log(1 − p)], which is small when p is close to the true label.
Now take the slope of each step. Step 3 gives dL/dp = −y/p + (1 − y)/(1 − p). Step 2 has the convenient derivative dσ/dz = σ(z)(1 − σ(z)) = p(1 − p). Step 1 gives ∂z/∂w = x. Multiply the first two and simplify: dL/dz = −y(1 − p) + (1 − y)p = p − y. So the full chain is ∂L/∂w = (p − y)·x and ∂L/∂b = p − y. For a label y = 0 and p = 0.7, the gradient with respect to w is 0.7·x: the model is too confident in the wrong class, and the gradient pushes the score down.
For a dataset, the loss is the mean over n examples, so the gradient is the mean of the per-example gradients. In matrix form that is Xᵀ(p − y) / n: the (d, n) transpose times the (n,) error vector gives one number per feature.
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(6, 2)) # 6 examples, 2 features
y = np.array([0, 1, 1, 0, 1, 0]) # binary labels
w = np.array([0.5, -0.3])
b = 0.1
def mean_log_loss(w, b):
p = 1 / (1 + np.exp(-(X @ w + b)))
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
# Forward pass, one named step at a time
z = X @ w + b # (6,) scores
p = 1 / (1 + np.exp(-z)) # (6,) predicted P(y = 1)
# Backward pass with the chain rule: dL/dz = p - y for each example
dz = (p - y) / len(y) # divide by n because the loss is a mean
grad_w = X.T @ dz # (2, 6) @ (6,) -> (2,)
grad_b = dz.sum()
print("loss:", round(mean_log_loss(w, b), 4))
print("grad_w:", grad_w.round(4), "grad_b:", round(grad_b, 4))
h = 1e-6 # compare with a nudge of the first weight
nudged = (mean_log_loss(w + [h, 0], b) - mean_log_loss(w, b)) / h
print("nudge estimate for grad_w[0]:", round(nudged, 4))loss: 0.5726
grad_w: [-0.1118 0.1765] grad_b: 0.0365
nudge estimate for grad_w[0]: -0.1118The hand-derived gradient and the nudge agree to four decimals. Notice how much simpler the code is than the derivation: once you know dL/dz = p − y, the whole backward pass is two lines. That simplicity is not luck. The log-loss and the sigmoid fit together so that their slopes cancel, which is one reason this pair is the standard choice for binary classification.
05. Jacobians and Hessians: the intuition
So far each function returned one number. A layer of a neural network returns a vector: it maps n inputs to m outputs. Its Jacobian is the m × n matrix of all partial derivatives, where row i, column j holds ∂output_i/∂input_j. Row i tells you how output i responds to each input; column j tells you how all outputs respond to input j. For a linear layer z = W x, the Jacobian with respect to x is simply W. For vector functions, the chain rule becomes a product of Jacobians, which is why backpropagation is built from matrix products.
The example computes the Jacobian of z = tanh(W x) by the chain rule (the slope of tanh is 1 − tanh², applied to each output) and checks it by nudging one input at a time.
import numpy as np
W = np.array([[1.0, -2.0, 0.5, 0.0],
[0.0, 1.0, 1.0, 3.0],
[2.0, 0.0, -1.0, 1.0]]) # a layer from 4 inputs to 3 outputs
x = np.array([0.5, 0.2, -0.4, 0.1])
def layer(x):
return np.tanh(W @ x) # z = W x, then tanh element-wise
# Analytic Jacobian by the chain rule: diag(1 - tanh(z)²) @ W
z = W @ x
J = (1 - np.tanh(z) ** 2)[:, None] * W # scale row i of W by the tanh slope
# Numerical Jacobian: nudge one input at a time, one column per input
h = 1e-6
J_num = np.column_stack([(layer(x + h * e) - layer(x)) / h for e in np.eye(4)])
print("Jacobian shape:", J.shape)
print(J.round(3))
print("max difference from nudging:", f"{np.abs(J - J_num).max():.1e}")Jacobian shape: (3, 4)
[[ 0.99 -1.98 0.495 0. ]
[ 0. 0.99 0.99 2.97 ]
[ 0.361 0. -0.181 0.181]]
max difference from nudging: 8.9e-07The Jacobian has one row per output and one column per input, so (3, 4) here. The third output is already in the flatter part of tanh, so its row is scaled down most.
The Hessian is the matrix of second derivatives of a scalar loss: entry (i, j) is how the slope for parameter i changes when parameter j changes. It describes curvature, the bend of the loss surface. Large curvature in one direction means the slope changes quickly there, so a big step overshoots; small curvature means you can take long steps. You rarely compute a Hessian in practice, because for d parameters it has d² entries. But the idea explains a lot. For mean squared error in linear regression the Hessian is (2/n)·XᵀX, so it depends on the scales of the features. In the lab you will see what that means for the learning rate.
06. Check your understanding
07. Apply it
You will need a correct gradient for the practice project of this skill. Prepare it now.
- Write the mean squared error of linear regression for a whole dataset, L(w, b) = mean((X w + b − y)²), as named steps: predictions, residuals, squares, mean.
- Derive ∂L/∂w and ∂L/∂b with the chain rule and write them in matrix form. Check the shapes: the gradient for w must have one entry per feature.
- Implement it in NumPy for
load_diabetesand compare one entry against a nudge of that weight, as inlogistic_grad.py. Keep the function: the lab uses it.
08. Review prompt
Without looking back, explain: what a partial derivative measures and why gradient descent steps against the gradient; how the chain rule turns the three steps of logistic regression into ∂L/∂w = (p − y)·x; why the gradient of a mean loss over a dataset is Xᵀ(p − y) / n; and what the rows and columns of a Jacobian stand for.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.