The Math Behind the Methods

Matrix Calculus Identities a Machine Learning Reader Needs

A compact, checked set of gradient identities for vectors and matrices, with shape rules, a derivation method and test code.

Key takeaways

  • The gradient of a scalar loss has the same shape as the variable, which settles most questions about where transposes go.
  • The gradient of xᵀAx is (A + Aᵀ)x, which becomes 2Ax only when A is symmetric.
  • The gradient of ‖Ax − b‖² is 2Aᵀ(Ax − b), and setting it to zero gives the normal equations.
  • Writing a small change as df = tr(Gᵀ dX) identifies G as the gradient and handles most new expressions.
  • Always confirm a derived gradient against a finite difference before trusting it.

Most gradients you meet in machine learning papers come from a short list of identities: linear and quadratic forms, squared error, traces, log determinants and the two classification losses. Learn that list, plus one method for deriving anything not on it, and most "it can be shown that" lines become checkable.

This page uses one layout throughout. The gradient of a scalar with respect to a vector or matrix has the same shape as that vector or matrix. Vectors are columns.

Layout conventions and why books disagree

Some texts write the derivative of a scalar with respect to a column vector as a column, others as a row. Both are consistent systems, often called denominator layout and numerator layout. Mixing them produces formulas that differ by a transpose and shapes that will not multiply.

Here the gradient ∇ₓf is a column like x, as optimizers expect, since w − η∇L must be a legal subtraction. For a vector-valued function y = f(x), the Jacobian has one row per output and one column per input, as described in Jacobians and vector-Jacobian products.

Linear and quadratic forms

Let x and a be vectors of length n, and let A be a matrix whose shape fits each expression.

Function Derivative Note
aᵀx gradient a Same as for xᵀa
xᵀx = ‖x‖² gradient 2x The matrix version of x²
xᵀAx gradient (A + Aᵀ)x 2Ax if A is symmetric
Ax (vector output) Jacobian A A has shape (m, n)
‖x‖, with x ≠ 0 gradient x / ‖x‖ A unit vector
xᵀAx, second derivative Hessian A + Aᵀ Constant everywhere

Verify the third row with numbers. Let A = [[1, 2], [0, 3]] and x = (1, 1).

f(x) = x₁² + 2x₁x₂ + 3x₂²
∂f/∂x₁ = 2x₁ + 2x₂ = 4
∂f/∂x₂ = 2x₁ + 6x₂ = 8

(A + Aᵀ) x = [[2, 2], [2, 6]] (1, 1) = (4, 8)

Using 2Ax here would give (6, 6), which is wrong, because A is not symmetric.

Least squares and ridge

Let X have shape (n, d), with one example per row, w shape (d,) and y shape (n,).

L(w) = ‖Xw − y‖²
∇L   = 2 Xᵀ (Xw − y)
H    = 2 Xᵀ X

Setting the gradient to zero gives the normal equations, XᵀXw = Xᵀy. Add a penalty λ‖w‖² with λ > 0 and the gradient gains 2λw, so the solution becomes:

w = (Xᵀ X + λ I)⁻¹ Xᵀ y

The matrix in parentheses is always invertible for λ > 0. If your loss averages over n or carries a factor of one half, the constants change, and so does the meaning of a given λ. In code, solve the linear system instead of forming an inverse.

For several outputs, let W have shape (d, k) and Y shape (n, k). With the Frobenius norm, the square root of the sum of squared entries, the gradient of ‖XW − Y‖² is 2Xᵀ(XW − Y). The picture behind the solution is in projections and least squares.

The method of differentials

For anything new, work with small changes. The trace, tr(M), is the sum of the diagonal entries of a square matrix. For two matrices of the same shape, tr(GᵀD) is the sum of the products of matching entries. So if you can write a change in f as

df = tr(Gᵀ dX)

then G is the gradient of f with respect to X. Three facts do the rearranging:

  • d(AB) = (dA)B + A(dB).
  • The trace of a product is unchanged by cycling its factors: tr(ABC) = tr(CAB) = tr(BCA).
  • A scalar equals its own trace and its own transpose.
Deriving a gradient with differentials
1 Perturb Take the differential of the whole expression. 2 Expand Apply the product rule, keeping factor order. 3 Wrap in a trace A scalar is its own trace. 4 Cycle Move dX to the far right of the product. 5 Read off What sits before dX is the gradient transposed. Perturb Take the differential of the whole expression. 1 Expand Apply the product rule, keeping factor order. 2 Wrap in a trace A scalar is its own trace. 3 Cycle Move dX to the far right of the product. 4 Read off What sits before dX is the gradient transposed. 5

Here is the method applied to f(X) = aᵀXb.

df = aᵀ (dX) b
   = tr(aᵀ dX b)
   = tr(b aᵀ dX)            cycle b to the front
Gᵀ = b aᵀ    so    G = a bᵀ

The result has shape (rows of X, columns of X), as it should: an outer product of a and b.

Inverses, determinants and traces

These appear in Gaussian models, Gaussian processes and normalizing flows. In each, A is square.

Expression Result Condition
tr(AᵀB), gradient in A B Same shapes
d(A⁻¹) −A⁻¹ (dA) A⁻¹ A invertible
ln det A, gradient in A (A⁻¹)ᵀ det A > 0
tr(A⁻¹B), gradient in A −(A⁻¹BA⁻¹)ᵀ A invertible

The inverse rule follows from differentiating AA⁻¹ = I. When A is symmetric, the transpose in the log determinant rule disappears.

Take fitting the covariance Σ of a Gaussian with a known mean μ. Let S be the sum over n examples of (x − μ)(x − μ)ᵀ. Dropping constants, the log likelihood is:

ℓ(Σ) = −(n/2) ln det Σ − (1/2) tr(Σ⁻¹ S)
∇ℓ   = −(n/2) Σ⁻¹ + (1/2) Σ⁻¹ S Σ⁻¹
∇ℓ = 0   →   Σ = S / n                (needs S invertible)

Two table rows and one multiplication on both sides by Σ give the familiar sample covariance.

Classification losses

For a linear logistic model with labels y of 0 or 1 and predictions p = σ(Xw), the summed log loss has the gradient

∇w = Xᵀ (p − y)
H  = Xᵀ diag(p ⊙ (1 − p)) X

where ⊙ is elementwise multiplication. For softmax regression with scores Z = XW, probabilities P and one-hot labels Y, all of shape (n, k), the gradient is Xᵀ(P − Y). Both read as inputs transposed times prediction error. The probabilistic reason is worked out in cross-entropy from likelihood.

Elementwise functions

If h acts on each entry separately and f = ∑ h(xᵢ), the gradient is h′ applied entrywise. When an elementwise function sits between matrix products, as in L = ℓ(h(XW)), let G be the gradient of ℓ with respect to the output of h. Then:

∇W = Xᵀ (G ⊙ h′(XW))

This single line covers the weight gradient of any fully connected layer. The chain rule on computation graphs shows how such pieces connect.

Worked case: the first principal direction

Identities become useful when you combine them. Suppose you want the unit vector u that maximizes uᵀCu, where C is a symmetric covariance matrix. This is the first step of principal component analysis.

The constraint uᵀu = 1 is handled with a Lagrange multiplier, an extra unknown λ that couples the objective to the constraint.

J(u, λ) = uᵀ C u − λ (uᵀ u − 1)
∇u J    = 2 C u − 2 λ u
∇u J = 0   →   C u = λ u

Two rows of the first table turned an optimization problem into an eigenvalue problem. Multiplying the result on the left by uᵀ shows that the objective equals λ at any such point, so the maximum is reached by the eigenvector with the largest eigenvalue.

Reading identities from a paper

When a formula in a paper does not match yours, run through a short checklist before concluding that either is wrong.

First, find the shapes. Authors differ on whether examples are rows or columns of X, and the two choices transpose nearly every expression. Write the shape under each symbol and confirm that the products are defined.

Second, find the layout. A row gradient in one source is the transpose of a column gradient in another.

Third, compare the loss definitions. A factor of one half, a mean over examples, or a sum over output dimensions changes constants. A natural logarithm and a base 2 logarithm differ by a factor of ln 2.

Fourth, check which matrices are assumed symmetric or invertible. Covariance matrices are symmetric, but may be singular when there are fewer examples than features, in which case the inverse and log determinant formulas do not apply without added regularization.

Finally, test a scalar case. Set every matrix to size 1 by 1 and the identity should reduce to an ordinary derivative. For the log determinant, that gives 1/a, as expected for ln a.

Test every result

A central difference along a random direction checks all entries at once.

import numpy as np

rng = np.random.default_rng(0)
n = 4
A = rng.normal(size=(n, n)) + 5*np.eye(n)     # comfortably invertible
B = rng.normal(size=(n, n))
D = rng.normal(size=(n, n))                   # random direction

def f(A):
    return np.trace(np.linalg.solve(A, B))    # tr(A^-1 B)

Ai = np.linalg.inv(A)
G = -(Ai @ B @ Ai).T
h = 1e-6
numeric = (f(A + h*D) - f(A - h*D)) / (2*h)
print(numeric, np.sum(G * D))                 # should agree closely

If the two numbers differ, check transposes first, then constants such as 2 or 1/n. For expressions involving symmetric matrices, perturb with a symmetric D if your function assumes symmetry.

Common errors

  • Dividing by a vector. There is no such operation. If a derivation seems to need it, a transpose or an inverse has gone missing.
  • Assuming matrices commute. AB and BA generally differ, and may not even have the same shape.
  • Applying the symmetric shortcut. The 2Ax rule needs A = Aᵀ.
  • Losing the batch factor. A mean loss divides the gradient by n, a sum does not.

Common questions

Do I need these if my library differentiates for me?

You can train models without them. You need them to read papers, to derive closed-form solutions, to debug a custom operation and to spot when a cheaper formula exists. Automatic differentiation computes numbers, while an identity can reveal structure.

What about derivatives of a matrix with respect to a matrix?

That object has four indices. You rarely need to write it out. Use differentials, or compute the product with an incoming gradient, which keeps every quantity a matrix.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 26 articles in The Math Behind the Methods →

Latest news on this topic