TExcelTAD
Home › Math for Machine Learning › Partial Derivatives and Gradients

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 f:Rn→Rf: \mathbb{R}^n \to \mathbb{R}, hold every variable but xix_i fixed and differentiate:

∂f∂xi=lim⁡h→0f(x1,…,xi+h,…,xn)−f(x)h\frac{\partial f}{\partial x_i} = \lim_{h \to 0} \frac{f(x_1, \ldots, x_i + h, \ldots, x_n) - f(\mathbf{x})}{h}

The gradient collects them. Following the convention of this course (and of the reference book), it is a row vector:

∇xf=dfdx=[∂f∂x1⋯∂f∂xn]∈R1×n\nabla_{\mathbf{x}} f = \frac{df}{d\mathbf{x}} = \begin{bmatrix} \frac{\partial f}{\partial x_1} & \cdots & \frac{\partial f}{\partial x_n} \end{bmatrix} \in \mathbb{R}^{1 \times n}

In code it is just an array of the same shape as x\mathbf{x}, and gradient descent uses its transpose.

Example: f(x1,x2)=x12x2+x1x23f(x_1, x_2) = x_1^2x_2 + x_1x_2^3 has

∂f∂x1=2x1x2+x23,∂f∂x2=x12+3x1x22\frac{\partial f}{\partial x_1} = 2x_1x_2 + x_2^3, \qquad \frac{\partial f}{\partial x_2} = x_1^2 + 3x_1x_2^2
python · try it yourself
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 u\mathbf{u}, the directional derivative is ∇f u=∥∇f∥cos⁡ω\nabla f\,\mathbf{u} = \lVert \nabla f \rVert \cos\omega. It is largest when u\mathbf{u} points along the gradient and most negative when it points against it. Along a direction orthogonal to the gradient, ff 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 ff depends on x\mathbf{x} through xi(t)x_i(t),

dfdt=∑i∂f∂xidxidt=∂f∂xdxdt\frac{df}{dt} = \sum_{i} \frac{\partial f}{\partial x_i}\frac{dx_i}{dt} = \frac{\partial f}{\partial \mathbf{x}}\frac{d\mathbf{x}}{dt}

a row vector times a column vector. In ML, tt is a parameter, x\mathbf{x} an intermediate activation and ff the loss: this product, repeated layer by layer, is backpropagation.

The gradient of the squared loss

For a linear model, L(θ)=∥y−Xθ∥2=∑n(yn−xnTθ)2L(\boldsymbol{\theta}) = \lVert \mathbf{y} - X\boldsymbol{\theta} \rVert^2 = \sum_n (y_n - \mathbf{x}_n^T\boldsymbol{\theta})^2. Differentiating each term with the chain rule:

∂L∂θd=∑n2(yn−xnTθ)(−xnd)  ⟹  ∇θL=−2(y−Xθ)TX\frac{\partial L}{\partial \theta_d} = \sum_n 2(y_n - \mathbf{x}_n^T\boldsymbol{\theta})(-x_{nd}) \implies \nabla_{\boldsymbol{\theta}} L = -2(\mathbf{y} - X\boldsymbol{\theta})^TX

Setting it to zero gives the normal equations XTXθ=XTyX^TX\boldsymbol{\theta} = X^T\mathbf{y}.

python · try it yourself
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() fills param.grad with 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 ∇f\nabla f for f(x,y)=exy+x2f(x, y) = e^{xy} + x^2 at (1,0)(1, 0).

Answer

(2,1)(2, 1).

Solution

∂f∂x=yexy+2x\frac{\partial f}{\partial x} = ye^{xy} + 2x, ∂f∂y=xexy\frac{\partial f}{\partial y} = xe^{xy}. At (1,0)(1, 0): 0+2=20 + 2 = 2 and 1⋅1=11 \cdot 1 = 1.

Exercise 2: Steepest descent direction

For f(x,y)=x2+4y2f(x, y) = x^2 + 4y^2 at (1,1)(1, 1), which unit direction decreases ff fastest?

Answer

−(2,8)/68≈(−0.243,−0.970)-(2, 8)/\sqrt{68} \approx (-0.243, -0.970).

Solution

∇f=(2x,8y)=(2,8)\nabla f = (2x, 8y) = (2, 8). The steepest descent direction is −∇f/∥∇f∥-\nabla f / \lVert \nabla f \rVert with ∥(2,8)∥=68\lVert (2, 8) \rVert = \sqrt{68}. It points mostly along yy, where the function is steeper.

Exercise 3: Gradient of a quadratic (code)

For f(x)=xTAxf(\mathbf{x}) = \mathbf{x}^TA\mathbf{x} the gradient is xT(A+AT)\mathbf{x}^T(A + A^T). Check it numerically for a random non-symmetric 3×33 \times 3 matrix.

Answer

The formula matches the numerical gradient.

Solution
python · try it yourself
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 ∇f(x)\nabla f(\mathbf{x}) points in the direction of…

  1. steepest decrease
  2. steepest increase
  3. no change
  4. the origin

For L(θ)=∥y−Xθ∥2L(\boldsymbol{\theta}) = \lVert \mathbf{y} - X\boldsymbol{\theta} \rVert^2, setting ∇L=0\nabla L = 0 gives…

  1. Xθ=0X\boldsymbol{\theta} = 0
  2. XTXθ=XTyX^TX\boldsymbol{\theta} = X^T\mathbf{y}
  3. θ=y\boldsymbol{\theta} = \mathbf{y}
  4. X=IX = I

Gradients are ___ to level sets (contour lines).

  1. parallel
  2. perpendicular
  3. tangent
  4. unrelated