Calculus for Machine Learning
Training a neural network is multivariable calculus applied at scale: a loss function of millions of parameters, its gradient from the chain rule, and a step downhill. This lesson derives the gradients that appear in almost every model (mean squared error, logistic loss, and the softmax with cross-entropy), computes the softmax Jacobian, and explains Jacobian-vector and vector-Jacobian products, the two primitives that every automatic-differentiation library is built on.
Background: Partial Derivatives, The Chain Rule and Directional Derivatives and the Gradient Vector. The survey course has gentler versions in Gradient descent, Backpropagation and Automatic differentiation.
Gradients of common losses
For a model with parameters , a loss measures how wrong the predictions are. Gradient descent updates , so we need . With data points, the input matrix, the targets and the weights:
| Loss | Formula | Gradient with respect to |
|---|---|---|
| Mean squared error (linear model) | ||
| Binary cross-entropy (logistic model, ) | ||
| Softmax + cross-entropy (one example, logits ) | , |
The second row rests on a pleasant identity of the sigmoid :
Then the chain rule through contributes the factor . The gradient "prediction minus target, times input" is the same shape as for least squares, which is no accident: both losses are negative log-likelihoods of exponential-family models.
import numpy as np
rng = np.random.default_rng(7)
X = np.column_stack([np.ones(50), rng.normal(size=(50, 2))])
y = (X @ np.array([0.5, 2.0, -1.0]) + rng.normal(scale=0.5, size=50) > 0).astype(float)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
def loss(w):
p = sigmoid(X @ w)
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
def grad(w):
return X.T @ (sigmoid(X @ w) - y) / len(y)
w = np.array([0.1, -0.2, 0.3])
h = 1e-6
numeric = np.array([(loss(w + h*e) - loss(w - h*e)) / (2*h) for e in np.eye(3)])
print("analytic :", np.round(grad(w), 6))
print("numeric :", np.round(numeric, 6))
for step in range(200):
w -= 1.0 * grad(w)
print("after 200 steps: w =", np.round(w, 3), " loss =", round(float(loss(w)), 4))analytic : [ 0.006707 -0.334977 0.137815]
numeric : [ 0.006707 -0.334977 0.137815]
after 200 steps: w = [ 1.334 5.478 -2.246] loss = 0.2209
Softmax and cross-entropy
A classifier with classes outputs logits , turns them into probabilities , and for the true class pays . Differentiate :
The softmax itself has the Jacobian with entries , that is . It is symmetric, and its rows sum to zero because can't change. Frameworks fuse softmax and cross-entropy into one operation precisely because is simpler and more stable than multiplying by .
import numpy as np
def softmax(z):
e = np.exp(z - z.max()) # subtracting the max avoids overflow
return e / e.sum()
z, t = np.array([2.0, -1.0, 0.5, 0.0]), 2
p = softmax(z)
J = np.diag(p) - np.outer(p, p)
print("p :", np.round(p, 4))
print("dL/dz :", np.round(p - np.eye(4)[t], 4))
h = 1e-6
J_num = np.column_stack([(softmax(z + h*e) - softmax(z - h*e)) / (2*h) for e in np.eye(4)])
print("max |J - J_num| =", f"{float(np.abs(J - J_num).max()):.1e}")
print("row sums of J :", np.round(J.sum(axis=1), 12) + 0.0)p : [0.7101 0.0354 0.1584 0.0961]
dL/dz : [ 0.7101 0.0354 -0.8416 0.0961]
max |J - J_num| = 6.3e-11
row sums of J : [0. 0. 0. 0.]
Jacobian-vector and vector-Jacobian products
For the Jacobian is an matrix, often far too big to store (a layer with a million inputs and outputs has entries). Automatic differentiation never builds it. It provides two products instead:
| Product | Meaning | AD mode | Cost of the full Jacobian |
|---|---|---|---|
| JVP: () | directional derivative of along | forward mode | passes |
| VJP: () | gradient of | reverse mode (backprop) | passes |
A loss has output, so one reverse pass (one VJP with ) gives the whole gradient, whatever the number of parameters. That is why deep learning uses reverse mode. A JVP is the directional derivative from Directional Derivatives: , which the next program approximates and compares with an exact product.
import numpy as np
A = np.array([[1.0, 2.0, 0.0], [0.0, -1.0, 3.0]])
f = lambda x: np.tanh(A @ x) # R^3 -> R^2
def jacobian(x):
s = 1 - np.tanh(A @ x)**2 # tanh' = 1 - tanh^2
return s[:, None] * A # chain rule: diag(s) @ A
x = np.array([0.2, -0.1, 0.4])
v = np.array([1.0, 0.0, -1.0])
u = np.array([1.0, 1.0])
eps = 1e-6
print("JVP exact :", np.round(jacobian(x) @ v, 6))
print("JVP finite :", np.round((f(x + eps*v) - f(x - eps*v)) / (2*eps), 6))
print("VJP u^T J :", np.round(u @ jacobian(x), 6), " = gradient of sum(f)")JVP exact : [ 1. -0.7723]
JVP finite : [ 1. -0.7723]
VJP u^T J : [1. 1.742567 0.7723 ] = gradient of sum(f)
In software
- PyTorch, JAX, TensorFlow.
loss.backward()is a VJP chain;jax.jvpandjax.vjpexpose both products, andjax.jacfwd/jax.jacrevbuild full Jacobians from JVPs or VJPs, choosing whichever is cheaper. - LLMs. The output layer of a language model is a softmax over a vocabulary of ~100,000 tokens, trained with exactly the gradient. Temperature divides the logits, , which scales that gradient by .
- Gradient checking. The finite-difference comparisons above are the standard unit test for a hand-written backward pass; see Numerical Calculus and Floating Point for choosing .
Exercises
Exercise 1: The logistic gradient
Show that for one example with label and logit , the derivative of is . What is it for , ?
Answer
; at , it is .
Solution
Exercise 2: Least squares by hand
Fit to the points , , with . Find and the minimiser.
Answer
; the minimiser is .
Solution
Exercise 3: A softmax gradient
For logits and true class (the third), compute and to 4 decimals.
Answer
; .
Solution
import numpy as np
z = np.array([1.0, 2.0, 3.0])
p = np.exp(z) / np.exp(z).sum()
print(np.round(p, 4), np.round(p - np.array([0, 0, 1]), 4))[0.09 0.2447 0.6652] [ 0.09 0.2447 -0.3348]
Exercise 4: JVP and VJP (code)
For at , compute the Jacobian, the JVP with and the VJP with .
Answer
; ; .
Solution
import numpy as np
x, y = 1.0, 2.0
J = np.array([[2*x*y, x**2], [y*np.cos(x*y), x*np.cos(x*y)]])
print(np.round(J, 6).tolist())
print(np.round(J @ [1, 0], 6), np.round(np.array([1, 1]) @ J, 6))[[4.0, 1.0], [-0.832294, -0.416147]]
[ 4. -0.832294] [3.167706 0.583853]
Exercise 5: Why the rows sum to zero
Explain without computing why each column of the softmax Jacobian sums to zero, and why that implies the rows do too.
Answer
for every , so (columns); is symmetric, so the rows sum to zero too.
Solution
Differentiate the constant with respect to : , which is the sum of column . The entry formula is symmetric in and , so row sums equal column sums. Consequence: adding the same constant to every logit does not change , so the gradient also sums to zero.
Test yourself
What is the gradient of softmax + cross-entropy with respect to the logits?
- (probabilities minus the one-hot target)
Why does deep learning use reverse-mode AD (vector-Jacobian products)?
- It is more accurate
- A scalar loss needs only one VJP to get the gradient for all parameters
- Forward mode cannot compute derivatives
- It avoids the chain rule
What does a Jacobian-vector product compute?
- The directional derivative of along
- The determinant of
- The gradient of
- The inverse of applied to