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.