For a two-layer network , , trained with cross-entropy on one example with true class , what are the gradients of the loss with respect to 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 at each layer as the gradient of the loss with respect to that layer's pre-activation : and . Then each weight gradient is an outer product, , where is the layer's input (, ). Each bias gradient is .
Steps
- Fix shapes: , , , , . Here is the input size, the hidden width and the number of classes.
- Forward: , , , , .
- Output layer: with the one-hot vector of class , (the standard result for softmax plus cross-entropy). Then (, matching ) and .
- Back into the hidden layer: . ReLU passes the gradient only where it was active, so , where is element-wise multiplication.
- First layer: (, matching ) and .
- Mini-batch of examples: capital letters stack the per-example vectors as rows, e.g. . Stack the deltas the same way: and . Then and , and the bias gradients are the column sums of .
Common mistakes
- Getting transposes wrong. Check that every gradient has the same shape as its parameter.
- Forgetting the ReLU mask , or using where a matrix product is needed (or the reverse).
- Forgetting the when the loss is averaged over the batch.
How long your answer should be
About a page; 6–8 minutes.
Last checked on 4 December 2026.
Read this
- CS231n: Putting it together, Minimal Neural Network Case Study: 'Training a Neural Network': a 2-layer ReLU-softmax network with dscores = (probs - onehot)/N, then dW2 = h^T dscores, the ReLU mask, and dW1 = X^T dhidden in numpy (batch-as-rows convention).
- Computing Neural Network Gradients (Kevin Clark, Stanford CS224n): Sections 3-5: Jacobian identities (dz/dW = delta x^T), the shape convention that gradients match parameter shapes, and a worked 1-hidden-layer network.
- NPTEL: Deep Learning (Part 1) (IIT Ropar, Prof. Sudarshan Iyengar; lectures by Prof. Mitesh M. Khapra): Week 3, Lectures: Backpropagation: gradients w.r.t. output units, hidden units and parameters, which derive each layer's gradients in vector form.
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 (the input to the sigmoid)? How do the two losses look as functions of 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?