09 / 16 · Calculus
Matrix calculus
Differentiating losses written in whole vectors and matrices, without indices: the differential and the trace trick, and the identities for quadratic forms, log-determinants, inverses and the softmax cross-entropy.
Gradients, Jacobians and Hessians · Determinants and eigenvalues
On this page 12
Fit a Gaussian to data by maximum likelihood, and the covariance matrix is found where the derivative of the log-likelihood
vanishes. Here is the number of points and the matrix of their scatter around the mean, defined below. What is the derivative of a log-determinant with respect to a matrix? And of an inverse?
The previous note differentiated one coordinate at a time, and for small expressions that works. In the quadratic form , the derivative in collects the terms with , which give , and those with , which give . The term belongs to both groups, and its derivative is shared between them:
For the same route needs the cofactor expansion of the determinant, and is defined only implicitly, by . Even when the entries come out right, they must be put back into a matrix of some shape. The losses of machine learning are written this way throughout: , the cross-entropy of , the Gaussian above. We want to differentiate them as whole expressions, the way we differentiate or for a number.
Layout: what shape a derivative has#
Texts disagree on whether the derivative of a scalar with respect to a column vector is a column or a row. Every course on this site uses one convention:
- for a scalar of a vector , the gradient is a column with the shape of ;
- for a scalar of a matrix , has the shape of , with entries ;
- for a vector function of , the Jacobian is , outputs × inputs.
For gradients this is the denominator layout: the derivative is laid out like the variable in the denominator. For Jacobians it is the numerator layout, so the gradient of a scalar is the transpose of its Jacobian. The least-squares note writes its gradient as a column, and the adjoints of backpropagation have the shapes of their variables. The Matrix Cookbook uses the same convention for scalars (Petersen and Pedersen, 2012).
The reason to prefer it: the update only makes sense when has the shape of . A source in the pure numerator layout writes , a row. That one formula tells you which layout a source uses.
The differential method#
The differential of a scalar function is the linear part of its change: , where is a small change of , a matrix of the same shape. The linear part has one coefficient per entry of . The layout convention puts the coefficient of at position , and the identity turns the sum of products into a trace. The identity holds because the -th diagonal entry of is :
Conversely, if for every , then the choice , the matrix with a single 1 at , gives . So the gradient can be read off any expression of the right form:
For a vector variable the same statement reads . Merkulov (2024) writes it with the inner product, , and the trace is that inner product for matrices.
Differentials obey a few rules. Each comes from expanding and dropping products of two small changes.
| Rule | Why |
|---|---|
| for a constant | it does not change |
| linearity | |
| the term is second order | |
| , | both maps are linear |
| for an elementwise | one variable per entry |
Here is the elementwise product. The rearranging is done by three facts about the trace: a scalar is its own trace, , and , since both equal . Applied to the pair and , the last fact gives , the cyclic property. A derivation then has three steps:
- compute with the rules;
- move to the right end of a trace with the cyclic property, ;
- read off .
Linear and quadratic forms#
A linear form changes by the form applied to the change, , so its gradient is . The quadratic form has in two places, and the product rule gives one term for each:
The gradient is , the result of the index computation above. For a symmetric it is , and only then.
Take with rows and and . Then , and has rows and , so the gradient is . The partial derivatives and agree. The shortcut is wrong, because this is not symmetric.
Least squares#
Why is the gradient of equal to ? Go through the residual , which changes by :
The third line gives the gradient . The Hessian is the Jacobian of the gradient, so the last line gives .
With the same , and : , , , and the gradient is . With , the design matrix, and , these are the gradient and the Hessian of the least-squares note, and setting the gradient to zero gives its normal equations. In that note’s four-point example, has columns and and . The gradient is at and zero at .
Traces of matrix products#
When the variable is a matrix, the trace is already there. For the differential is , so and the gradient is . For the product rule gives two terms. Transposing the first inside its trace puts at the right end of both:
So and the gradient is . The squared Frobenius norm is the case , with gradient : the derivative of the weight-decay penalty of regularization.
The transpose in is easy to lose. For with rows and , , so the coefficient of is , the entry of . A guess of would give 2.
The log-determinant#
The columns of span a parallelogram, or in dimensions a parallelepiped, of volume . How much does the volume change when the columns move a little? We need one fact first. For a small matrix ,
By the Leibniz formula , the identity permutation contributes plus products of two or more entries of . Every other permutation moves at least two indices, so its product contains at least two off-diagonal entries of and is second order. For invertible we factor , use the product rule , and apply the fact with . Since , a term of second order in is of second order in :
The linear part is the differential, and dividing by gives the logarithm, since :
Reading off, , where , and . For a symmetric the first is . The second is the matrix of cofactors. Every Leibniz product contains the entry at most once, so is affine in , and its coefficient there, , is by definition the cofactor . So , which is the cofactor formula . Strang (2018) reaches the gradient from that side, through the cofactor expansion along a row.
A worked example with of rows and , and a change of rows and :
| Quantity | Value |
|---|---|
| , by rows | , |
| , by rows | , |
| first-order prediction | |
| exact |
The area grows by 15% to first order. The remaining is : for matrices, exactly. Raising only by raises the determinant by exactly , because the determinant is affine in each single entry, with the cofactor as slope.
Derivation: the exact 2 × 2 identity
Write with rows and , and expand the formula for :
The middle bracket is with the cofactors , , , . By the cofactor formula , so the bracket is . In the example, .
The differential of the determinant as a change of area
The log-determinant appears wherever a density is normalized or transformed: in the log-likelihood of the multivariate Gaussian, in normalizing flows, and the evidence of Bayesian linear regression and of Gaussian processes, whose gradients use this identity and the next one.
The inverse#
The inverse is defined by . Differentiate both sides; the right side does not change:
Multiplying by on the left gives
For matrices this is the familiar . Differentiating assumed that has a differential at all; the fold checks the result directly.
Derivation: the inverse has this differential
Let be a small change and the candidate. Multiply out:
Multiplying on the left by , which exists for small because is close to :
By the cofactor formula the entries of are polynomials in the entries divided by , so they stay bounded near . The right side is therefore , and is the linear part of the change.
A scalar built from the inverse, such as for fixed vectors and , then follows in two steps:
So , and the gradient is .
With as above, and : and . The gradient is minus the outer product of and :
Raising by should lower the value by about .
Back to the Gaussian covariance#
Now the opening problem takes a few lines. For points with a known mean , let . Each quadratic term of the Gaussian log-density is a scalar, hence its own trace, and the cyclic property turns it into . Linearity of the trace collects the sum into one trace. Up to the term with of the density, which does not depend on ,
A covariance matrix is positive definite, so and . The log-determinant rule handles the first term. For the second, , the inverse rule gives the second line, and the cyclic property moves to the right end:
Only symmetric changes keep a covariance matrix. The matrix in the bracket is symmetric too, and the choice gives . So the differential vanishes for every symmetric exactly when . Multiplying by on both sides gives , that is,
The estimate is a valid covariance when is positive definite, that is, when the centred points span the whole space: vanishes only for a orthogonal to all of them. Written in the precision , the log-likelihood is , and the log-determinant rule alone gives , the form in which Merkulov (2024) poses the exercise.
For the three points , and , whose mean is , has rows and , and . The factor instead of is the bias of maximum likelihood discussed in the estimators note. The same estimate, weighted by responsibilities, is the M-step of the EM algorithm for each component.
The softmax cross-entropy#
For scores the probabilities are , with , and the loss for a one-hot label is . Two facts make the differential short. First, , where is the log-sum-exp, and , so . Second, , by the chain rule through the logarithm. For a linear layer , so that :
So , and .
Take with the true class first, , and the input :
| Quantity | Value |
|---|---|
| , by rows | , , |
The entries of sum to 0, because , where is the vector of ones: adding the same constant to every score changes nothing. With the sign reversed, the same result is the score of a softmax policy, for the action taken, the factor that policy gradients multiply by the return.
The route through the softmax Jacobian gives the same result with more work. From , , so . The gradient of the loss in is , entry by entry, and the chain rule multiplies it by the symmetric Jacobian: . Frameworks therefore fuse softmax and cross-entropy into one operation. It is also more stable numerically: it computes with the maximum subtracted, and never takes the logarithm of a probability that has underflowed to 0. For a batch with the examples as the rows of , , the loss is the sum over examples, and summing the per-example gradients over the rows gives . It is the of the logistic regression note, with the weights stored as columns instead of rows.
The check against logistic regression#
Binary logistic regression has , and the loss . With , the chain rule gives , and since , this is . Dividing by and by , the two kinds of terms change by
For either label the term changes by , the binary case of . With and :
where . So and , the gradient and the Hessian of the logistic regression note. In its worked example, with one feature , labels and , the residuals are , the gradient is , and the Hessian is .
Where it breaks#
Every formula above treats the entries of as independent variables. A covariance matrix is symmetric, and if its parameters are only the distinct entries, the formulas give the wrong number. Take with rows and at , so that . The derivative in the single parameter is
The formula gives at position . Both entries and move with , so the true derivative is the sum of the two, . In general, let be the gradient computed as if all entries were independent, and let the parameters be the entries with , so that . The chain rule adds the two entries that move with : for , and on the diagonal. In matrix form the gradient is (Petersen and Pedersen, 2012, Section 2.8.2, equation 138). An optimizer that updates all entries needs the formulas as derived here, and for a symmetric the gradients and are symmetric anyway, so the iterates stay symmetric.
Layouts cause the second common error. An identity copied from a text in the numerator layout arrives transposed; check it with and by the shapes. Matrix-valued functions of matrices have four-index derivatives, which the method avoids by keeping a scalar loss at the end of every chain. And a formula is not an algorithm: numerical code computes by a linear solve and as twice the sum of the logarithms of the diagonal entries of a Cholesky factor, which never forms a determinant that could overflow or underflow. For training code, automatic differentiation computes the gradients; the identities give closed forms, Hessians for Newton’s method, and a check on what autograd returns.
What you should remember#
- Gradients have the shape of the variable; Jacobians are outputs × inputs.
- means . Get there with the product rule and the cyclic trace.
- ; ; .
- and .
- Softmax cross-entropy: , .
- For symmetric parameters, count each off-diagonal entry twice.
Code#
Every identity of the note is checked against central differences, with a helper that perturbs one entry of a vector or a matrix at a time; the random matrices are fixed by a seed. Digits in the last places may vary across platforms.
import numpy as np
rng = np.random.default_rng(0)
def num_grad(f, X, h=1e-6):
"""Central differences in every entry of X; the result has the shape of X."""
G = np.zeros_like(X, dtype=float)
for idx in np.ndindex(X.shape):
E = np.zeros_like(X, dtype=float); E[idx] = h
G[idx] = (f(X + E) - f(X - E)) / (2 * h)
return G
def check(name, f, X, G):
print(f'{name:14s} max error {np.abs(num_grad(f, X) - G).max():.1e}')
# the worked examples
A = np.array([[1., 2], [0, 3]]); x = np.array([1., 2]); b = np.array([1., 1])
print(x @ A @ x, (A + A.T) @ x, 2 * A @ x, 2 * A.T @ (A @ x - b)) # 17.0 [ 6. 14.] [10. 12.] [ 8. 46.]
X = np.array([[2., 1], [0.5, 1.5]]); Xi = np.linalg.inv(X); dX = np.array([[0.1, 0.05], [-0.05, 0.1]])
print(np.linalg.det(X).round(6), (np.linalg.det(X) * Xi.T).round(6), np.trace(Xi @ dX).round(6),
(np.linalg.det(X) * (1 + np.trace(Xi @ dX))).round(6), np.linalg.det(X + dX).round(6), np.linalg.det(dX).round(6))
# 2.5 [[ 1.5 -0.5] [-1. 2. ]] 0.15 2.875 2.8875 0.0125
a = np.array([1., 2]); print(round(a @ Xi @ b, 6), (-Xi.T @ np.outer(a, b) @ Xi.T).round(6)) # 1.4 [[-0.04 -0.12] [-0.24 -0.72]]
# every identity on random matrices
n = 4
a, b, x = rng.normal(size=n), rng.normal(size=n), rng.normal(size=n)
A, B = rng.normal(size=(n, n)), rng.normal(size=(n, n))
X = rng.normal(size=(n, n)) + n * np.eye(n) # comfortably invertible
check('a^T x', lambda v: a @ v, x, a)
check('x^T A x', lambda v: v @ A @ v, x, (A + A.T) @ x)
check('|Ax - b|^2', lambda v: np.sum((A @ v - b) ** 2), x, 2 * A.T @ (A @ x - b))
check('tr(AX)', lambda M: np.trace(A @ M), X, A.T)
check('tr(X^T A X)', lambda M: np.trace(M.T @ A @ M), X, (A + A.T) @ X)
check('log|det X|', lambda M: np.linalg.slogdet(M)[1], X, np.linalg.inv(X).T)
Xi = np.linalg.inv(X)
check('a^T X^-1 b', lambda M: a @ np.linalg.solve(M, b), X, -Xi.T @ np.outer(a, b) @ Xi.T)
# each line prints a max error between 3e-11 and 7e-09: agreement to the accuracy of central differences
# d(X^-1) itself: the first-order change of the inverse matches -X^-1 dX X^-1
E = 1e-6 * rng.normal(size=(n, n))
print(f'{np.abs(np.linalg.inv(X + E) - Xi - (-Xi @ E @ Xi)).max():.1e}') # 7.0e-14: second order in E
# softmax cross-entropy: the worked example, then a random layer
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
z = np.array([2., 1, 0.1]); y = np.array([1., 0, 0]); p = softmax(z)
print(p.round(3), round(-np.log(p[0]), 3), (p - y).round(3), np.outer(p - y, [1, -2]).round(3))
# [0.659 0.242 0.099] 0.417 [-0.341 0.242 0.099] [[-0.341 0.682] [ 0.242 -0.485] [ 0.099 -0.197]]
K, d = 3, 5
W, bb, xx = rng.normal(size=(K, d)), rng.normal(size=K), rng.normal(size=d)
ce = lambda W_, b_: -np.log(softmax(W_ @ xx + b_)[1]) # true class 1
p = softmax(W @ xx + bb); y = np.eye(K)[1]
check('CE, W', lambda M: ce(M, bb), W, np.outer(p - y, xx))
check('CE, b', lambda v: ce(W, v), bb, p - y)
# CE, W max error 2.4e-10 | CE, b max error 1.5e-10
# least squares on the four points of the least-squares note
Xd = np.column_stack([np.ones(4), [0., 1, 2, 3]]); yd = np.array([1., 3, 2, 5])
print(2 * Xd.T @ (Xd @ np.zeros(2) - yd), (2 * Xd.T @ (Xd @ np.array([1.1, 1.1]) - yd)).round(12) + 0) # [-22. -44.] [0. 0.]
# logistic regression: the worked example of its note, then a random design
sig = lambda t: 1 / (1 + np.exp(-t))
xl, yl = np.array([2., -1, 0.5]), np.array([1., 0, 0]); pl = sig(xl)
print((pl - yl).round(3), round(xl @ (pl - yl), 3), round(np.sum(pl * (1 - pl) * xl ** 2), 3)) # [-0.119 0.269 0.622] -0.196 0.675
Xr, yr, w = rng.normal(size=(20, 3)), rng.integers(0, 2, 20).astype(float), rng.normal(size=3)
nll = lambda v: -np.sum(yr * np.log(sig(Xr @ v)) + (1 - yr) * np.log(1 - sig(Xr @ v)))
pr = sig(Xr @ w)
check('logistic grad', nll, w, Xr.T @ (pr - yr))
grad_l = lambda v: Xr.T @ (sig(Xr @ v) - yr)
H_num = np.column_stack([(grad_l(w + 1e-6 * e) - grad_l(w - 1e-6 * e)) / 2e-6 for e in np.eye(3)]) # Jacobian of the gradient
print(f'{"logistic Hess":14s} max error {np.abs(H_num - Xr.T @ np.diag(pr * (1 - pr)) @ Xr).max():.1e}')
# logistic grad max error 2.0e-09 | logistic Hess max error 7.2e-10
# the Gaussian covariance by maximum likelihood: the gradient vanishes at S / n
P3 = np.array([[1., 0], [-1, 1], [0, -1]]); S = P3.T @ P3
ell = lambda Sig: -1.5 * np.linalg.slogdet(Sig)[1] - 0.5 * np.trace(np.linalg.solve(Sig, S))
G_at = lambda Sig: -1.5 * np.linalg.inv(Sig) + 0.5 * np.linalg.inv(Sig) @ S @ np.linalg.inv(Sig)
check('Gaussian ell', ell, np.eye(2), G_at(np.eye(2))) # max error 2.6e-10
print((S / 3).round(3), np.abs(num_grad(ell, S / 3)).max() < 1e-8) # [[ 0.667 -0.333] [-0.333 0.667]] True
# where it breaks: a symmetric matrix with one shared off-diagonal parameter s
logdet_s = lambda s: np.linalg.slogdet(np.array([[2., s], [s, 2.]]))[1]
h = 1e-6
print(round((logdet_s(1 + h) - logdet_s(1 - h)) / (2 * h), 4), np.linalg.inv([[2., 1], [1, 2]])[0, 1].round(4))
# -0.6667 -0.3333: the derivative in s is twice the (1, 2) entry of the inverse
Next#
The calculus so far has been about derivatives. The other half, integration, enters machine learning through probability: normalizing a density, computing an expectation, marginalizing a variable, transforming a random vector by an invertible map. The next note builds integrals over several variables and derives the change-of-variables formula, whose factor is the local volume change seen in the Jacobian section. With it, the Gaussian integral that normalizes every Gaussian density takes three lines.
References#
- K. B. Petersen, M. S. Pedersen. The Matrix Cookbook, version of November 15, 2012. Section 2 (derivatives: the rules for differentials; 2.1, determinants; 2.2, inverses; 2.4, vector and scalar forms; 2.5, traces; 2.8, structured matrices).
- D. Merkulov. Optimization for ML, HSE University, 2024. Lecture 2: line search, matrix calculus, automatic differentiation (the differential, its rules, and the exercise with ).
- G. Strang. Matrix Methods in Data Analysis, Signal Processing, and Machine Learning (MIT 18.065), 2018. Lecture 22: gradient descent, downhill to a minimum (the gradient of the log-determinant through cofactors).