Partial Derivatives and Gradients
A loss function depends on many parameters at once. The partial derivative with respect to one parameter asks how the loss changes when only that parameter moves; collecting all of them gives the gradient, a vector that points in the direction of steepest increase. Training a model is walking against the gradient.
Partial derivatives
For , hold every variable but fixed and differentiate:
The gradient collects them. Following the convention of this course (and of the reference book), it is a row vector:
In code it is just an array of the same shape as , and gradient descent uses its transpose.
Example: has
import numpy as np
def f(x): return x[0]**2 * x[1] + x[0] * x[1]**3
def grad(x): return np.array([2 * x[0] * x[1] + x[1]**3, x[0]**2 + 3 * x[0] * x[1]**2])
def numeric_grad(f, x, h=1e-6):
g = np.zeros_like(x)
for i in range(len(x)):
e = np.zeros_like(x); e[i] = h
g[i] = (f(x + e) - f(x - e)) / (2 * h)
return g
x = np.array([1.0, 2.0])
print("analytic:", grad(x), " numeric:", np.round(numeric_grad(f, x), 6))analytic: [12. 13.] numeric: [12. 13.]
The gradient is the steepest direction
For a unit direction , the directional derivative is . It is largest when points along the gradient and most negative when it points against it. Along a direction orthogonal to the gradient, does not change at first order: gradients are perpendicular to level sets (contour lines).
Rules for gradients
The one-variable rules carry over. The chain rule is the important one: if depends on through ,
a row vector times a column vector. In ML, is a parameter, an intermediate activation and the loss: this product, repeated layer by layer, is backpropagation.
The gradient of the squared loss
For a linear model, . Differentiating each term with the chain rule:
Setting it to zero gives the normal equations .
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(50, 3)); y = X @ np.array([1.0, -2.0, 0.5]) + 0.1 * rng.normal(size=50)
theta = np.array([0.0, 0.0, 0.0])
L = lambda t: np.sum((y - X @ t) ** 2)
g = -2 * (y - X @ theta) @ X
h = 1e-6
num = np.array([(L(theta + h * e) - L(theta - h * e)) / (2 * h) for e in np.eye(3)])
print("formula:", np.round(g, 4))
print("numeric:", np.round(num, 4))
theta_star = np.linalg.solve(X.T @ X, X.T @ y)
print("gradient at the solution:", np.round(-2 * (y - X @ theta_star) @ X, 8) + 0)formula: [-119.1102 133.4759 -55.009 ]
numeric: [-119.1102 133.4759 -55.009 ]
gradient at the solution: [0. 0. 0.]
In software
- PyTorch's
loss.backward()fillsparam.gradwith exactly these partial derivatives, shaped like the parameters. - The numerical gradient above is the standard way to test hand-written gradients.
- Gradients are perpendicular to contour lines: plotting both is a good sanity check for 2-parameter toy problems.
Exercises
Exercise 1: Compute a gradient
Find for at .
Answer
.
Solution
, . At : and .
Exercise 2: Steepest descent direction
For at , which unit direction decreases fastest?
Answer
.
Solution
. The steepest descent direction is with . It points mostly along , where the function is steeper.
Exercise 3: Gradient of a quadratic (code)
For the gradient is . Check it numerically for a random non-symmetric matrix.
Answer
The formula matches the numerical gradient.
Solution
import numpy as np
rng = np.random.default_rng(4)
A, x = rng.normal(size=(3, 3)), rng.normal(size=3)
f = lambda v: v @ A @ v
num = np.array([(f(x + 1e-6 * e) - f(x - 1e-6 * e)) / 2e-6 for e in np.eye(3)])
print(np.allclose(num, x @ (A + A.T), atol=1e-6))True
Test yourself
The gradient points in the direction of…
- steepest decrease
- steepest increase
- no change
- the origin
For , setting gives…
Gradients are ___ to level sets (contour lines).
- parallel
- perpendicular
- tangent
- unrelated