Course contents 09 / 16

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.

On this page 12

Fit a Gaussian to data by maximum likelihood, and the covariance matrix Σ\Sigma is found where the derivative of the log-likelihood

ℓ(Σ)=−n2log⁡det⁡Σ−12tr⁡(Σ−1S)\ell(\Sigma) = -\frac n2 \log\det\Sigma - \frac12 \operatorname{tr}\big(\Sigma^{-1}S\big)

vanishes. Here nn is the number of points and SS 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 x⊤Ax=∑i∑jxiAijxjx^\top Ax = \sum_i \sum_j x_i A_{ij} x_j, the derivative in xkx_k collects the terms with i=ki = k, which give ∑jAkjxj\sum_j A_{kj}x_j, and those with j=kj = k, which give ∑ixiAik\sum_i x_i A_{ik}. The term Akkxk2A_{kk}x_k^2 belongs to both groups, and its derivative 2Akkxk2A_{kk}x_k is shared between them:

∂∂xk x⊤Ax=(Ax)k+(A⊤x)k.\frac{\partial}{\partial x_k}\, x^\top Ax = (Ax)_k + (A^\top x)_k .

For log⁡det⁡Σ\log\det\Sigma the same route needs the cofactor expansion of the determinant, and Σ−1\Sigma^{-1} is defined only implicitly, by ΣΣ−1=I\Sigma\Sigma^{-1} = I. 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: ∥Xw−y∥2\lVert Xw - y\rVert^2, the cross-entropy of softmax⁡(Wx)\operatorname{softmax}(Wx), the Gaussian above. We want to differentiate them as whole expressions, the way we differentiate log⁡x\log x or 1/x1/x 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 ff of a vector xx, the gradient ∂f/∂x=∇f(x)\partial f/\partial x = \nabla f(x) is a column with the shape of xx;
  • for a scalar ff of a matrix XX, ∂f/∂X\partial f/\partial X has the shape of XX, with entries ∂f/∂Xij\partial f/\partial X_{ij};
  • for a vector function ff of xx, the Jacobian ∂f/∂x\partial f/\partial x is m×nm \times n, 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 1×n1 \times n Jacobian. The least-squares note writes its gradient 2X⊤(Xw−y)2X^\top(Xw - y) 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 W←W−η ∂L/∂WW \leftarrow W - \eta\, \partial L/\partial W only makes sense when ∂L/∂W\partial L/\partial W has the shape of WW. A source in the pure numerator layout writes ∂(a⊤x)/∂x=a⊤\partial(a^\top x)/\partial x = a^\top, a row. That one formula tells you which layout a source uses.

The differential method#

The differential dfdf of a scalar function is the linear part of its change: f(X+dX)=f(X)+df+o(∥dX∥)f(X + dX) = f(X) + df + o(\lVert dX\rVert), where dXdX is a small change of XX, a matrix of the same shape. The linear part has one coefficient per entry of dXdX. The layout convention puts the coefficient of dXijdX_{ij} at position (i,j)(i, j), and the identity tr⁡(A⊤B)=∑ijAijBij\operatorname{tr}(A^\top B) = \sum_{ij} A_{ij} B_{ij} turns the sum of products into a trace. The identity holds because the jj-th diagonal entry of A⊤BA^\top B is ∑iAijBij\sum_i A_{ij} B_{ij}:

df=∑i,j∂f∂Xij dXij=tr⁡((∂f∂X) ⁣⊤dX).\begin{aligned} df &= \sum_{i,j} \frac{\partial f}{\partial X_{ij}}\, dX_{ij} \\ &= \operatorname{tr}\Big(\Big(\frac{\partial f}{\partial X}\Big)^{\!\top} dX\Big) . \end{aligned}

Conversely, if df=tr⁡(G⊤dX)df = \operatorname{tr}(G^\top dX) for every dXdX, then the choice dX=EijdX = E_{ij}, the matrix with a single 1 at (i,j)(i, j), gives Gij=∂f/∂XijG_{ij} = \partial f/\partial X_{ij}. So the gradient can be read off any expression of the right form:

  df=tr⁡(G⊤dX) for all dX  ⟺  ∂f∂X=G  \boxed{\; df = \operatorname{tr}\big(G^\top dX\big) \ \text{for all } dX \iff \frac{\partial f}{\partial X} = G \;}

For a vector variable the same statement reads df=g⊤dx  ⟺  ∇f=gdf = g^\top dx \iff \nabla f = g. Merkulov (2024) writes it with the inner product, df=⟨∇f,dx⟩df = \langle \nabla f, dx\rangle, and the trace is that inner product for matrices.

Differentials obey a few rules. Each comes from expanding f(X+dX)f(X + dX) and dropping products of two small changes.

RuleWhy
dA=0dA = 0 for a constant AAit does not change
d(αX+βY)=α dX+β dYd(\alpha X + \beta Y) = \alpha\, dX + \beta\, dYlinearity
d(XY)=(dX) Y+X (dY)d(XY) = (dX)\,Y + X\,(dY)the term (dX)(dY)(dX)(dY) is second order
d(X⊤)=(dX)⊤d(X^\top) = (dX)^\top,  dtr⁡X=tr⁡dX\ d\operatorname{tr}X = \operatorname{tr}dXboth maps are linear
d φ(x)=φ′(x)⊙dxd\,\varphi(x) = \varphi'(x) \odot dx for an elementwise φ\varphione variable per entry

Here ⊙\odot is the elementwise product. The rearranging is done by three facts about the trace: a scalar is its own trace, tr⁡(A⊤)=tr⁡A\operatorname{tr}(A^\top) = \operatorname{tr}A, and tr⁡(AB)=tr⁡(BA)\operatorname{tr}(AB) = \operatorname{tr}(BA), since both equal ∑i,jAijBji\sum_{i,j} A_{ij}B_{ji}. Applied to the pair ABAB and CC, the last fact gives tr⁡(ABC)=tr⁡(CAB)\operatorname{tr}(ABC) = \operatorname{tr}(CAB), the cyclic property. A derivation then has three steps:

  1. compute dfdf with the rules;
  2. move dXdX to the right end of a trace with the cyclic property, df=tr⁡(M dX)df = \operatorname{tr}(M\, dX);
  3. read off ∂f/∂X=M⊤\partial f/\partial X = M^\top.

Linear and quadratic forms#

A linear form changes by the form applied to the change, d(a⊤x)=a⊤dxd(a^\top x) = a^\top dx, so its gradient is aa. The quadratic form has xx in two places, and the product rule gives one term for each:

d(x⊤Ax)=(dx)⊤Ax+x⊤A dxproduct rule=x⊤A⊤dx+x⊤A dxtranspose a scalar=((A+A⊤)x)⊤dx.\begin{aligned} d(x^\top Ax) &= (dx)^\top Ax + x^\top A\, dx && \text{product rule} \\ &= x^\top A^\top dx + x^\top A\, dx && \text{transpose a scalar} \\ &= \big((A + A^\top)x\big)^\top dx . \end{aligned}

The gradient is (A+A⊤)x(A + A^\top)x, the result of the index computation above. For a symmetric AA it is 2Ax2Ax, and only then.

Take AA with rows (1,2)(1, 2) and (0,3)(0, 3) and x=(1,2)x = (1, 2). Then x⊤Ax=x12+2x1x2+3x22=17x^\top Ax = x_1^2 + 2x_1x_2 + 3x_2^2 = 17, and A+A⊤A + A^\top has rows (2,2)(2, 2) and (2,6)(2, 6), so the gradient is (6,14)(6, 14). The partial derivatives 2x1+2x2=62x_1 + 2x_2 = 6 and 2x1+6x2=142x_1 + 6x_2 = 14 agree. The shortcut 2Ax=(10,12)2Ax = (10, 12) is wrong, because this AA is not symmetric.

Least squares#

Why is the gradient of ∥Ax−b∥2\lVert Ax - b\rVert^2 equal to 2A⊤(Ax−b)2A^\top(Ax - b)? Go through the residual r=Ax−br = Ax - b, which changes by dr=A dxdr = A\, dx:

d(r⊤r)=2 r⊤drproduct rule, transpose=2 r⊤A dx=(2A⊤r)⊤dx,d(2A⊤r)=2A⊤A dx.\begin{aligned} d(r^\top r) &= 2\,r^\top dr && \text{product rule, transpose} \\ &= 2\,r^\top A\, dx \\ &= \big(2A^\top r\big)^\top dx , \\ d\big(2A^\top r\big) &= 2A^\top A\, dx . \end{aligned}

The third line gives the gradient 2A⊤(Ax−b)2A^\top(Ax - b). The Hessian is the Jacobian of the gradient, so the last line gives ∇2=2A⊤A\nabla^2 = 2A^\top A.

With the same AA, b=(1,1)b = (1, 1) and x=(1,2)x = (1, 2): Ax=(5,6)Ax = (5, 6), r=(4,5)r = (4, 5), ∥r∥2=41\lVert r\rVert^2 = 41, and the gradient is 2A⊤r=(8,46)2A^\top r = (8, 46). With A=XA = X, the design matrix, and b=yb = y, these are the gradient 2X⊤(Xw−y)2X^\top(Xw - y) and the Hessian 2X⊤X2X^\top X of the least-squares note, and setting the gradient to zero gives its normal equations. In that note’s four-point example, XX has columns (1,1,1,1)(1, 1, 1, 1) and (0,1,2,3)(0, 1, 2, 3) and y=(1,3,2,5)y = (1, 3, 2, 5). The gradient is (−22,−44)(-22, -44) at w=0w = 0 and zero at w^=(1.1,1.1)\hat w = (1.1, 1.1).

Traces of matrix products#

When the variable is a matrix, the trace is already there. For tr⁡(AX)\operatorname{tr}(AX) the differential is tr⁡(A dX)\operatorname{tr}(A\, dX), so M=AM = A and the gradient is A⊤A^\top. For tr⁡(X⊤AX)\operatorname{tr}(X^\top AX) the product rule gives two terms. Transposing the first inside its trace puts dXdX at the right end of both:

dtr⁡(X⊤AX)=tr⁡((dX)⊤AX)+tr⁡(X⊤A dX)=tr⁡(X⊤A⊤dX)+tr⁡(X⊤A dX)=tr⁡(X⊤(A+A⊤) dX).\begin{aligned} d\operatorname{tr}(X^\top A X) &= \operatorname{tr}\big((dX)^\top A X\big) + \operatorname{tr}\big(X^\top A\, dX\big) \\ &= \operatorname{tr}\big(X^\top A^\top dX\big) + \operatorname{tr}\big(X^\top A\, dX\big) \\ &= \operatorname{tr}\big(X^\top (A + A^\top)\, dX\big) . \end{aligned}

So M=X⊤(A+A⊤)M = X^\top(A + A^\top) and the gradient is (A+A⊤)X(A + A^\top)X. The squared Frobenius norm ∥X∥F2=tr⁡(X⊤X)\lVert X\rVert_F^2 = \operatorname{tr}(X^\top X) is the case A=IA = I, with gradient 2X2X: the derivative of the weight-decay penalty λ∥W∥F2\lambda\lVert W\rVert_F^2 of regularization.

The transpose in ∂tr⁡(AX)/∂X=A⊤\partial\operatorname{tr}(AX)/\partial X = A^\top is easy to lose. For AA with rows (1,2)(1, 2) and (3,4)(3, 4), tr⁡(AX)=∑ijAjiXij\operatorname{tr}(AX) = \sum_{ij} A_{ji} X_{ij}, so the coefficient of X12X_{12} is A21=3A_{21} = 3, the entry (1,2)(1, 2) of A⊤A^\top. A guess of AA would give 2.

The log-determinant#

The columns of XX span a parallelogram, or in nn dimensions a parallelepiped, of volume ∣det⁡X∣\lvert\det X\rvert. How much does the volume change when the columns move a little? We need one fact first. For a small matrix EE,

det⁡(I+E)=1+tr⁡E+O(∥E∥2).\det(I + E) = 1 + \operatorname{tr}E + O\big(\lVert E\rVert^2\big) .

By the Leibniz formula det⁡M=∑σsgn⁡σ∏iMiσ(i)\det M = \sum_\sigma \operatorname{sgn}\sigma \prod_i M_{i\sigma(i)}, the identity permutation contributes ∏i(1+Eii)=1+∑iEii\prod_i (1 + E_{ii}) = 1 + \sum_i E_{ii} plus products of two or more entries of EE. Every other permutation moves at least two indices, so its product contains at least two off-diagonal entries of EE and is second order. For invertible XX we factor X+dX=X(I+X−1dX)X + dX = X(I + X^{-1}dX), use the product rule det⁡(AB)=det⁡Adet⁡B\det(AB) = \det A \det B, and apply the fact with E=X−1dXE = X^{-1}dX. Since ∥X−1dX∥≤∥X−1∥ ∥dX∥\lVert X^{-1}dX\rVert \le \lVert X^{-1}\rVert\, \lVert dX\rVert, a term of second order in EE is of second order in dXdX:

det⁡(X+dX)=det⁡X det⁡(I+X−1dX)=det⁡X (1+tr⁡(X−1dX))+O(∥dX∥2).\begin{aligned} \det(X + dX) &= \det X \,\det\big(I + X^{-1}dX\big) \\ &= \det X \,\big(1 + \operatorname{tr}(X^{-1}dX)\big) + O\big(\lVert dX\rVert^2\big) . \end{aligned}

The linear part is the differential, and dividing by det⁡X\det X gives the logarithm, since dlog⁡∣t∣=dt/td\log\lvert t\rvert = dt/t:

ddet⁡X=det⁡X⋅tr⁡(X−1dX),dlog⁡∣det⁡X∣=tr⁡(X−1dX).\begin{aligned} d\det X &= \det X \cdot \operatorname{tr}\big(X^{-1}dX\big) , \\ d\log\lvert\det X\rvert &= \operatorname{tr}\big(X^{-1}dX\big) . \end{aligned}

Reading off, ∂log⁡∣det⁡X∣/∂X=X−⊤\partial \log\lvert\det X\rvert/\partial X = X^{-\top}, where X−⊤=(X−1)⊤X^{-\top} = (X^{-1})^\top, and ∂det⁡X/∂X=det⁡X⋅X−⊤\partial\det X/\partial X = \det X \cdot X^{-\top}. For a symmetric XX the first is X−1X^{-1}. The second is the matrix of cofactors. Every Leibniz product contains the entry XijX_{ij} at most once, so det⁡X\det X is affine in XijX_{ij}, and its coefficient there, ∂det⁡X/∂Xij\partial\det X/\partial X_{ij}, is by definition the cofactor CijC_{ij}. So C=det⁡X⋅X−⊤C = \det X \cdot X^{-\top}, which is the cofactor formula X−1=C⊤/det⁡XX^{-1} = C^\top/\det X. Strang (2018) reaches the gradient from that side, through the cofactor expansion along a row.

A worked example with XX of rows (2,1)(2, 1) and (0.5,1.5)(0.5, 1.5), and a change dXdX of rows (0.1,0.05)(0.1, 0.05) and (−0.05,0.1)(-0.05, 0.1):

QuantityValue
det⁡X\det X2.52.5
X−1X^{-1}, by rows(0.6,−0.4)(0.6, -0.4), (−0.2,0.8)(-0.2, 0.8)
∂det⁡X/∂X=2.5 X−⊤\partial\det X/\partial X = 2.5\,X^{-\top}, by rows(1.5,−0.5)(1.5, -0.5), (−1,2)(-1, 2)
tr⁡(X−1dX)\operatorname{tr}(X^{-1}dX)0.150.15
first-order prediction 2.5⋅1.152.5 \cdot 1.152.8752.875
exact det⁡(X+dX)\det(X + dX)2.88752.8875

The area grows by 15% to first order. The remaining 0.01250.0125 is det⁡(dX)\det(dX): for 2×22 \times 2 matrices, det⁡(X+E)=det⁡X (1+tr⁡(X−1E))+det⁡E\det(X + E) = \det X\,\big(1 + \operatorname{tr}(X^{-1}E)\big) + \det E exactly. Raising only X11X_{11} by 0.10.1 raises the determinant by exactly 1.5⋅0.1=0.151.5 \cdot 0.1 = 0.15, because the determinant is affine in each single entry, with the cofactor C11=X22=1.5C_{11} = X_{22} = 1.5 as slope.

Derivation: the exact 2 × 2 identity

Write XX with rows (a,b)(a, b) and (c,d)(c, d), and expand the 2×22 \times 2 formula for X+EX + E:

det⁡(X+E)=(a+e11)(d+e22)−(b+e12)(c+e21)=det⁡X+(d e11−c e12−b e21+a e22)+det⁡E.\begin{aligned} \det(X + E) &= (a + e_{11})(d + e_{22}) - (b + e_{12})(c + e_{21}) \\ &= \det X + \big(d\,e_{11} - c\,e_{12} - b\,e_{21} + a\,e_{22}\big) + \det E . \end{aligned}

The middle bracket is tr⁡(C⊤E)\operatorname{tr}(C^\top E) with the cofactors C11=dC_{11} = d, C12=−cC_{12} = -c, C21=−bC_{21} = -b, C22=aC_{22} = a. By the cofactor formula C⊤=det⁡X⋅X−1C^\top = \det X \cdot X^{-1}, so the bracket is det⁡Xtr⁡(X−1E)\det X \operatorname{tr}(X^{-1}E). In the example, det⁡dX=0.01+0.0025=0.0125\det dX = 0.01 + 0.0025 = 0.0125.

Figure

The differential of the determinant as a change of area

Two nearby parallelograms spanned by the columns of a matrix before and after a small changeA filled blue parallelogram with a corner at the origin and a slightly larger red outline over it, with the areas written beside it.Xe₁ = (2, 0.5)Xe₂ = (1, 1.5)0det X = 2.5 (blue area)det(X + dX) = 2.8875 (red outline)first order: 2.5 · (1 + tr(X⁻¹dX))= 2.5 · 1.15 = 2.875remainder: det(dX) = 0.0125Two nearby parallelograms spanned by the columns of a matrix before and after a small changeA filled blue parallelogram with a corner at the origin and a slightly larger red outline over it, with the areas written beside it.Xe₁Xe₂0det X = 2.5 (blue area)det(X + dX) = 2.8875 (red outline)first order: 2.5 · (1 + tr(X⁻¹dX))= 2.5 · 1.15 = 2.875remainder: det(dX) = 0.0125
The columns of X = [[2, 1], [0.5, 1.5]] span a parallelogram of area 2.5 (blue). After the change dX = [[0.1, 0.05], [−0.05, 0.1]], the columns of X + dX span area 2.8875 (red outline). The first-order prediction is 2.5 · (1 + tr(X⁻¹dX)) = 2.875; the gap, det(dX) = 0.0125, is second order.

The log-determinant appears wherever a density is normalized or transformed: −12log⁡det⁡Σ-\tfrac12\log\det\Sigma in the log-likelihood of the multivariate Gaussian, log⁡∣det⁡J∣\log\lvert\det J\rvert 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 XX−1=IXX^{-1} = I. Differentiate both sides; the right side does not change:

0=d(XX−1)=(dX) X−1+X d(X−1).\begin{aligned} 0 &= d\big(XX^{-1}\big) \\ &= (dX)\,X^{-1} + X\, d\big(X^{-1}\big) . \end{aligned}

Multiplying by X−1X^{-1} on the left gives

d(X−1)=−X−1(dX) X−1.d\big(X^{-1}\big) = -X^{-1}(dX)\,X^{-1} .

For 1×11 \times 1 matrices this is the familiar d(1/x)=−dx/x2d(1/x) = -dx/x^2. Differentiating XX−1XX^{-1} assumed that X−1X^{-1} has a differential at all; the fold checks the result directly.

Derivation: the inverse has this differential

Let EE be a small change and Y=X−1−X−1EX−1Y = X^{-1} - X^{-1}EX^{-1} the candidate. Multiply out:

(X+E) Y=I+EX−1−EX−1−EX−1EX−1=I−(EX−1)2.\begin{aligned} (X + E)\,Y &= I + EX^{-1} - EX^{-1} - EX^{-1}EX^{-1} \\ &= I - \big(EX^{-1}\big)^2 . \end{aligned}

Multiplying on the left by (X+E)−1(X + E)^{-1}, which exists for small EE because det⁡(X+E)\det(X + E) is close to det⁡X≠0\det X \ne 0:

(X+E)−1−Y=(X+E)−1(EX−1)2.(X + E)^{-1} - Y = (X + E)^{-1}\big(EX^{-1}\big)^2 .

By the cofactor formula the entries of (X+E)−1(X + E)^{-1} are polynomials in the entries divided by det⁡(X+E)\det(X + E), so they stay bounded near XX. The right side is therefore O(∥E∥2)O(\lVert E\rVert^2), and −X−1EX−1-X^{-1}EX^{-1} is the linear part of the change.

A scalar built from the inverse, such as a⊤X−1ba^\top X^{-1}b for fixed vectors aa and bb, then follows in two steps:

d(a⊤X−1b)=−a⊤X−1(dX) X−1b=−tr⁡(X−1b a⊤X−1 dX)cyclic property\begin{aligned} d\big(a^\top X^{-1}b\big) &= -a^\top X^{-1}(dX)\,X^{-1}b \\ &= -\operatorname{tr}\big(X^{-1}b\,a^\top X^{-1}\, dX\big) && \text{cyclic property} \end{aligned}

So M=−X−1ba⊤X−1M = -X^{-1}ba^\top X^{-1}, and the gradient is M⊤=−X−⊤ab⊤X−⊤M^\top = -X^{-\top}ab^\top X^{-\top}.

With XX as above, a=(1,2)a = (1, 2) and b=(1,1)b = (1, 1): X−1b=(0.2,0.6)X^{-1}b = (0.2, 0.6) and a⊤X−1b=1.4a^\top X^{-1}b = 1.4. The gradient is minus the outer product of X−⊤a=(0.2,1.2)X^{-\top}a = (0.2, 1.2) and X−1bX^{-1}b:

∂ a⊤X−1b∂X=−(0.21.2)(0.20.6)=(−0.04−0.12−0.24−0.72).\frac{\partial\, a^\top X^{-1}b}{\partial X} = -\begin{pmatrix} 0.2 \\ 1.2\end{pmatrix}\begin{pmatrix} 0.2 & 0.6\end{pmatrix} = \begin{pmatrix} -0.04 & -0.12 \\ -0.24 & -0.72\end{pmatrix} .

Raising X22X_{22} by 0.010.01 should lower the value by about 0.00720.0072.

Back to the Gaussian covariance#

Now the opening problem takes a few lines. For points x1,…,xnx_1, \dots, x_n with a known mean μ\mu, let S=∑i(xi−μ)(xi−μ)⊤S = \sum_i (x_i - \mu)(x_i - \mu)^\top. Each quadratic term of the Gaussian log-density is a scalar, hence its own trace, and the cyclic property turns it into tr⁡(Σ−1(xi−μ)(xi−μ)⊤)\operatorname{tr}\big(\Sigma^{-1}(x_i - \mu)(x_i - \mu)^\top\big). Linearity of the trace collects the sum into one trace. Up to the term with log⁡2π\log 2\pi of the density, which does not depend on Σ\Sigma,

ℓ(Σ)=−n2log⁡det⁡Σ−12∑i=1n(xi−μ)⊤Σ−1(xi−μ)=−n2log⁡det⁡Σ−12tr⁡(Σ−1S).\begin{aligned} \ell(\Sigma) &= -\frac n2 \log\det\Sigma - \frac12 \sum_{i=1}^n (x_i - \mu)^\top \Sigma^{-1}(x_i - \mu) \\ &= -\frac n2 \log\det\Sigma - \frac12 \operatorname{tr}\big(\Sigma^{-1}S\big) . \end{aligned}

A covariance matrix is positive definite, so det⁡Σ>0\det\Sigma \gt 0 and log⁡det⁡Σ=log⁡∣det⁡Σ∣\log\det\Sigma = \log\lvert\det\Sigma\rvert. The log-determinant rule handles the first term. For the second, dtr⁡(Σ−1S)=tr⁡(d(Σ−1) S)d\operatorname{tr}(\Sigma^{-1}S) = \operatorname{tr}\big(d(\Sigma^{-1})\,S\big), the inverse rule gives the second line, and the cyclic property moves dΣd\Sigma to the right end:

dℓ=−n2tr⁡(Σ−1dΣ)+12tr⁡(Σ−1(dΣ) Σ−1S)=12tr⁡((Σ−1SΣ−1−nΣ−1) dΣ).\begin{aligned} d\ell &= -\frac n2 \operatorname{tr}\big(\Sigma^{-1}d\Sigma\big) \\ &\quad + \frac12 \operatorname{tr}\big(\Sigma^{-1}(d\Sigma)\,\Sigma^{-1}S\big) \\ &= \frac12 \operatorname{tr}\Big(\big(\Sigma^{-1}S\Sigma^{-1} - n\Sigma^{-1}\big)\, d\Sigma\Big) . \end{aligned}

Only symmetric changes dΣd\Sigma keep Σ\Sigma a covariance matrix. The matrix M=Σ−1SΣ−1−nΣ−1M = \Sigma^{-1}S\Sigma^{-1} - n\Sigma^{-1} in the bracket is symmetric too, and the choice dΣ=Md\Sigma = M gives tr⁡(M2)=∥M∥F2\operatorname{tr}(M^2) = \lVert M\rVert_F^2. So the differential vanishes for every symmetric dΣd\Sigma exactly when M=0M = 0. Multiplying Σ−1SΣ−1=nΣ−1\Sigma^{-1}S\Sigma^{-1} = n\Sigma^{-1} by Σ\Sigma on both sides gives S=nΣS = n\Sigma, that is,

Σ^=1nS=1n∑i=1n(xi−μ)(xi−μ)⊤.\hat\Sigma = \frac1n S = \frac1n \sum_{i=1}^n (x_i - \mu)(x_i - \mu)^\top .

The estimate is a valid covariance when SS is positive definite, that is, when the centred points xi−μx_i - \mu span the whole space: u⊤Su=∑i((xi−μ)⊤u)2u^\top S u = \sum_i \big((x_i - \mu)^\top u\big)^2 vanishes only for a uu orthogonal to all of them. Written in the precision Λ=Σ−1\Lambda = \Sigma^{-1}, the log-likelihood is n2log⁡det⁡Λ−12tr⁡(ΛS)\tfrac n2 \log\det\Lambda - \tfrac12\operatorname{tr}(\Lambda S), and the log-determinant rule alone gives Λ−1=S/n\Lambda^{-1} = S/n, the form in which Merkulov (2024) poses the exercise.

For the three points (1,0)(1, 0), (−1,1)(-1, 1) and (0,−1)(0, -1), whose mean is 00, SS has rows (2,−1)(2, -1) and (−1,2)(-1, 2), and Σ^=S/3\hat\Sigma = S/3. The factor 1/n1/n instead of 1/(n−1)1/(n - 1) 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 z∈RKz \in \mathbb R^K the probabilities are p=softmax⁡(z)p = \operatorname{softmax}(z), with pk=ezk/∑jezjp_k = e^{z_k}/\sum_j e^{z_j}, and the loss for a one-hot label yy is L=−∑kyklog⁡pkL = -\sum_k y_k \log p_k. Two facts make the differential short. First, log⁡pk=zk−lse⁡(z)\log p_k = z_k - \operatorname{lse}(z), where lse⁡(z)=log⁡∑jezj\operatorname{lse}(z) = \log\sum_j e^{z_j} is the log-sum-exp, and ∑kyk=1\sum_k y_k = 1, so L=−y⊤z+lse⁡(z)L = -y^\top z + \operatorname{lse}(z). Second, ∂lse⁡/∂zk=ezk/∑jezj=pk\partial\operatorname{lse}/\partial z_k = e^{z_k}/\sum_j e^{z_j} = p_k, by the chain rule through the logarithm. For a linear layer z=Wx+bz = Wx + b, so that dz=(dW) x+dbdz = (dW)\,x + db:

dL=−y⊤dz+p⊤dz=(p−y)⊤dz=(p−y)⊤(dW) x+(p−y)⊤db=tr⁡(x (p−y)⊤dW)+(p−y)⊤db.\begin{aligned} dL &= -y^\top dz + p^\top dz \\ &= (p - y)^\top dz \\ &= (p - y)^\top (dW)\,x + (p - y)^\top db \\ &= \operatorname{tr}\big(x\,(p - y)^\top dW\big) + (p - y)^\top db . \end{aligned}

So ∇zL=p−y\nabla_z L = p - y, ∂L/∂W=(p−y) x⊤\partial L/\partial W = (p - y)\,x^\top and ∂L/∂b=p−y\partial L/\partial b = p - y.

Take z=(2,1,0.1)z = (2, 1, 0.1) with the true class first, y=(1,0,0)y = (1, 0, 0), and the input x=(1,−2)x = (1, -2):

QuantityValue
p=softmax⁡(z)p = \operatorname{softmax}(z)(0.659,0.242,0.099)(0.659, 0.242, 0.099)
L=−log⁡p1L = -\log p_10.4170.417
∇zL=p−y\nabla_z L = p - y(−0.341,0.242,0.099)(-0.341, 0.242, 0.099)
∂L/∂W=(p−y)x⊤\partial L/\partial W = (p - y)x^\top, by rows(−0.341,0.682)(-0.341, 0.682), (0.242,−0.485)(0.242, -0.485), (0.099,−0.197)(0.099, -0.197)

The entries of p−yp - y sum to 0, because 1⊤p=1⊤y=1\mathbf 1^\top p = \mathbf 1^\top y = 1, where 1\mathbf 1 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, ∇zlog⁡pa=y−p\nabla_z \log p_a = y - p for the action aa taken, the factor that policy gradients multiply by the return.

The route through the softmax Jacobian gives the same result with more work. From log⁡pk=zk−lse⁡(z)\log p_k = z_k - \operatorname{lse}(z), dpk=pk dlog⁡pk=pk(dzk−p⊤dz)dp_k = p_k\, d\log p_k = p_k\big(dz_k - p^\top dz\big), so dp=(diag⁡(p)−pp⊤) dzdp = \big(\operatorname{diag}(p) - pp^\top\big)\, dz. The gradient of the loss in pp is −y/p-y/p, entry by entry, and the chain rule multiplies it by the symmetric Jacobian: −diag⁡(p) y/p+p (1⊤y)=−y+p-\operatorname{diag}(p)\,y/p + p\,(\mathbf 1^\top y) = -y + p. Frameworks therefore fuse softmax and cross-entropy into one operation. It is also more stable numerically: it computes −log⁡pk=lse⁡(z)−zk-\log p_k = \operatorname{lse}(z) - z_k 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 XX, Z=XW⊤+1b⊤Z = XW^\top + \mathbf 1b^\top, the loss is the sum over examples, and summing the per-example gradients (pi−yi) xi⊤(p_i - y_i)\,x_i^\top over the rows gives ∂L/∂W=(P−Y)⊤X\partial L/\partial W = (P - Y)^\top X. It is the X⊤(P−Y)X^\top(P - Y) of the logistic regression note, with the weights stored as columns instead of rows.

The check against logistic regression#

Binary logistic regression has pi=σ(zi)p_i = \sigma(z_i), z=Xwz = Xw and the loss L(w)=−∑i[yilog⁡pi+(1−yi)log⁡(1−pi)]L(w) = -\sum_i \big[y_i \log p_i + (1 - y_i)\log(1 - p_i)\big]. With σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}), the chain rule gives σ′(z)=e−z/(1+e−z)2\sigma'(z) = e^{-z}/(1 + e^{-z})^2, and since 1−σ(z)=e−z/(1+e−z)1 - \sigma(z) = e^{-z}/(1 + e^{-z}), this is σ′=σ(1−σ)\sigma' = \sigma(1 - \sigma). Dividing by σ\sigma and by 1−σ1 - \sigma, the two kinds of terms change by

d[−log⁡σ(z)]=−(1−σ(z)) dz,d[−log⁡(1−σ(z))]=σ(z) dz.\begin{aligned} d\big[-\log\sigma(z)\big] &= -\big(1 - \sigma(z)\big)\, dz , \\ d\big[-\log\big(1 - \sigma(z)\big)\big] &= \sigma(z)\, dz . \end{aligned}

For either label the term changes by (pi−yi) dzi(p_i - y_i)\, dz_i, the binary case of p−yp - y. With dz=X dwdz = X\,dw and dpi=pi(1−pi) dzidp_i = p_i(1 - p_i)\, dz_i:

dL=(p−y)⊤X dw,d(X⊤(p−y))=X⊤SX dw,\begin{aligned} dL &= (p - y)^\top X\, dw , \\ d\big(X^\top(p - y)\big) &= X^\top S X\, dw , \end{aligned}

where S=diag⁡(pi(1−pi))S = \operatorname{diag}\big(p_i(1 - p_i)\big). So ∇L=X⊤(p−y)\nabla L = X^\top(p - y) and ∇2L=X⊤SX\nabla^2 L = X^\top S X, the gradient and the Hessian of the logistic regression note. In its worked example, with one feature x=(2,−1,0.5)x = (2, -1, 0.5), labels y=(1,0,0)y = (1, 0, 0) and w=1w = 1, the residuals are p−y=(−0.119,0.269,0.622)p - y = (-0.119, 0.269, 0.622), the gradient is −0.196-0.196, and the Hessian is ∑ipi(1−pi) xi2=0.675\sum_i p_i(1 - p_i)\, x_i^2 = 0.675.

Where it breaks#

Every formula above treats the entries of XX as independent variables. A covariance matrix is symmetric, and if its parameters are only the distinct entries, the formulas give the wrong number. Take Σ\Sigma with rows (2,s)(2, s) and (s,2)(s, 2) at s=1s = 1, so that log⁡det⁡Σ=log⁡(4−s2)\log\det\Sigma = \log(4 - s^2). The derivative in the single parameter ss is

ddslog⁡(4−s2)=−2s4−s2=−23.\frac{d}{ds}\log(4 - s^2) = -\frac{2s}{4 - s^2} = -\frac23 .

The formula ∂log⁡det⁡Σ/∂Σ=Σ−1\partial\log\det\Sigma/\partial\Sigma = \Sigma^{-1} gives −13-\tfrac13 at position (1,2)(1, 2). Both entries (1,2)(1, 2) and (2,1)(2, 1) move with ss, so the true derivative is the sum of the two, 2(Σ−1)122(\Sigma^{-1})_{12}. In general, let GG be the gradient computed as if all n2n^2 entries were independent, and let the parameters be the entries sijs_{ij} with i≤ji \le j, so that Xij=Xji=sijX_{ij} = X_{ji} = s_{ij}. The chain rule adds the two entries that move with sijs_{ij}: ∂f/∂sij=Gij+Gji\partial f/\partial s_{ij} = G_{ij} + G_{ji} for i≠ji \ne j, and GiiG_{ii} on the diagonal. In matrix form the gradient is G+G⊤−diag⁡(G)G + G^\top - \operatorname{diag}(G) (Petersen and Pedersen, 2012, Section 2.8.2, equation 138). An optimizer that updates all n2n^2 entries needs the formulas as derived here, and for a symmetric Σ\Sigma the gradients Σ−1\Sigma^{-1} and Σ−1SΣ−1\Sigma^{-1}S\Sigma^{-1} 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 ∂(a⊤x)/∂x\partial(a^\top x)/\partial x 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 X−1bX^{-1}b by a linear solve and log⁡det⁡Σ\log\det\Sigma 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.
  • df=tr⁡(M dX)df = \operatorname{tr}(M\, dX) means ∂f/∂X=M⊤\partial f/\partial X = M^\top. Get there with the product rule and the cyclic trace.
  • ∇(x⊤Ax)=(A+A⊤)x\nabla(x^\top Ax) = (A + A^\top)x;  ∇∥Ax−b∥2=2A⊤(Ax−b)\ \nabla\lVert Ax - b\rVert^2 = 2A^\top(Ax - b);  ∂tr⁡(AX)/∂X=A⊤\ \partial\operatorname{tr}(AX)/\partial X = A^\top.
  • dlog⁡∣det⁡X∣=tr⁡(X−1dX)d\log\lvert\det X\rvert = \operatorname{tr}(X^{-1}dX) and d(X−1)=−X−1(dX)X−1d(X^{-1}) = -X^{-1}(dX)X^{-1}.
  • Softmax cross-entropy: ∇zL=p−y\nabla_z L = p - y,  ∂L/∂W=(p−y)x⊤\ \partial L/\partial W = (p - y)x^\top.
  • 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 ∣det⁡J∣\lvert\det J\rvert 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 tr⁡(SX)−log⁡det⁡X\operatorname{tr}(SX) - \log\det X).
  • 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).