Skip to content
BIASED

Matrix calculus

Block 1 of 7~2 min

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, ∇x∥Ax−b∥2\nabla_x \lVert Ax - b \rVert^2 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, ∂zk/∂Wij\partial z_k / \partial W_{ij}. 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 f:Rn→Rmf: \mathbb R^n \to \mathbb R^m, the matrix Jf(x)J_f(x) is m×nm \times n, as in the previous topic.
  • A gradient of a scalar has the shape of its variable: ∇xf\nabla_x f is a column in Rn\mathbb R^n for x∈Rnx \in \mathbb R^n, and ∇WL\nabla_W L is an m×nm \times n matrix for W∈Rm×nW \in \mathbb R^{m \times n}, with entries (∇WL)ij=∂L/∂Wij(\nabla_W L)_{ij} = \partial L / \partial W_{ij}.

For a scalar function of a vector the two differ only by a transpose: the Jacobian is the 1×n1 \times n row Jf=(∇f)⊤J_f = (\nabla f)^\top.

Why insist on the shape of the variable? Because of the update step. Gradient descent

W←W−η ∇WLW \leftarrow W - \eta\, \nabla_W L

subtracts the gradient from the weights, so the two must have the same shape.

One example pins the convention down. For f(x)=a⊤x=a1x1+⋯+anxnf(x) = a^\top x = a_1 x_1 + \dots + a_n x_n each partial derivative is ∂f/∂xi=ai\partial f / \partial x_i = a_i, so

∇x(a⊤x)=a,\nabla_x (a^\top x) = a,

a column, not the row a⊤a^\top. 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.

Answers are saved on the server and tied to this browser until you sign in.