Matrix calculus
Gradients of vector and matrix expressions without indices: the differential method, the shape convention, the trace trick, and the gradients of least squares, the log-determinant and softmax cross-entropy.
Layout: the gradient has the shape of the variable
The topic Gradients, Jacobians and Hessians gave us the gradient of a scalar loss and the chain rule as a product of Jacobians. In principle that is enough. In practice, computed entry by entry is a page of double sums, and the derivative of a layer's output with respect to its weight matrix carries three indices at once, . This topic computes such gradients in a few lines, without indices.
First we agree on shapes. Two conventions meet here.
- A Jacobian is arranged outputs × inputs: for , the matrix is , as in the previous topic.
- A gradient of a scalar has the shape of its variable: is a column in for , and is an matrix for , with entries .
For a scalar function of a vector the two differ only by a transpose: the Jacobian is the row .
Why insist on the shape of the variable? Because of the update step. Gradient descent
subtracts the gradient from the weights, so the two must have the same shape.
One example pins the convention down. For each partial derivative is , so
a column, not the row . Some books and papers use the opposite layout, and then every formula comes out transposed. Before borrowing a formula, check how the source writes this one.
The differential method
Index-free computing rests on the differential. For a function of a vector , the differential is the linear part of the change of when moves by a small :
For a scalar the previous topic already named this linear part: . Read backwards, that is the whole method: compute , bring it to the form , and read off .
Differentials obey the familiar rules. Here is a constant, and , are vector or matrix expressions of matching shapes:
The product rule keeps the factors in their order, because matrices do not commute.
Take the quadratic form with any square . The product rule gives two terms:
The first term is a number, so it equals its own transpose: . Now both terms end in :
For a symmetric (see the topic Symmetric matrices and quadratic forms) this is , the analogue of . For a non-symmetric the shortcut fails. With
we get and , while is wrong.
The chain rule turns into substitution. If depends on and depends on , write through , then replace by its own expression through .
The gradient of least squares
Least squares (see the topic Inner products, norms and orthogonality) minimizes
In linear regression the rows of are the examples, holds the weights and the targets. The residual is an intermediate variable, so we substitute in two steps. First, , because the two terms are the same number. Second, , because is a constant. Together:
The shapes agree: is and the residual lives in , so the gradient lives in , like .
Setting the gradient to zero gives . These are the normal equations, which the earlier topic found from geometry; here they come from calculus.
With the matrix from the previous block, and , the residual is and the gradient is . The large second entry says that the loss is most sensitive to , which enters both rows of .
Matrix variables and the trace trick
Now let the variable be a matrix . We need an inner product for matrices: multiply matching entries and add them up. The trace writes it compactly:
The -th diagonal entry of is , and the trace adds these up over .
The differential has one term per entry, , and this sum is the inner product of the gradient with , exactly as for vectors:
So the job is to bring to the form ; then . Two facts do the moving. A number equals its own trace, . And the trace is cyclic: whenever both products exist, since both equal . So a factor may travel from the front of a product to its back. This is the trace trick.
The simplest case is , so . A check with : , and the coefficient of is .
The case that matters most is a linear layer. Let , and let the loss depend on only through , with already known. Then and . The number is its own trace, and the cyclic property moves to the front:
The weight gradient is an outer product: the column , one entry per output, times the row , one entry per input. That is exactly the shape of . With a bias, , the same steps give .
One more identity for later. The Frobenius norm is the norm of all entries, , and its gradient is . This is the gradient of the weight-decay penalty.
The log-determinant
Some losses contain a determinant. The log-density of a Gaussian with covariance has the term , and the log-likelihood of a normalizing flow contains . We need its gradient.
For a small , factor out of the determinant:
For a small matrix , . The reason is in the topic Determinants and eigenvalues: the eigenvalues of are , their product is plus products of small numbers, and . Hence
This is already the form with , so
where . The same formula holds for when . For a symmetric covariance it is simply .
A numerical check. Take
Move by . The first-order prediction is . The exact value is . The gap is second order: for matrices it equals .
Softmax cross-entropy
A classifier with classes computes logits , turns them into probabilities with softmax, and pays the cross-entropy of the true class :
Let be the one-hot vector of class , so that . The first term contributes . For the second, the differential of a logarithm is the differential of its argument divided by the argument:
Together:
Prediction minus target, as with the residual in least squares. The linear-layer rule from the trace-trick block, with , finishes the job:
An example with and true class : , and . With the input , the first row of is .
Note what we never built: the Jacobian of the softmax. The chain ended at a scalar, so the differentials collapsed to a vector before any big matrix appeared. Deep learning frameworks fuse softmax and cross-entropy for the same reason, and for numerical stability as well.
How to check a formula
Three habits catch most mistakes in matrix calculus.
- Shapes. The gradient has the shape of the variable. A formula that returns a matrix for a variable is transposed somewhere.
- The 1-D case. Set every size to 1. Then becomes , the ordinary derivative of .
- Finite differences. Nudge one entry by a small in both directions and compare with the entry of the formula. Here has a single in position . Every formula of this topic was checked this way.
The results of the topic in one table:
| gradient | |
|---|---|
| , with | , |
| softmax cross-entropy |
Two caveats. The formulas treat all entries of as independent, so a symmetric matrix, whose and move together, needs care: the derivative in their shared value is the sum of the two entries of the formula, as in the log-determinant check. And in code, automatic differentiation computes all of this for you. Closed forms are for understanding, for checking code and for second-order methods.
We can now write a loss and its gradient. But many losses come from probabilities, and the probability of a vector is an integral over many variables: the normalizing constant of a Gaussian, the expected loss over the data. Change the variables, say in a flow, and a determinant appears. It is where the of this topic comes from. That is the next topic, Multiple integrals and change of variables.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.