For a mini-batch of N examples stacked as rows in X∈RN×d, a two-layer network computes Z=XW1+1b1⊤, H=ϕ(Z) and Y^=HW2+1b2⊤, where W1∈Rd×m, b1∈Rm, W2∈Rm×K, b2∈RK and 1∈RN is the all-ones vector. Given the batch-averaged loss gradient Δ2=∂L∂Y^∈RN×K, what are the gradients with respect to W2,b2,W1,b1, and how do matrix dimensions verify the transposes?

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

What's being asked

Whether you can vectorise backpropagation across a row-major mini-batch and use tensor shapes to verify every transpose.

Key idea

Summing over the N examples in a batch is a matrix product along the N axis: ∂L∂W2=H⊤Δ2∈Rm×K, ∂L∂b2=Δ2⊤1∈RK, Δ1=(Δ2W2⊤)⊙ϕ′(Z)∈RN×m, ∂L∂W1=X⊤Δ1∈Rd×m and ∂L∂b1=Δ1⊤1∈Rm.

Steps

  1. Note the scaling: because L=1N∑i=1Nℓi, the factor 1N is already inside Δ2=∂L∂Y^, so do not divide by N a second time.
  2. Output layer weights and bias: matching (m×N)(N×K)=m×K gives ∂L∂W2=H⊤Δ2. Summing rows of Δ2 gives ∂L∂b2=Δ2⊤1=∑i=1N(Δ2)i,:⊤∈RK.
  3. Hidden activations and pre-activations: ∂L∂H=Δ2W2⊤, whose shape is (N×K)(K×m)=N×m. Multiplying element-wise (denoted ⊙) by the activation derivative ϕ′(Z) gives Δ1=(Δ2W2⊤)⊙ϕ′(Z)∈RN×m.
  4. First layer weights and bias: matching (d×N)(N×m)=d×m gives ∂L∂W1=X⊤Δ1, and ∂L∂b1=Δ1⊤1∈Rm.

Common mistakes

How long your answer should be

Half a page; 4–5 minutes.

Last checked on 4 December 2026.

Read this

Previous in Deep learning: Consider a small ReLU network with input x=[1,−1]⊤, hidden layer z(1)=W(1)x with W(1)=[1−1−12], h=ReLU⁡(z(1)), and scalar output y^=w(2)⊤h with w(2)=[2,−1]⊤ (no biases). For target y=3 and squared loss L=12(y^−y)2, what are the exact gradients ∂L∂w(2) and ∂L∂W(1)?
Next in Deep learning: How do you express the derivatives of σ(z)=11+e−z and tanh⁡(z)=ez−e−zez+e−z purely in terms of σ(z) and tanh⁡(z), what are their maximum values, and why is tanh⁡ generally preferred over σ in hidden layers?