For a two-layer network h=ReLU⁡(W1x+b1), y^=softmax⁡(W2h+b2), trained with cross-entropy on one example with true class c, what are the gradients of the loss with respect to W1,b1,W2,b2 in matrix form, and do their shapes check out?

Deep learning, Backpropagation
Level L3 Intermediate. Length Long. Nature Mat Mathematical.

What's being asked

Whether you can run backpropagation with vectors and matrices, keep shapes consistent, and handle the ReLU mask.

Key idea

Define the error δl at each layer as the gradient of the loss with respect to that layer's pre-activation zl: δ2=∂L∂z2=y^−y and δ1=(W2⊤δ2)⊙1[z1>0]. Then each weight gradient is an outer product, ∂L∂Wl=δl al−1⊤, where al−1 is the layer's input (a0=x, a1=h). Each bias gradient is δl.

Steps

  1. Fix shapes: x∈Rd, W1∈Rm×d, b1,z1,h∈Rm, W2∈RK×m, b2,z2,y^∈RK. Here d is the input size, m the hidden width and K the number of classes.
  2. Forward: z1=W1x+b1, h=ReLU⁡(z1), z2=W2h+b2, y^=softmax⁡(z2), L=−log⁡y^c.
  3. Output layer: with y the one-hot vector of class c, δ2=y^−y∈RK (the standard result for softmax plus cross-entropy). Then ∂L∂W2=δ2h⊤ (K×m, matching W2) and ∂L∂b2=δ2.
  4. Back into the hidden layer: ∂L∂h=W2⊤δ2∈Rm. ReLU passes the gradient only where it was active, so δ1=(W2⊤δ2)⊙1[z1>0], where ⊙ is element-wise multiplication.
  5. First layer: ∂L∂W1=δ1x⊤ (m×d, matching W1) and ∂L∂b1=δ1.
  6. Mini-batch of B examples: capital letters stack the per-example vectors as rows, e.g. X∈RB×d. Stack the deltas the same way: Δ2=(Y^−Y)/B and Δ1=(Δ2W2)⊙1[Z1>0]. Then ∂L∂W2=Δ2⊤H and ∂L∂W1=Δ1⊤X, and the bias gradients are the column sums of Δl.

Common mistakes

How long your answer should be

About a page; 6–8 minutes.

Last checked on 4 December 2026.

Read this

Previous in Deep learning: Suppose you train a binary classification network with a sigmoid output using mean-squared error (MSE) instead of cross-entropy. Is training still useful, judging by the gradient of each loss with respect to the logit z (the input to the sigmoid)? How do the two losses look as functions of z for a positive example?
Next in Deep learning: How does the product of layer Jacobians explain vanishing and exploding gradients in a deep feed-forward network, and why are sigmoid networks especially prone to vanishing gradients?