Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsCalculus

Matrix calculus for ML

P1.C1145 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Every layer of a network is a matrix product, and training needs the gradient of the loss with respect to every weight matrix and bias vector. Matrix calculus is the short list of rules that gives each of these gradients in one line, plus a shape check that catches many mistakes.

  • Backpropagation through a dense layer sends the gradient back with W⊤\mathbf{W}^\top and gives the weights the gradient gx⊤\mathbf{g}\mathbf{x}^\top. (P4.8: Backpropagation: step by step with numbers)
  • A network built from scratch in NumPy writes each of these rules as one line of code. (P4.10: Build an MLP from scratch (NumPy), coming soon)
  • Linear regression has the gradient 2X⊤(Xw−y)2\mathbf{X}^\top(\mathbf{X}\mathbf{w}-\mathbf{y}), and setting it to zero gives the normal equations. (P3.A2: Linear regression, coming soon)
  • A softmax classifier has the gradient p−y\mathbf{p}-\mathbf{y} with respect to its scores. (P3.A8: Softmax regression, coming soon)
  • Autograd libraries implement rules like these, one for each kind of node in the graph. (P2.6: PyTorch tensors and autograd, coming soon)

Before this: The gradient, Vector functions and the Jacobian, Matrix multiplication, Transpose, symmetric and orthogonal matrices

After this lesson you can

  • State this site's layout (the gradient of a scalar has the shape of the variable, and a Jacobian is m×nm\times n), say that books differ, and use the shape check on any gradient
  • Derive a matrix gradient by nudging the variable, expanding, and keeping the part that is linear in the nudge, then verify it with a central difference
  • Write the gradients of a⊤x\mathbf{a}^\top\mathbf{x}, ∥x∥2\lVert\mathbf{x}\rVert^2, ∥x∥\lVert\mathbf{x}\rVert, x⊤Ax\mathbf{x}^\top\mathbf{A}\mathbf{x} and ∥Xw−y∥2\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2, and say when 2Ax2\mathbf{A}\mathbf{x} is correct
  • Write the backward pass of a dense layer (one example and a batch), of an elementwise function, and of softmax with cross-entropy, and recognise the common shape bugs

P1.C7 found that a dense layer sends the gradient back through W⊤\mathbf{W}^\top, and P1.C5 said that the gradient for a weight matrix is a matrix of the same shape. This lesson keeps both promises, and adds the rest of the short list: the few rules that give the gradients of many of the layers and losses you will meet.

Why a list? A network has millions of weights, and people do not write the sums out one weight at a time. The rules say it in one line, such as W⊤g\mathbf{W}^\top\mathbf{g}. A rule is only useful if you can trust it, so each one below comes with the shapes of its pieces and a number check.

Two layout conventions and one habit

Take a scalar loss LL that depends on a vector x\mathbf{x} with nn entries. Its gradient has nn entries (P1.C5). Should they be written as a column or a row? And for a matrix W\mathbf{W}, should the gradient be shaped like W\mathbf{W} or like W⊤\mathbf{W}^\top? Both choices are in use, and this site picks the following.

  • Gradient of a scalar: the shape of the variable. ∇xL\nabla_{\mathbf{x}}L is a column with the same shape as x\mathbf{x}, and ∇WL\nabla_{\mathbf{W}}L is a matrix with the same shape as W\mathbf{W}, with entry ∂L∂Wij\frac{\partial L}{\partial W_{ij}} at position (i,j)(i,j). This is called the denominator layout, because the shape comes from the variable we differentiate by. It makes the update W←W−η∇WL\mathbf{W}\leftarrow\mathbf{W}-\eta\nabla_{\mathbf{W}}L a plain subtraction of two arrays of one shape.
  • Jacobian of a vector function: m×nm\times n. For f:Rn→Rm\mathbf{f}:\mathbb{R}^n\to\mathbb{R}^m, the Jacobian has one row per output and one column per input (P1.C7). This is the numerator layout.

Many books use the numerator layout for everything, so the gradient of a scalar becomes a row, and their formulas show a transpose where ours do not. Neither is wrong: the numbers are the same, only the arrangement differs. When you read a formula in another source, find out which layout it uses before comparing.

From the denominator layout comes a habit that catches many mistakes, the shape check:

The check is cheap, and it often forces the right formula. Later we meet a 4×54\times5 matrix W\mathbf{W}, a vector g\mathbf{g} with 44 entries and a vector x\mathbf{x} with 55 entries. Which product of g\mathbf{g} and x\mathbf{x} has the shape of W\mathbf{W}? Only gx⊤\mathbf{g}\mathbf{x}^\top (4×14\times1 times 1×51\times5). But the check is not a proof: when the matrices are square, wrong formulas can keep the right shape. So every rule here also gets a numeric check.

The method: nudge, expand, keep the linear part

P1.C5’s first-order approximation says that for a small nudge Δ\boldsymbol{\Delta} of the input,

L(x+Δ)≈L(x)+∇L⋅Δ.L(\mathbf{x}+\boldsymbol{\Delta})\approx L(\mathbf{x})+\nabla L\cdot\boldsymbol{\Delta}.

For a matrix variable the same holds, if the dot product is taken entry by entry. For two matrices of the same shape write ⟨G,Δ⟩=∑i,jGijΔij\langle\mathbf{G},\boldsymbol{\Delta}\rangle=\sum_{i,j}G_{ij}\Delta_{ij}: multiply matching entries and add. It is the dot product you would get after listing both matrices’ entries in one long column. Then

L(W+Δ)≈L(W)+⟨∇WL,Δ⟩.L(\mathbf{W}+\boldsymbol{\Delta})\approx L(\mathbf{W})+\langle\nabla_{\mathbf{W}}L,\boldsymbol{\Delta}\rangle.

This gives a method that works for every rule below:

  1. Replace the variable by (variable + Δ+\,\boldsymbol{\Delta}) and expand.
  2. Drop every term that contains Δ\boldsymbol{\Delta} twice (such terms are tiny: halve the nudge and they shrink four times).
  3. Write what remains as ⟨ something,Δ⟩\langle\,\text{something},\boldsymbol{\Delta}\rangle. That something is the gradient.

Two warm-ups. First, L=a⊤xL=\mathbf{a}^\top\mathbf{x} (a number: the dot product of P1.B3). Then L(x+Δ)=a⊤x+a⊤ΔL(\mathbf{x}+\boldsymbol{\Delta})=\mathbf{a}^\top\mathbf{x}+\mathbf{a}^\top\boldsymbol{\Delta}, so ∇xL=a\nabla_{\mathbf{x}}L=\mathbf{a}, which is the result of P1.C4 and P1.C5. Second, L=x⊤x=∥x∥2L=\mathbf{x}^\top\mathbf{x}=\lVert\mathbf{x}\rVert^2:

L(x+Δ)=(x+Δ)⊤(x+Δ)=x⊤x+x⊤Δ+Δ⊤x+Δ⊤Δ=x⊤x+2 x⊤Δ+Δ⊤Δ.\begin{aligned} L(\mathbf{x}+\boldsymbol{\Delta})&=(\mathbf{x}+\boldsymbol{\Delta})^\top(\mathbf{x}+\boldsymbol{\Delta})\\ &=\mathbf{x}^\top\mathbf{x}+\mathbf{x}^\top\boldsymbol{\Delta}\\ &\quad+\boldsymbol{\Delta}^\top\mathbf{x}+\boldsymbol{\Delta}^\top\boldsymbol{\Delta}\\ &=\mathbf{x}^\top\mathbf{x}+2\,\mathbf{x}^\top\boldsymbol{\Delta}+\boldsymbol{\Delta}^\top\boldsymbol{\Delta}. \end{aligned}

The two middle terms are equal because a number equals its own transpose: x⊤Δ=Δ⊤x\mathbf{x}^\top\boldsymbol{\Delta}=\boldsymbol{\Delta}^\top\mathbf{x}. The last term has Δ\boldsymbol{\Delta} twice, so it is dropped. What is left is ⟨2x,Δ⟩\langle2\mathbf{x},\boldsymbol{\Delta}\rangle, so ∇∥x∥2=2x\nabla\lVert\mathbf{x}\rVert^2=2\mathbf{x}. Check with x=(3,4)\mathbf{x}=(3,4) and Δ=(0.01,0.02)\boldsymbol{\Delta}=(0.01,0.02): the true value is (3.01)2+(4.02)2=25.2205(3.01)^2+(4.02)^2=25.2205, and the first-order estimate is 25+2(3⋅0.01+4⋅0.02)=25.2225+2(3\cdot0.01+4\cdot0.02)=25.22. The difference is 0.0005=Δ⊤Δ0.0005=\boldsymbol{\Delta}^\top\boldsymbol{\Delta}, the dropped term.

The cheat sheet

Here is the whole list. Vectors are columns. In all lines LL is a number, and g\mathbf{g} or G\mathbf{G} is the gradient that arrives from the rest of the network (the gradient that the layers above send back). Each rule is derived or checked below. The letter y\mathbf{y} is the layer output in the dense-layer lines and the target in the least-squares and softmax lines.

  • Linear. L=a⊤xL=\mathbf{a}^\top\mathbf{x} gives ∇xL=a\nabla_{\mathbf{x}}L=\mathbf{a}, an n×1n\times1 column.
  • Squared length. L=∥x∥2L=\lVert\mathbf{x}\rVert^2 gives 2x2\mathbf{x}.
  • Length. L=∥x∥L=\lVert\mathbf{x}\rVert gives x/∥x∥\mathbf{x}/\lVert\mathbf{x}\rVert, for x≠0\mathbf{x}\neq\mathbf{0}.
  • Quadratic form. L=x⊤AxL=\mathbf{x}^\top\mathbf{A}\mathbf{x} gives (A+A⊤)x(\mathbf{A}+\mathbf{A}^\top)\mathbf{x}, which equals 2Ax2\mathbf{A}\mathbf{x} when A\mathbf{A} is symmetric.
  • Least squares. L=∥Xw−y∥2L=\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2 gives 2X⊤(Xw−y)2\mathbf{X}^\top(\mathbf{X}\mathbf{w}-\mathbf{y}), a d×1d\times1 column. For the average over NN examples the factor is 2N\frac2N.
  • Dense layer. With y=Wx+b\mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b} and g=∇yL\mathbf{g}=\nabla_{\mathbf{y}}L (an m×1m\times1 column):
    • ∇xL=W⊤g\nabla_{\mathbf{x}}L=\mathbf{W}^\top\mathbf{g}, which is n×1n\times1;
    • ∇WL=gx⊤\nabla_{\mathbf{W}}L=\mathbf{g}\mathbf{x}^\top, which is m×nm\times n;
    • ∇bL=g\nabla_{\mathbf{b}}L=\mathbf{g}, which is m×1m\times1.
  • Dense layer on a batch. With Y=XW⊤+b\mathbf{Y}=\mathbf{X}\mathbf{W}^\top+\mathbf{b} and G=∇YL\mathbf{G}=\nabla_{\mathbf{Y}}L (N×mN\times m):
    • ∇WL=G⊤X\nabla_{\mathbf{W}}L=\mathbf{G}^\top\mathbf{X}, which is m×nm\times n;
    • ∇XL=GW\nabla_{\mathbf{X}}L=\mathbf{G}\mathbf{W}, which is N×nN\times n;
    • ∇bL=\nabla_{\mathbf{b}}L= the column sums of G\mathbf{G}, which is m×1m\times1.
  • Elementwise function. With a=σ(z)\mathbf{a}=\sigma(\mathbf{z}) applied entry by entry, ∇zL=g⊙σ′(z)\nabla_{\mathbf{z}}L=\mathbf{g}\odot\sigma'(\mathbf{z}), where ⊙\odot multiplies matching entries.
  • Softmax with cross-entropy. ∇zL=p−y\nabla_{\mathbf{z}}L=\mathbf{p}-\mathbf{y}, where p=softmax(z)\mathbf{p}=\mathrm{softmax}(\mathbf{z}) and y\mathbf{y} is the one-hot target.

Before the derivations, try the shape checker. For each expression it shows the shape of every quantity, the formula with its shape arithmetic, and a check of the formula against a central difference (nudging each entry up and down by 0.000010.00001) on the same numbers.

Shape checker: gradient formula, its shape, and a numeric check

L = gᵀ(Wx)

inputs n 3
outputs m 2
  • W 2×3 weights
  • x 3×1 input (the gradient is taken for this one)
  • g 2×1 gradient from above, ∂L/∂y
  • L 1×1 a single number (scalar)

The gradient must be 3×1, the shape of x.

Formula
∂L/∂x = Wᵀ g
Shapes: 3×2 · 2×1 → 3×1
Formula gives
−2−10
Central difference gives
−2−10

Shape 3×1 matches x. The formula agrees with the central difference: the largest difference is 1.6e-11.

Show the numbers used
  • W = [[1, 2, 3], [4, 5, 6]]
  • x = (1, 0, −1)
  • g = (2, −1)

Start with the lesson numbers, then switch the mistake on for each expression. With square sizes (for example n = m) some mistakes keep the right shape, and only the numbers give them away. The central difference nudges each entry by 0.00001 up and down on the same numbers.

The shape checker. Pick an expression and set the sizes with the − and + buttons. The list shows the shape of every quantity, and the line below it says which shape the gradient must have. The orange box is the formula with the shapes of its pieces. Below it, the formula's numbers (orange) are placed beside the central-difference numbers, and the status line compares them. “Lesson numbers” uses the numbers of this lesson, and “New random numbers” draws new ones between −2 and 2. “Show a common mistake” replaces the formula by a plausible wrong one, and the status says whether the shape check, the numeric check, both or neither catches it.

Things to try with the shape checker:

  1. Start with Wx\mathbf{W}\mathbf{x} for x\mathbf{x} at the lesson numbers: the formula W⊤g\mathbf{W}^\top\mathbf{g} gives (−2,−1,0)(-2,-1,0), the shape 3×13\times1 of x\mathbf{x}, and the central difference agrees.
  2. Switch on the mistake. Wg\mathbf{W}\mathbf{g} is not defined, since W\mathbf{W} is 2×32\times3 and g\mathbf{g} is 2×12\times1. Now raise mm to 33 so that W\mathbf{W} is square: the product exists, the shape fits, and the numbers are wrong. Only the numeric check catches it.
  3. Choose Wx\mathbf{W}\mathbf{x} for W\mathbf{W} with the mistake on: xg⊤\mathbf{x}\mathbf{g}^\top has the shape 3×23\times2 instead of 2×32\times3. Make nn and mm equal and the shape fits again.
  4. Choose x⊤Ax\mathbf{x}^\top\mathbf{A}\mathbf{x} with the mistake 2Ax2\mathbf{A}\mathbf{x}. The shape fits and the numbers are wrong. Tick “Make A symmetric” and the status says the mistake is harmless here, because the two formulas agree for symmetric A\mathbf{A}.
  5. Choose the batch layer for b\mathbf{b} at the lesson numbers: the mistaken row sums have the right shape only because N=m=2N=m=2. Raise NN to 33 and see the shape fail.

Dense layer, from components

Take y=Wx+b\mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b} with W\mathbf{W} of size m×nm\times n (P1.B5), so output ii is yi=∑jWijxj+biy_i=\sum_j W_{ij}x_j+b_i. The rest of the network turns y\mathbf{y} into the loss LL, and the gradient g=∇yL\mathbf{g}=\nabla_{\mathbf{y}}L with entries gi=∂L∂yig_i=\frac{\partial L}{\partial y_i} has arrived. We want the gradients for the layer’s own variables. The chain rule (P1.C3) turns each into one product.

For the weights. WijW_{ij} affects only output ii, and it does so by the amount xjx_j: ∂yi∂Wij=xj\frac{\partial y_i}{\partial W_{ij}}=x_j. Therefore

∂L∂Wij=∂L∂yi ∂yi∂Wij=gi xj.\frac{\partial L}{\partial W_{ij}}=\frac{\partial L}{\partial y_i}\,\frac{\partial y_i}{\partial W_{ij}}=g_i\,x_j.

Entry (i,j)(i,j) is gixjg_ix_j: a column g\mathbf{g} times a row x⊤\mathbf{x}^\top. This matrix is the outer product gx⊤\mathbf{g}\mathbf{x}^\top (P1.B6). In words: the gradient of a weight is (the gradient arriving at its output) times (the input it multiplies).

For the input. xjx_j affects every output, through the weights in column jj, so the effects add: ∂L∂xj=∑igiWij\frac{\partial L}{\partial x_j}=\sum_i g_iW_{ij}. That is entry jj of W⊤g\mathbf{W}^\top\mathbf{g}. For the bias, ∂yi∂bi=1\frac{\partial y_i}{\partial b_i}=1, so ∇bL=g\nabla_{\mathbf{b}}L=\mathbf{g}.

The numbers of P1.C7 and P1.B15: W=(123456)\mathbf{W}=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix}, x=(1,0,−1)\mathbf{x}=(1,0,-1), and g=(2,−1)\mathbf{g}=(2,-1), which is the gradient of the made-up loss L=2y1−y2L=2y_1-y_2. Then

∇xL=W⊤g=(−2,−1,0),∇WL=gx⊤=(20−2−101),∇bL=g=(2,−1).\begin{aligned} \nabla_{\mathbf{x}}L&=\mathbf{W}^\top\mathbf{g}=(-2,-1,0),\\ \nabla_{\mathbf{W}}L&=\mathbf{g}\mathbf{x}^\top=\begin{pmatrix}2&0&-2\\-1&0&1\end{pmatrix},\\ \nabla_{\mathbf{b}}L&=\mathbf{g}=(2,-1). \end{aligned}

Check the middle line by nudging. The entry W23W_{23} (row 2, column 3) is 66. Raise it by 0.0010.001: then y2y_2 changes by x3⋅0.001=−0.001x_3\cdot0.001=-0.001, and L=2y1−y2L=2y_1-y_2 changes by +0.001+0.001. So ∂L∂W23=1\frac{\partial L}{\partial W_{23}}=1, which is g2x3=(−1)(−1)g_2x_3=(-1)(-1), the entry in row 2, column 3 of gx⊤\mathbf{g}\mathbf{x}^\top. The entries in the middle column are 00 because x2=0x_2=0: a weight on a zero input cannot change the loss.

The shapes force the formula. W\mathbf{W} is m×nm\times n, g\mathbf{g} is m×1m\times1 and x\mathbf{x} is n×1n\times1. The only way to build an m×nm\times n matrix from g\mathbf{g} and x\mathbf{x} is gx⊤\mathbf{g}\mathbf{x}^\top (xg⊤\mathbf{x}\mathbf{g}^\top is n×mn\times m). To build an n×1n\times1 vector from W\mathbf{W} and g\mathbf{g} you need W⊤g\mathbf{W}^\top\mathbf{g} (Wg\mathbf{W}\mathbf{g} is not defined unless n=mn=m). The shape check was nearly enough to find both formulas.

The same layer on a batch

Real training handles a batch of NN examples at once. Stack them as the rows of X\mathbf{X} (N×nN\times n), as in P1.B15, so the layer is Y=XW⊤+b\mathbf{Y}=\mathbf{X}\mathbf{W}^\top+\mathbf{b}, with the bias added to every row. The gradient arriving at Y\mathbf{Y} is G\mathbf{G} (N×mN\times m), whose row kk is the g\mathbf{g} of example kk. The loss adds the examples, so the weight gradients add:

∇WL=∑k=1Ngkxk⊤=G⊤X.\nabla_{\mathbf{W}}L=\sum_{k=1}^{N}\mathbf{g}_k\mathbf{x}_k^\top=\mathbf{G}^\top\mathbf{X}.

The right-hand side is one matrix product: its (i,j)(i,j) entry is ∑kGkiXkj\sum_kG_{ki}X_{kj}, the same sum. Because the examples are the rows of X\mathbf{X} and of G\mathbf{G}, the sum over examples happens inside the matrix product. The other two are ∇XL=GW\nabla_{\mathbf{X}}L=\mathbf{G}\mathbf{W} (row kk is (W⊤gk)⊤(\mathbf{W}^\top\mathbf{g}_k)^\top, the single-example result) and ∇bL=∑kgk\nabla_{\mathbf{b}}L=\sum_k\mathbf{g}_k, the column sums of G\mathbf{G}. The bias is shared by all examples, so its gradient is added over them and has the shape of b\mathbf{b}, not one row per example.

With X=(10−1210)\mathbf{X}=\begin{pmatrix}1&0&-1\\2&1&0\end{pmatrix} and G=(2−101)\mathbf{G}=\begin{pmatrix}2&-1\\0&1\end{pmatrix} (the numbers of P1.B15):

G⊤X=(20−2111),GW=(−2−10456),\begin{aligned} \mathbf{G}^\top\mathbf{X}&=\begin{pmatrix}2&0&-2\\1&1&1\end{pmatrix},\\ \mathbf{G}\mathbf{W}&=\begin{pmatrix}-2&-1&0\\4&5&6\end{pmatrix}, \end{aligned}

and the column sums of G\mathbf{G} are (2,0)(2,0).

The first row of GW\mathbf{G}\mathbf{W} is the single-example answer (−2,−1,0)(-2,-1,0). The first matrix is the single-example gx⊤\mathbf{g}\mathbf{x}^\top of above plus the second example’s (000210)\begin{pmatrix}0&0&0\\2&1&0\end{pmatrix}.

Two remarks. If the loss is an average over the batch, the factor 1N\frac1N is already inside G\mathbf{G}, because G\mathbf{G} is the gradient of that loss. And if a library stores the weights the other way round, as an n×mn\times m matrix with Y=XW\mathbf{Y}=\mathbf{X}\mathbf{W}, the formulas change with the shapes (exercise 8). The shape check finds them again.

Quadratics: x⊤Ax\mathbf{x}^\top\mathbf{A}\mathbf{x}, the length, and least squares

The quadratic form. For a square n×nn\times n matrix A\mathbf{A}, L=x⊤Ax=∑i,jAijxixjL=\mathbf{x}^\top\mathbf{A}\mathbf{x}=\sum_{i,j}A_{ij}x_ix_j is a number. Nudge x\mathbf{x}:

L(x+Δ)=(x+Δ)⊤A(x+Δ)=x⊤Ax+x⊤AΔ+Δ⊤Ax+Δ⊤AΔ.\begin{aligned} L(\mathbf{x}+\boldsymbol{\Delta})&=(\mathbf{x}+\boldsymbol{\Delta})^\top\mathbf{A}(\mathbf{x}+\boldsymbol{\Delta})\\ &=\mathbf{x}^\top\mathbf{A}\mathbf{x}+\mathbf{x}^\top\mathbf{A}\boldsymbol{\Delta}\\ &\quad+\boldsymbol{\Delta}^\top\mathbf{A}\mathbf{x}+\boldsymbol{\Delta}^\top\mathbf{A}\boldsymbol{\Delta}. \end{aligned}

The last term is dropped. The third term is a number, so it equals its own transpose, Δ⊤Ax=x⊤A⊤Δ\boldsymbol{\Delta}^\top\mathbf{A}\mathbf{x}=\mathbf{x}^\top\mathbf{A}^\top\boldsymbol{\Delta} (P1.B10). The linear part is therefore x⊤(A+A⊤)Δ=⟨(A+A⊤)x,Δ⟩\mathbf{x}^\top(\mathbf{A}+\mathbf{A}^\top)\boldsymbol{\Delta}=\langle(\mathbf{A}+\mathbf{A}^\top)\mathbf{x},\boldsymbol{\Delta}\rangle. The matrix A+A⊤\mathbf{A}+\mathbf{A}^\top is symmetric, so x⊤(A+A⊤)=((A+A⊤)x)⊤\mathbf{x}^\top(\mathbf{A}+\mathbf{A}^\top)=\left((\mathbf{A}+\mathbf{A}^\top)\mathbf{x}\right)^\top. So

∇x(x⊤Ax)=(A+A⊤)x.\nabla_{\mathbf{x}}(\mathbf{x}^\top\mathbf{A}\mathbf{x})=(\mathbf{A}+\mathbf{A}^\top)\mathbf{x}.

If A\mathbf{A} is symmetric (A⊤=A\mathbf{A}^\top=\mathbf{A}, P1.B10), this is 2Ax2\mathbf{A}\mathbf{x}, which is the familiar-looking “derivative of ax2ax^2 is 2ax2ax”. For a non-symmetric A\mathbf{A} the shortcut is wrong. Take A=(2103)\mathbf{A}=\begin{pmatrix}2&1\\0&3\end{pmatrix} and x=(1,2)\mathbf{x}=(1,2). Then Ax=(4,6)\mathbf{A}\mathbf{x}=(4,6) and x⊤Ax=16\mathbf{x}^\top\mathbf{A}\mathbf{x}=16. By components, L=2x12+x1x2+3x22L=2x_1^2+x_1x_2+3x_2^2, whose partial derivatives are 4x1+x24x_1+x_2 and x1+6x2x_1+6x_2, which are (6,13)(6,13) at (1,2)(1,2). The formula agrees:

(A+A⊤)x=(4116)(12)=(613),\begin{aligned} (\mathbf{A}+\mathbf{A}^\top)\mathbf{x}&=\begin{pmatrix}4&1\\1&6\end{pmatrix}\begin{pmatrix}1\\2\end{pmatrix}\\ &=\begin{pmatrix}6\\13\end{pmatrix}, \end{aligned}

while the shortcut gives 2Ax=(8,12)2\mathbf{A}\mathbf{x}=(8,12). Nudge x1x_1 from 11 to 1.0011.001: LL rises from 1616 to 16.00600216.006002, which is 6×0.0016\times0.001 and not 8×0.0018\times0.001.

The length. ∥x∥=x⊤x\lVert\mathbf{x}\rVert=\sqrt{\mathbf{x}^\top\mathbf{x}} is a square root of the previous case, so the chain rule (P1.C3) gives 12∥x∥⋅2x\frac{1}{2\lVert\mathbf{x}\rVert}\cdot2\mathbf{x}:

∇∥x∥=x∥x∥(x≠0).\nabla\lVert\mathbf{x}\rVert=\frac{\mathbf{x}}{\lVert\mathbf{x}\rVert}\qquad(\mathbf{x}\neq\mathbf{0}).

It is the unit vector along x\mathbf{x}: for x=(3,4)\mathbf{x}=(3,4) it is (0.6,0.8)(0.6,0.8). Its length is 11, which makes sense: moving outward along x\mathbf{x} by a distance hh lengthens x\mathbf{x} by hh. At x=0\mathbf{x}=\mathbf{0} the length has a corner (a cone), like ∣x∣|x| in P1.C1, and there is no gradient. The squared length ∥x∥2\lVert\mathbf{x}\rVert^2 has no such problem: its gradient 2x2\mathbf{x} is 0\mathbf{0} at the origin.

Least squares. For NN examples with features as the rows of X\mathbf{X} (N×dN\times d), targets y\mathbf{y} (N×1N\times1) and weights w\mathbf{w} (d×1d\times1), the predictions are Xw\mathbf{X}\mathbf{w} and the residual is r=Xw−y\mathbf{r}=\mathbf{X}\mathbf{w}-\mathbf{y}, which has NN entries. The loss L=∥r∥2L=\lVert\mathbf{r}\rVert^2 is built from two rules we have. First, ∇rL=2r\nabla_{\mathbf{r}}L=2\mathbf{r} (the squared length). Second, r\mathbf{r} is a linear function of w\mathbf{w} through X\mathbf{X}, so the rule “W⊤\mathbf{W}^\top times the arriving gradient” applies with X\mathbf{X} in the role of W\mathbf{W} and 2r2\mathbf{r} as g\mathbf{g}:

∇w∥Xw−y∥2=2 X⊤(Xw−y).\nabla_{\mathbf{w}}\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2=2\,\mathbf{X}^\top(\mathbf{X}\mathbf{w}-\mathbf{y}).

The shapes are (d×N)(N×1)=d×1(d\times N)(N\times1)=d\times1, the shape of w\mathbf{w}. Expanding the bracket gives 2X⊤Xw−2X⊤y2\mathbf{X}^\top\mathbf{X}\mathbf{w}-2\mathbf{X}^\top\mathbf{y}, the form used in P1.B11. For the mean squared error (P0.2), the factor is 2N\frac2N.

Use the P0.2 data (1,2),(2,3),(3,7)(1,2),(2,3),(3,7). Give each example the features (x,1)(x,1), so that w=(w,b)\mathbf{w}=(w,b), and write X=(112131)\mathbf{X}=\begin{pmatrix}1&1\\2&1\\3&1\end{pmatrix}, y=(2,3,7)\mathbf{y}=(2,3,7). At w=(1,0)\mathbf{w}=(1,0):

r=Xw−y=(−1,−1,−4),X⊤r=(−15,−6),∇wL=2X⊤r=(−30,−12).\begin{aligned} \mathbf{r}&=\mathbf{X}\mathbf{w}-\mathbf{y}=(-1,-1,-4),\\ \mathbf{X}^\top\mathbf{r}&=(-15,-6),\\ \nabla_{\mathbf{w}}L&=2\mathbf{X}^\top\mathbf{r}=(-30,-12). \end{aligned}

The first entry of X⊤r\mathbf{X}^\top\mathbf{r} is 1(−1)+2(−1)+3(−4)=−151(-1)+2(-1)+3(-4)=-15 and the second is −1−1−4=−6-1-1-4=-6.

The sum of squared residuals is 1818 and the mean is 66, the loss of P1.C5. The mean’s gradient is 23X⊤r=(−10,−4)\frac23\mathbf{X}^\top\mathbf{r}=(-10,-4), exactly the ∇L(1,0)\nabla\mathcal{L}(1,0) of P1.C5, and the sum’s gradient is 33 times larger. This agrees with the per-example gradients (−2,−2)(-2,-2), (−4,−2)(-4,-2), (−24,−8)(-24,-8) of P1.C5, which add to (−30,−12)(-30,-12).

Setting the gradient to zero gives X⊤Xw=X⊤y\mathbf{X}^\top\mathbf{X}\mathbf{w}=\mathbf{X}^\top\mathbf{y}, the normal equations of P1.B11, and with these data (14663)w=(29,12)\begin{pmatrix}14&6\\6&3\end{pmatrix}\mathbf{w}=(29,12) has the solution (2.5,−1)(2.5,-1), the bottom of the loss in P1.C5. P3.A2 compares this one-step solution with gradient descent.

Elementwise functions and softmax with cross-entropy

An elementwise function. If a=σ(z)\mathbf{a}=\sigma(\mathbf{z}) applies a function to each entry, output ii depends only on input ii, so the Jacobian is diagonal (P1.C7) and the vector-Jacobian product is an entry-by-entry product:

∇zL=g⊙σ′(z).\nabla_{\mathbf{z}}L=\mathbf{g}\odot\sigma'(\mathbf{z}).

Take the sigmoid layer of P1.C7: W=(2−112)\mathbf{W}=\begin{pmatrix}2&-1\\1&2\end{pmatrix}, b=(0.5,−1)\mathbf{b}=(0.5,-1), x=(0.5,0.5)\mathbf{x}=(0.5,0.5), so z=Wx+b=(1,0.5)\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b}=(1,0.5), and the gradient g=(1,−1)\mathbf{g}=(1,-1) arrives at the outputs. The slopes are σ′(z)=(0.1966,0.2350)\sigma'(\mathbf{z})=(0.1966,0.2350), so the gradient at z\mathbf{z} is δ=g⊙σ′(z)=(0.1966,−0.2350)\boldsymbol{\delta}=\mathbf{g}\odot\sigma'(\mathbf{z})=(0.1966,-0.2350). Now the dense-layer rules apply to δ\boldsymbol{\delta}:

∇xL=W⊤δ=(0.158,−0.667),∇WL=δx⊤=(0.09830.0983−0.1175−0.1175),∇bL=δ.\begin{aligned} \nabla_{\mathbf{x}}L&=\mathbf{W}^\top\boldsymbol{\delta}=(0.158,-0.667),\\ \nabla_{\mathbf{W}}L&=\boldsymbol{\delta}\mathbf{x}^\top\\ &=\begin{pmatrix}0.0983&0.0983\\-0.1175&-0.1175\end{pmatrix},\\ \nabla_{\mathbf{b}}L&=\boldsymbol{\delta}. \end{aligned}

The first line is the (0.158,−0.667)(0.158,-0.667) of P1.C7. These three lines are the whole backward step of a dense layer with an activation: scale by the slope, then multiply by W⊤\mathbf{W}^\top, by x⊤\mathbf{x}^\top, or keep it for the bias. P4.10 builds a network from this step.

Softmax with cross-entropy. P1.C7 derived the softmax Jacobian diag(p)−pp⊤\mathrm{diag}(\mathbf{p})-\mathbf{p}\mathbf{p}^\top and used it to pull back the cross-entropy gradient. We can reach the same result with no Jacobian at all. For scores z\mathbf{z} and the correct class kk, the loss is L=−ln⁡pkL=-\ln p_k, with pk=ezk/∑jezjp_k=\mathrm{e}^{z_k}/\sum_j\mathrm{e}^{z_j}, so

L=−zk+ln⁡∑jezj.L=-z_k+\ln\sum_j\mathrm{e}^{z_j}.

The first term has the derivative −1-1 with respect to zkz_k and 00 with respect to the others. The derivative of the second term with respect to ziz_i is ezi/∑jezj=pi\mathrm{e}^{z_i}/\sum_j\mathrm{e}^{z_j}=p_i (the chain rule on ln⁡\ln). Therefore

∇zL=p−y,\nabla_{\mathbf{z}}L=\mathbf{p}-\mathbf{y},

where y\mathbf{y} is the one-hot target: 11 at position kk, 00 elsewhere. For z=(1,2,3)\mathbf{z}=(1,2,3) and the third class correct, p=(0.0900,0.2447,0.6652)\mathbf{p}=(0.0900,0.2447,0.6652), L=−ln⁡0.6652=0.4076L=-\ln0.6652=0.4076 and

∇zL=(0.0900,  0.2447,  −0.3348),\nabla_{\mathbf{z}}L=(0.0900,\;0.2447,\;-0.3348),

the result that P1.C7’s vector-Jacobian product gave. Read it: the entry for the correct class is negative, so raising that score lowers the loss, and every other entry is positive, so raising a wrong class’s score raises the loss. The entries add up to 00, because adding the same number to every score changes nothing. The size of each entry is the probability error. The gradient is 0\mathbf{0} only if p=y\mathbf{p}=\mathbf{y}, which a softmax with finite scores cannot reach exactly. P3.A8 uses this gradient for softmax regression.

Verifying a gradient numerically

Every rule above can be tested the way P1.C5 tested a gradient: nudge each entry of the variable up and down by a small hh and divide the change in LL by 2h2h. A matrix gets the same treatment entry by entry, and costs two evaluations of LL per entry, which is too slow for a large model but cheap for a test on small random numbers. The habit has two steps: compare the shape first, then compare the numbers.

With h=10−5h=10^{-5} and ordinary floating-point numbers, a correct formula usually agrees to about 10−810^{-8} or better. Much larger differences point to a bug. A mistake that is small but not zero, such as a missing 1N\frac1N, shows up as a ratio: if your gradient is exactly a constant times the numeric one, look for a lost factor.

Deep-learning libraries do the same job with automatic differentiation (P1.C10). In PyTorch, each tensor created with requires_grad=True gets a .grad of the same shape as the tensor. This runs in Colab or on your machine, not in the browser here:

import torch
W = torch.tensor(
    [[1., 2, 3], [4, 5, 6]],
    requires_grad=True)
x = torch.tensor(
    [1., 0, -1], requires_grad=True)
g = torch.tensor([2., -1])
L = g @ (W @ x)   # made-up loss
L.backward()
print(W.grad)     # a 2x3 matrix
print(x.grad)     # 3 entries

The loss is the number 2y1−y22y_1-y_2. The two prints show (20−2−101)\begin{pmatrix}2&0&-2\\-1&0&1\end{pmatrix} and (−2,−1,0)(-2,-1,0), which are gx⊤\mathbf{g}\mathbf{x}^\top and W⊤g\mathbf{W}^\top\mathbf{g} of this lesson (a zero entry may print as -0., which is the same number). The library has these rules built in, and a library’s gradient is as correct as its rules; when you write your own backward function, the central difference is the test.

Common shape bugs

  • A missing transpose in the backward pass: Wg\mathbf{W}\mathbf{g} in place of W⊤g\mathbf{W}^\top\mathbf{g}. For a rectangular W\mathbf{W}, NumPy raises an error. For a square one it runs and returns wrong numbers (unless W\mathbf{W} is symmetric).
  • The outer product the wrong way round: xg⊤\mathbf{x}\mathbf{g}^\top (n×mn\times m) in place of gx⊤\mathbf{g}\mathbf{x}^\top (m×nm\times n). The update W−η(⋯ )\mathbf{W}-\eta(\cdots) would usually fail, or, for square W\mathbf{W}, silently use the transposed gradient.
  • A gradient with the wrong orientation: a row (1×n)(1\times n) in place of a column (n×1)(n\times1), for example because a source uses the numerator layout.
  • A lost factor. The 22 of ∥x∥2\lVert\mathbf{x}\rVert^2, or the 1N\frac1N of an average. A gradient that is exactly NN times too large still has the right shape and the right direction, and in plain gradient descent it acts like a learning rate NN times larger.
  • 2Ax2\mathbf{A}\mathbf{x} for a non-symmetric A\mathbf{A}.
  • Not summing the bias gradient over the batch. It must have the shape of b\mathbf{b}, not of Y\mathbf{Y}.
  • Broadcasting a wrong shape into a wrong number. If Xw\mathbf{X}\mathbf{w} has shape (N,)(N,) and y\mathbf{y} has shape (N,1)(N,1), then Xw−y\mathbf{X}\mathbf{w}-\mathbf{y} is an N×NN\times N array (P1.B14). With the P0.2 data the sum of squares becomes 8484 instead of 1818, and no error is raised. The second cell below shows it.
Go deeper Why books disagree: numerator and denominator layouts

Take y=f(x)y=f(\mathbf{x}) with x\mathbf{x} a column of nn entries. In the numerator layout the derivative ∂y∂x\frac{\partial y}{\partial\mathbf{x}} is a row (∂y∂x1,…,∂y∂xn)\left(\frac{\partial y}{\partial x_1},\dots,\frac{\partial y}{\partial x_n}\right), the 1×n1\times n Jacobian, so that the first-order approximation reads Δy≈∂y∂x Δ\Delta y\approx\frac{\partial y}{\partial\mathbf{x}}\,\boldsymbol{\Delta} with no transposes, and the chain rule is a product in the same order as the functions. In the denominator layout it is the column ∇xy\nabla_{\mathbf{x}}y, which has the shape of x\mathbf{x}, so that the update x−η∇y\mathbf{x}-\eta\nabla y needs no transpose. The two differ by a transpose: ∇xy=(∂y∂x)⊤\nabla_{\mathbf{x}}y=\left(\frac{\partial y}{\partial\mathbf{x}}\right)^\top.

So a book in the numerator layout writes ∂∂x(a⊤x)=a⊤\frac{\partial}{\partial\mathbf{x}}(\mathbf{a}^\top\mathbf{x})=\mathbf{a}^\top and ∂∂x(x⊤Ax)=x⊤(A+A⊤)\frac{\partial}{\partial\mathbf{x}}(\mathbf{x}^\top\mathbf{A}\mathbf{x})=\mathbf{x}^\top(\mathbf{A}+\mathbf{A}^\top), rows where this lesson has columns. Transposing converts one to the other. The names are used with some variation in the literature, so check a source’s own definition. This site uses the denominator layout for gradients of scalars (the shape of the variable), and the m×nm\times n numerator layout for Jacobians, which is why a gradient is the transpose of the one-row Jacobian (P1.C7).

Go deeper The matrix inner product and the trace

The inner product used in this lesson, ⟨A,B⟩=∑i,jAijBij\langle\mathbf{A},\mathbf{B}\rangle=\sum_{i,j}A_{ij}B_{ij}, can be written with the trace (the sum of the diagonal entries): ⟨A,B⟩=tr⁡(A⊤B)\langle\mathbf{A},\mathbf{B}\rangle=\operatorname{tr}(\mathbf{A}^\top\mathbf{B}). The trace has a cyclic property, tr⁡(PQR)=tr⁡(RPQ)\operatorname{tr}(\mathbf{P}\mathbf{Q}\mathbf{R})=\operatorname{tr}(\mathbf{R}\mathbf{P}\mathbf{Q}) whenever the products exist. Together they give the weight gradient in one line. Let L=g⊤WxL=\mathbf{g}^\top\mathbf{W}\mathbf{x} (a number) and nudge W\mathbf{W} by Δ\boldsymbol{\Delta}. The change is exactly

g⊤Δx=tr⁡(g⊤Δx)=tr⁡(xg⊤Δ)=tr⁡ ⁣((gx⊤)⊤Δ)=⟨gx⊤,Δ⟩.\begin{aligned} \mathbf{g}^\top\boldsymbol{\Delta}\mathbf{x}&=\operatorname{tr}(\mathbf{g}^\top\boldsymbol{\Delta}\mathbf{x})\\ &=\operatorname{tr}(\mathbf{x}\mathbf{g}^\top\boldsymbol{\Delta})\\ &=\operatorname{tr}\!\left((\mathbf{g}\mathbf{x}^\top)^\top\boldsymbol{\Delta}\right)\\ &=\langle\mathbf{g}\mathbf{x}^\top,\boldsymbol{\Delta}\rangle. \end{aligned}

A number is its own trace, the second step moves x\mathbf{x} round the cycle, and (gx⊤)⊤=xg⊤(\mathbf{g}\mathbf{x}^\top)^\top=\mathbf{x}\mathbf{g}^\top. So ∇WL=gx⊤\nabla_{\mathbf{W}}L=\mathbf{g}\mathbf{x}^\top, as found from components. The same pattern (bring the nudge to the right end, then read off what is in front) gives many matrix gradients. If it feels like a trick, use the component method: it always works, only more slowly.

Go deeper Only the symmetric part of A matters

Split A=S+K\mathbf{A}=\mathbf{S}+\mathbf{K} with S=12(A+A⊤)\mathbf{S}=\frac12(\mathbf{A}+\mathbf{A}^\top) symmetric and K=12(A−A⊤)\mathbf{K}=\frac12(\mathbf{A}-\mathbf{A}^\top) antisymmetric (K⊤=−K\mathbf{K}^\top=-\mathbf{K}). For an antisymmetric matrix, x⊤Kx\mathbf{x}^\top\mathbf{K}\mathbf{x} is a number equal to its own transpose, x⊤K⊤x=−x⊤Kx\mathbf{x}^\top\mathbf{K}^\top\mathbf{x}=-\mathbf{x}^\top\mathbf{K}\mathbf{x}, so it is 00. Hence x⊤Ax=x⊤Sx\mathbf{x}^\top\mathbf{A}\mathbf{x}=\mathbf{x}^\top\mathbf{S}\mathbf{x}: the antisymmetric part contributes nothing, and the gradient (A+A⊤)x=2Sx(\mathbf{A}+\mathbf{A}^\top)\mathbf{x}=2\mathbf{S}\mathbf{x} only sees S\mathbf{S}. For A=(01−10)\mathbf{A}=\begin{pmatrix}0&1\\-1&0\end{pmatrix} the value is 00 for every x\mathbf{x}, and so is the gradient. The derivative of the gradient (A+A⊤)x(\mathbf{A}+\mathbf{A}^\top)\mathbf{x} with respect to x\mathbf{x} is the matrix A+A⊤\mathbf{A}+\mathbf{A}^\top, which is the Hessian of P1.C8.

Go deeper Why we avoid the full derivative of Wx with respect to W

The Jacobian of y=Wx\mathbf{y}=\mathbf{W}\mathbf{x} with respect to x\mathbf{x} is the matrix W\mathbf{W} (P1.C7). With respect to the matrix W\mathbf{W} it is stranger: each of the mm outputs depends on each of the m⋅nm\cdot n weights, so the derivative has m⋅m⋅nm\cdot m\cdot n entries (twelve for a 2×32\times3 matrix), a three-index array with ∂yi∂Wkj=xj\frac{\partial y_i}{\partial W_{kj}}=x_j when i=ki=k and 00 otherwise. Almost all of it is zeros. A scalar loss avoids the problem: contracting this array with the arriving gradient g\mathbf{g} leaves a matrix of the shape of W\mathbf{W}, the outer product gx⊤\mathbf{g}\mathbf{x}^\top. That is why the rules in this lesson are stated for a scalar LL and an arriving gradient, which is also how automatic differentiation works (the vector-Jacobian product of P1.C7).

Matrix calculus in three depths

Intuition

Backward through a layer, the gradient meets the same matrix as the forward pass, transposed. Output ii was built from row ii of W\mathbf{W}. Input jj affected every output through column jj, so its gradient is collected from column jj. A weight’s gradient is (what arrived at its output) times (what went in at its input). A weight on a large input, whose output matters a lot to the loss, gets a large gradient, and a weight on a zero input gets none.

“Blame” is only a picture. The gradient is a slope, how much the loss would change per unit change of that weight, and a weight with a large gradient may be quite right and a different one still needs a bigger move.

When you are stuck, forget the shapes of the answer for a moment and write the sum with indices, as with yi=∑jWijxjy_i=\sum_jW_{ij}x_j. Differentiate one entry. Then arrange the entries back into a matrix and let the shape check confirm the arrangement.

Math

Layout: ∇XL\nabla_{\mathbf{X}}L has the shape of X\mathbf{X}, with entries ∂L/∂Xij\partial L/\partial X_{ij}. Method: L(X+Δ)−L(X)≈⟨∇XL,Δ⟩=∑ij(∇XL)ijΔijL(\mathbf{X}+\boldsymbol{\Delta})-L(\mathbf{X})\approx\langle\nabla_{\mathbf{X}}L,\boldsymbol{\Delta}\rangle=\sum_{ij}(\nabla_{\mathbf{X}}L)_{ij}\Delta_{ij}.

∇(a⊤x)=a,∇∥x∥2=2x,∇∥x∥=x∥x∥,∇(x⊤Ax)=(A+A⊤)x,\begin{aligned} \nabla(\mathbf{a}^\top\mathbf{x})&=\mathbf{a},\\ \nabla\lVert\mathbf{x}\rVert^2&=2\mathbf{x},\\ \nabla\lVert\mathbf{x}\rVert&=\frac{\mathbf{x}}{\lVert\mathbf{x}\rVert},\\ \nabla(\mathbf{x}^\top\mathbf{A}\mathbf{x})&=(\mathbf{A}+\mathbf{A}^\top)\mathbf{x}, \end{aligned}

For least squares, L=∥Xw−y∥2L=\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2 and

∇wL=2X⊤(Xw−y).\nabla_{\mathbf{w}}L=2\mathbf{X}^\top(\mathbf{X}\mathbf{w}-\mathbf{y}).

Layers, with g=∇yL\mathbf{g}=\nabla_{\mathbf{y}}L and G=∇YL\mathbf{G}=\nabla_{\mathbf{Y}}L:

  • y=Wx+b\mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b}, for x\mathbf{x}, W\mathbf{W}, b\mathbf{b}: W⊤g\mathbf{W}^\top\mathbf{g}, gx⊤\mathbf{g}\mathbf{x}^\top, g\mathbf{g}.
  • Y=XW⊤+b\mathbf{Y}=\mathbf{X}\mathbf{W}^\top+\mathbf{b}, for X\mathbf{X}, W\mathbf{W}, b\mathbf{b}: GW\mathbf{G}\mathbf{W}, G⊤X\mathbf{G}^\top\mathbf{X}, G⊤1\mathbf{G}^\top\mathbf{1}.
  • a=σ(z)\mathbf{a}=\sigma(\mathbf{z}), for z\mathbf{z}: g⊙σ′(z)\mathbf{g}\odot\sigma'(\mathbf{z}).
  • Softmax with cross-entropy, for z\mathbf{z}: p−y\mathbf{p}-\mathbf{y}.

Here 1\mathbf{1} is a column of NN ones, so G⊤1\mathbf{G}^\top\mathbf{1} is the column sums of G\mathbf{G}. The component derivation of the dense layer is ∂L∂Wij=gixj\frac{\partial L}{\partial W_{ij}}=g_ix_j and ∂L∂xj=∑igiWij\frac{\partial L}{\partial x_j}=\sum_ig_iW_{ij}.

Code

import numpy as np

def num_grad(f, x, h=1e-5):
    """Central differences."""
    x = np.array(x, dtype=float)
    g = np.zeros_like(x)
    for i in np.ndindex(x.shape):
        up = x.copy()
        down = x.copy()
        up[i] += h
        down[i] -= h
        fu, fd = f(up), f(down)
        g[i] = (fu - fd) / (2*h)
    return g

# a non-symmetric A
A = np.array([[2, 1], [0, 3]])
x = np.array([1, 2])
print((A + A.T) @ x)    # [ 6 13]
f = lambda x: x @ A @ x
print(num_grad(f, x))
# about [ 6. 13.]

After backward(), each tensor you created with requires_grad=True has a .grad of its own shape (an intermediate result gets none unless you ask with retain_grad()), so W.grad.shape == W.shape is a one-line shape check.

Try it: verify the rules in code

The first cell uses a num_grad that works for arrays of any shape and checks the rules of this lesson on the lesson’s numbers: a shape check first, then the largest difference from the formula. Predict the output before you run: the differences should be tiny (of the order 10−1010^{-10} or smaller). The second cell shows the shape bugs: a square matrix that hides a missing transpose, the outer product the wrong way round, and the broadcast that turns a shape error into a wrong number.

Try it: check the gradient rules numerically

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Challenge: check the gradient of x⊤Ax\mathbf{x}^\top\mathbf{A}\mathbf{x} for a random 4×44\times4 matrix A = np.random.rand(4, 4) and a random x. Then replace A\mathbf{A} by (A + A.T) / 2 and see that 2Ax2\mathbf{A}\mathbf{x} passes the check too.

Try it: shape bugs that run without an error

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Challenge: write the backward pass of the sigmoid layer of this lesson as three lines of NumPy (delta, then W.T @ delta, then np.outer(delta, x)) and check each with num_grad.

Common mistakes

Check your understanding

  1. Let A=(1203)\mathbf{A}=\begin{pmatrix}1&2\\0&3\end{pmatrix} and L=x⊤AxL=\mathbf{x}^\top\mathbf{A}\mathbf{x}. What is ∇xL\nabla_{\mathbf{x}}L at x=(1,1)\mathbf{x}=(1,1)?

  2. A layer computes y=Wx\mathbf{y}=\mathbf{W}\mathbf{x} with W\mathbf{W} of shape 4×54\times5. The gradient g=∇yL\mathbf{g}=\nabla_{\mathbf{y}}L arrives. What is the shape of ∇WL=gx⊤\nabla_{\mathbf{W}}L=\mathbf{g}\mathbf{x}^\top?

  3. A batch of 3232 examples goes through Y=XW⊤+b\mathbf{Y}=\mathbf{X}\mathbf{W}^\top+\mathbf{b}, where b\mathbf{b} has 44 entries. What shape does ∇bL\nabla_{\mathbf{b}}L have?

  4. A classifier with three classes outputs the probabilities p=(0.7, 0.2, 0.1)\mathbf{p}=(0.7,\,0.2,\,0.1), and the correct class is the second. What is the gradient of the cross-entropy loss with respect to the three scores?

  5. A backward pass through y=Wx\mathbf{y}=\mathbf{W}\mathbf{x} with a square 3×33\times3 matrix W\mathbf{W} is coded as W @ g instead of W.T @ g. No error appears. What is the right conclusion?

Exercises

  1. Find ∇∥x∥2\nabla\lVert\mathbf{x}\rVert^2 and ∇∥x∥\nabla\lVert\mathbf{x}\rVert at x=(1,−2,2)\mathbf{x}=(1,-2,2).
    Show answer∥x∥=1+4+4=3\lVert\mathbf{x}\rVert=\sqrt{1+4+4}=3. So ∇∥x∥2=2x=(2,−4,4)\nabla\lVert\mathbf{x}\rVert^2=2\mathbf{x}=(2,-4,4) and ∇∥x∥=x/3=(13,−23,23)\nabla\lVert\mathbf{x}\rVert=\mathbf{x}/3=(\tfrac13,-\tfrac23,\tfrac23), which has length 11.
  2. For A=(1234)\mathbf{A}=\begin{pmatrix}1&2\\3&4\end{pmatrix} and x=(1,−1)\mathbf{x}=(1,-1), find ∇(x⊤Ax)\nabla(\mathbf{x}^\top\mathbf{A}\mathbf{x}), and the wrong 2Ax2\mathbf{A}\mathbf{x}.
    Show answerA+A⊤=(2558)\mathbf{A}+\mathbf{A}^\top=\begin{pmatrix}2&5\\5&8\end{pmatrix}, so the gradient is (2−5,  5−8)=(−3,−3)(2-5,\;5-8)=(-3,-3). The shortcut 2Ax=2(−1,−1)=(−2,−2)2\mathbf{A}\mathbf{x}=2(-1,-1)=(-2,-2) is wrong because A\mathbf{A} is not symmetric.
  3. For X=(101112)\mathbf{X}=\begin{pmatrix}1&0\\1&1\\1&2\end{pmatrix} and y=(1,2,2)\mathbf{y}=(1,2,2), find the gradient of ∥Xw−y∥2\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2 at w=0\mathbf{w}=\mathbf{0}, then solve the normal equations.
    Show answerAt w=0\mathbf{w}=\mathbf{0} the residual is −y=(−1,−2,−2)-\mathbf{y}=(-1,-2,-2), X⊤r=(−5,−6)\mathbf{X}^\top\mathbf{r}=(-5,-6) and the gradient is 2X⊤r=(−10,−12)2\mathbf{X}^\top\mathbf{r}=(-10,-12). The normal equations (3335)w=(5,6)\begin{pmatrix}3&3\\3&5\end{pmatrix}\mathbf{w}=(5,6) give w=(76,12)≈(1.167,0.5)\mathbf{w}=(\tfrac76,\tfrac12)\approx(1.167,0.5).
  4. A layer has W=(102103)\mathbf{W}=\begin{pmatrix}1&0\\2&1\\0&3\end{pmatrix}, input x=(2,1)\mathbf{x}=(2,1) and arriving gradient g=(1,0,−1)\mathbf{g}=(1,0,-1). Find ∇xL\nabla_{\mathbf{x}}L and ∇WL\nabla_{\mathbf{W}}L, and give their shapes.
    Show answer∇xL=W⊤g=(1−0,  0−3)=(1,−3)\nabla_{\mathbf{x}}L=\mathbf{W}^\top\mathbf{g}=(1-0,\;0-3)=(1,-3), with 22 entries like x\mathbf{x}. ∇WL=gx⊤=(2100−2−1)\nabla_{\mathbf{W}}L=\mathbf{g}\mathbf{x}^\top=\begin{pmatrix}2&1\\0&0\\-2&-1\end{pmatrix}, shape 3×23\times2 like W\mathbf{W}.
  5. A ReLU acts on z=(−2,0.5,3)\mathbf{z}=(-2,0.5,3), and the gradient (1,2,3)(1,2,3) arrives at its outputs. What does it send back?
    Show answerThe slope of ReLU is 00 for negative inputs and 11 for positive ones, so g⊙ReLU′(z)=(0,2,3)\mathbf{g}\odot\mathrm{ReLU}'(\mathbf{z})=(0,2,3). (At exactly 00 the slope is not defined and software picks a convention; none of the entries here is 00.)
  6. Two classes have equal scores z=(0,0)\mathbf{z}=(0,0) and the first class is correct. Find the gradient of the cross-entropy loss.
    Show answerp=(0.5,0.5)\mathbf{p}=(0.5,0.5) and y=(1,0)\mathbf{y}=(1,0), so p−y=(−0.5,0.5)\mathbf{p}-\mathbf{y}=(-0.5,0.5): raise the first score, lower the second.
  7. A batch of 6464 examples with 784784 features goes through a layer with 128128 outputs, Y=XW⊤+b\mathbf{Y}=\mathbf{X}\mathbf{W}^\top+\mathbf{b}. Give the shapes of W\mathbf{W}, G\mathbf{G}, ∇WL\nabla_{\mathbf{W}}L, ∇bL\nabla_{\mathbf{b}}L and ∇XL\nabla_{\mathbf{X}}L.
    Show answerW\mathbf{W} is 128×784128\times784 and G\mathbf{G} is 64×12864\times128. Then ∇WL=G⊤X\nabla_{\mathbf{W}}L=\mathbf{G}^\top\mathbf{X} is (128×64)(64×784)=128×784(128\times64)(64\times784)=128\times784. ∇bL\nabla_{\mathbf{b}}L has 128128 entries, and ∇XL=GW\nabla_{\mathbf{X}}L=\mathbf{G}\mathbf{W} is (64×128)(128×784)=64×784(64\times128)(128\times784)=64\times784.
  8. A library stores the weights as W\mathbf{W} of shape n×mn\times m and computes Y=XW\mathbf{Y}=\mathbf{X}\mathbf{W} (no transpose). Find ∇WL\nabla_{\mathbf{W}}L and ∇XL\nabla_{\mathbf{X}}L from G\mathbf{G}.
    Show answer∇WL=X⊤G\nabla_{\mathbf{W}}L=\mathbf{X}^\top\mathbf{G}, shape (n×N)(N×m)=n×m(n\times N)(N\times m)=n\times m, and ∇XL=GW⊤\nabla_{\mathbf{X}}L=\mathbf{G}\mathbf{W}^\top, shape (N×m)(m×n)=N×n(N\times m)(m\times n)=N\times n. These are the earlier formulas with W\mathbf{W} replaced by W⊤\mathbf{W}^\top. A central-difference check on random X\mathbf{X}, W\mathbf{W} and G\mathbf{G} agrees to about 10−910^{-9}.
  9. Why is p−y\mathbf{p}-\mathbf{y} a sensible error signal for softmax?
    Show answerIts entry for the correct class is pk−1≤0p_k-1\le0, so a gradient step raises that score, and its other entries pi≥0p_i\ge0 lower the wrong scores, more for the classes the model prefers. The entries add up to 00, so the step raises some scores and lowers others by the same total. It is small when p\mathbf{p} is already close to y\mathbf{y}.

Next: P1.C8 takes the second derivative of these formulas, the Hessian, and explains bowls and saddles. P4.8 and P4.10 use the dense-layer rules above to run backpropagation through a whole network, and P3.A2 and P3.A8 use the least-squares and softmax gradients to train models.

Key takeaways

  • Layout and the shape check. On this site the gradient of a scalar LL with respect to a vector or matrix has the shape of that vector or matrix, and a Jacobian of f:Rn→Rm\mathbf{f}:\mathbb{R}^n\to\mathbb{R}^m is m×nm\times n. Books differ, and their formulas then differ by a transpose. After you write a gradient, check its shape against the thing it belongs to.
  • The method. Nudge the variable by Δ\boldsymbol{\Delta}, expand L(x+Δ)L(\mathbf{x}+\boldsymbol{\Delta}), and drop terms with Δ\boldsymbol{\Delta} twice. What is left is ⟨∇L,Δ⟩\langle\nabla L,\boldsymbol{\Delta}\rangle, a sum of entrywise products, and the thing multiplying Δ\boldsymbol{\Delta} is the gradient.
  • Cheat sheet. ∇(a⊤x)=a\nabla(\mathbf{a}^\top\mathbf{x})=\mathbf{a}, ∇∥x∥2=2x\nabla\lVert\mathbf{x}\rVert^2=2\mathbf{x}, ∇∥x∥=x/∥x∥\nabla\lVert\mathbf{x}\rVert=\mathbf{x}/\lVert\mathbf{x}\rVert for x≠0\mathbf{x}\neq\mathbf{0}, ∇(x⊤Ax)=(A+A⊤)x\nabla(\mathbf{x}^\top\mathbf{A}\mathbf{x})=(\mathbf{A}+\mathbf{A}^\top)\mathbf{x} (which is 2Ax2\mathbf{A}\mathbf{x} only for symmetric A\mathbf{A}), and ∇w∥Xw−y∥2=2X⊤(Xw−y)\nabla_{\mathbf{w}}\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2=2\mathbf{X}^\top(\mathbf{X}\mathbf{w}-\mathbf{y}). For the average over NN examples, divide by NN.
  • Layers. For y=Wx+b\mathbf{y}=\mathbf{W}\mathbf{x}+\mathbf{b} with g=∇yL\mathbf{g}=\nabla_{\mathbf{y}}L: ∇xL=W⊤g\nabla_{\mathbf{x}}L=\mathbf{W}^\top\mathbf{g}, ∇WL=gx⊤\nabla_{\mathbf{W}}L=\mathbf{g}\mathbf{x}^\top (an outer product) and ∇bL=g\nabla_{\mathbf{b}}L=\mathbf{g}. For a batch Y=XW⊤+b\mathbf{Y}=\mathbf{X}\mathbf{W}^\top+\mathbf{b} with G=∇YL\mathbf{G}=\nabla_{\mathbf{Y}}L: G⊤X\mathbf{G}^\top\mathbf{X}, GW\mathbf{G}\mathbf{W} and the column sums of G\mathbf{G}. An elementwise function gives g⊙σ′(z)\mathbf{g}\odot\sigma'(\mathbf{z}).
  • Softmax with cross-entropy has the gradient p−y\mathbf{p}-\mathbf{y} with respect to the scores, where y\mathbf{y} is the one-hot target. For scores (1,2,3)(1,2,3) and the third class correct it is (0.0900, 0.2447, −0.3348)(0.0900,\,0.2447,\,-0.3348).
  • Check, do not trust. A shape check misses a missing transpose when W\mathbf{W} is square, and broadcasting can turn a wrong shape into a wrong number. Compare every new gradient with a central difference on small random numbers; automatic differentiation (PyTorch) gives the same answers.
Found a mistake? Tell us