Gradients of Matrices
Vector Calculus
In ML, loss functions often depend on whole matrices of parameters (think weight matrices in a neural net layer). The gradient with respect to a matrix is just another matrix: frac{partial L}{partial W} in mathbb{R}^{m times n} has the same shape as W, with entry (i,j) giving frac{partial L}{partial
Matrix gradients have the same shape as the matrix parameter.
In ML, loss functions often depend on whole matrices of parameters (think weight matrices in a neural net layer). The gradient with respect to a matrix is just another matrix: has the same shape as , with entry giving .
Matrix calculus identities streamline derivations. The most-used ones: , (and when is symmetric), , and . These let us differentiate common ML losses quickly without expanding index-by-index.
Using these identities, we can rederive the normal equations. For , expanding gives . Applying the identities: . Setting this to zero yields โ the normal equations, arrived at without a single index calculation.
The denominator layout (also called 'gradient layout') matches the shape of โ the convention most ML texts and auto-diff libraries use. An alternative numerator layout transposes. Be consistent, pick one, and note PyTorch/JAX use denominator layout by default (the gradient of a loss has the same shape as the parameter).
Neural network training is one long matrix gradient computation. A single fully connected layer has where is the upstream gradient after passing through . This outer-product structure is general: the gradient of a matrix that appears in a linear-plus-nonlinear layer is always an outer product of the downstream error and the upstream activation. This is the atom of deep-learning gradient math.
Worked example โ verify $\nabla_{\mathbf{x}}(\mathbf{x}^\top A\mathbf{x}) = (A + A^\top)\mathbf{x}$: Take and . Expand , giving gradient at . Alternatively, , so โ the identity checks out.
Exercises
Put your understanding to the test. Score + streak + speed all count.
Confirm you've got it
3 quick questions. Get 2 right to mark this lesson complete.