Concept Library/The Complete Guide to Backpropagation: From Multivariable Chain Rule Trees to Vectorized Matrix Calculus
Deep Learning FoundationsBook Index: Letter B
The Complete Guide to Backpropagation: From Multivariable Chain Rule Trees to Vectorized Matrix Calculus
Master backpropagation from foundational multivariable calculus to production matrix operations: Multivariable Chain Rule trees, gradient descent dynamics, Confusion Matrix diagnostics, Binary Cross-Entropy vs. Squared Error, Stanford CS229 vectorized calculus, and raw Python implementations.
functionsMathematical Representation
∂W[l]∂L=δ[l](a[l−1])T
Backpropagation is often presented as an intimidating wall of partial derivatives, subscripts, and matrix transposes. At its core, however, backpropagation is simply the Multivariable Chain Rule from Calculus 3 applied to a nested function. Whether you derive gradients one scalar weight at a time using a Dependency Tree or compute an entire layer's gradients simultaneously using Vectorized Matrix Calculus, the underlying mathematics is identical.
This master guide walks through the entire lifecycle of backpropagation:
Network Architecture & Forward Pass Mechanics
The Sigmoid Derivative Trick
Method 1: The Multivariable Chain Rule Dependency Tree (Scalar Approach)
Why Derivative Values Matter: The Mechanics of Gradient Descent
Worked Numerical Examples (Overshooting vs. Undershooting)
Evaluation Metrics: Decoding the Confusion Matrix (TN, FP, FN, TP)
Binary Cross-Entropy (BCE) vs. Squared-Error Loss (Full Numerical Walkthrough)
Consider a canonical two-layer feedforward neural network designed for binary classification (y∈{0,1}). It takes two input features (x0,x1), passes them through a hidden layer with two nodes (a0,a1), and outputs a final prediction (a2). The network contains 9 tunable parameters (θ): six weights (w0…w5) and three biases (b0,b1,b2).
where σ(z)=1+e−z1 is the sigmoid activation function. The factor of 21 in the loss function is included so that the exponent 2 cancels cleanly during differentiation.
2. The Sigmoid Derivative Trick
To differentiate through the hidden layer, we need the derivative of the sigmoid function σ(z)=(1+e−z)−1. By applying the chain rule and adding/subtracting 1 in the numerator, we can write σ′(z) purely in terms of σ(z):
Because we already compute a0=σ(z0) and a1=σ(z1) during the forward pass, we never have to re-evaluate exponential functions during the backward pass:
∂z0∂a0=a0(1−a0)and∂z1∂a1=a1(1−a1)
3. Method 1: Building the Multivariable Chain Rule Tree
In multivariable calculus, when a top-level function L depends on nested intermediate variables, we construct a Dependency Tree.
The 4 Rules of Tree Construction
Start at the final scalar output (L) and inspect its formula: L=21(y−a2)2.
Branch to every changeable variable inside that formula (a2).
Continue or Terminate: If a variable is computed via its own equation (like a2,a0,a1,z0,z1), draw branches to its components. If a variable is a raw tunable parameter (w0…w5,b0…b2), the branch stops (shown in brackets [ ]).
Treat Dataset Values as Constants: The inputs (x0,x1) and true label (y) are fixed observations from the dataset. Since we cannot modify the dataset, they act as constants and never receive branches.
To find the partial derivative of L with respect to any parameter [θ], trace the unique path from L to [θ] and multiply every branch derivative along that path:
Root Error Signal (L→a2):∂a2∂L=21⋅2(y−a2)⋅(−1)=a2−y
(Note: Why are there no + signs between paths like in general multivariable chain rule problems? Because each weight wi appears in only one place in the network, meaning there is only a single path from L to any parameter.)
4. Why Derivative Values Matter: The Mechanics of Gradient Descent
Once you evaluate the 9 derivative equations, you get 9 plain numbers — one for each parameter. You then update each parameter by subtracting its own derivative scaled by the learning rate η:
θnew=θold−η⋅∂θ∂L
Why We Cannot Simply Add or Subtract a Fixed Constant
What if we ignored the derivative equations and simply subtracted a fixed 0.1 from every weight whenever the network's output was too high? Two immediate failures occur:
Sign Reversals Through Negative Weights: Suppose output weight w4=−0.8 (negative) and our prediction a2 is too high. Because a0 is multiplied by a negative weight (w4=−0.8), reducing w0 makes a0 smaller, which makes w4a0less negative, pushing a2 higher and worsening the error! The chain rule equation:
∂w0∂L=(a2−y)w4a0(1−a0)x0
multiplies by w4, automatically flipping the derivative's sign so our subtraction moves w0 in the true error-reducing direction.
Proportional Credit Assignment (Inactive Inputs): Consider z0=w0x0+w2x1. If an input has measurements x0=10 and x1=0, weight w2 was multiplied by 0 — it contributed nothing to the output error. Because ∂w2∂L multiplies by x1=0, the formula automatically yields ∂w2∂L=0, leaving w2 untouched while giving w0 a large update proportional to x0=10.
In practice, you do not need to reason about impact or sign manually — calculating the derivative formula automatically encodes both direction and magnitude into a single number. You simply compute the number and subtract (η×derivative) from that parameter.
5. Worked Numerical Examples (Squared-Error Loss)
Example A: Network Guesses Too Low (Negative Derivatives → Weights Increase)
a2new=(0.60)(0.157)+(0.20)(0.301)−0.20=−0.046 (Dropped from 0.80 right down to −0.046≈0.0!)
Lnew=21(0.0−(−0.046))2≈0.001
6. Evaluation Metrics: Decoding the Confusion Matrix
While the Loss function L guides gradient descent with continuous numbers, classification performance is evaluated by thresholding the continuous prediction (c=0 if a2<0.5 else 1) and tallying four outcomes:
Second Word (Positive / Negative) = What the Network Predicted (c): Positive means c=1; Negative means c=0.
First Word (True / False) = Whether the Prediction Matched Reality (c==y): True means correct; False means incorrect.
Metric
Prediction (c)
True Label (y)
Meaning
TN (True Negative)
0
0
Correct Rejection: Network predicted Class 0, actual was Class 0.
TP (True Positive)
1
1
Correct Hit: Network predicted Class 1, actual was Class 1.
FP (False Positive)
1
0
False Alarm (Type I Error): Network predicted Class 1, actual was Class 0.
FN (False Negative)
0
1
Missed Detection (Type II Error): Network predicted Class 0, actual was Class 1.
From these four fundamental counts, we derive standard diagnostic metrics:
Accuracy:Accuracy=TN+FP+FN+TPTN+TP(Overall fraction of correct predictions)
Precision:Precision=TP+FPTP(How often positive predictions are actually correct)
Recall (Sensitivity):Recall=TP+FNTP(Fraction of actual positives successfully detected)
7. Upgrading to Binary Cross-Entropy (BCE) Loss
Squared-error loss works well for regression (predicting unbounded continuous values), but for binary classification, Binary Cross-Entropy (BCE) paired with a sigmoid output activation is mathematically superior:
Output Layer Becomes a Sigmoid Probability:z2=w4a0+w5a1+b2⟹a2=σ(z2)=1+e−z21
Binary Cross-Entropy Loss Formula:L=−[yln(a2)+(1−y)ln(1−a2)]
Why BCE + Sigmoid Beats Squared Error + Sigmoid
If you apply Squared Error to a sigmoid output, the root gradient with respect to z2 is (a2−y)⋅a2(1−a2). When the network is confidently wrong (e.g., y=1,a2=0.001), the sigmoid slope a2(1−a2)≈0.001 crushes the gradient (vanishing gradient), slowing learning to a standstill.
With BCE, the derivative with respect to a2 and the sigmoid derivative cancel each other out completely:
∂a2∂L=−a2y+1−a21−y=a2(1−a2)a2−y
Multiplying by the sigmoid derivative ∂z2∂a2=a2(1−a2) via the chain rule:
The saturation term a2(1−a2) vanishes from the denominator and numerator! Even if a2=0.001 when y=1, the error signal is 0.001−1.0=−0.999 — a massive gradient that instantly corrects the network.
Worked BCE Numerical Example
Inputs & Target:x0=2.0,x1=1.0,y=1.0,η=0.5
Initial Parameters:w0=w1=w2=w3=b0=b1=0.0, and w4=−0.8,w5=−1.2,b2=−1.0
Step 1: Forward Pass
z0=0⟹a0=0.5, and z1=0⟹a1=0.5
z2=(−0.8)(0.5)+(−1.2)(0.5)−1.0=−0.4−0.6−1.0=−2.0
a2=σ(−2.0)=1+e2.01≈0.119 (11.9% predicted probability for Class 1)
BCE Loss:L=−[(1.0)ln(0.119)+0]=−ln(0.119)≈2.129
Step 2: Backward Pass (Verifying the Cancellation Numerically)
Root Signal directly at z2:δ2=∂z2∂L=a2−y=0.119−1.0=−0.881
Hidden Gradients (Note sign flip due to negative w4,w5):δ0=∂z0∂L=δ2⋅w4⋅a0(1−a0)=(−0.881)(−0.8)(0.25)=+0.1762∂w0∂L=δ0⋅x0=(+0.1762)(2.0)=+0.3524∂w2∂L=δ0⋅x1=(+0.1762)(1.0)=+0.1762,∂b0∂L=+0.1762δ1=∂z1∂L=δ2⋅w5⋅a1(1−a1)=(−0.881)(−1.2)(0.25)=+0.2643∂w1∂L=δ1⋅x0=(+0.2643)(2.0)=+0.5286∂w3∂L=δ1⋅x1=(+0.2643)(1.0)=+0.2643,∂b1∂L=+0.2643
In advanced courses like Stanford CS229, rather than writing separate equations for every weight, parameters are grouped into Matrices (W[l]) and Column Vectors (a[l],b[l]).
Direct Substitution Derivation (Stanford Whiteboard Method)
To find the gradient of the BCE loss L(i) with respect to the output weight matrix W[3], substitute y^(i)=a[3]=σ(W[3]a[2]+b[3]) directly into the loss function and differentiate in one vectorized line:
Averaging over m training examples gives the total cost gradient:
∂W[3]∂J=m1∑i=1m(a[3](i)−y(i))(a[2](i))T
The 4 Unbreakable Rules of Matrix Dimensions
How do you instantly know the shape of every matrix and why (a[2])T requires a transpose? Follow these four rules:
Activations (a[l],z[l]), Biases (b[l]), and Error Signals (δ[l]) Are Column Vectors:
For a single sample, if Layer l has nl nodes, its vector has shape (nl,1).
Weight Matrix W[l] Has Shape (Current Layer Nodes, Previous Layer Nodes):W[l]∈Rnl×nl−1
This guarantees that the inner dimensions match during the forward pass:
(nl×1)z[l]=(nl×nl−1)W[l]⋅(nl−1×1)a[l−1]+(nl×1)b[l]
A Gradient ∂W[l]∂L ALWAYS Has the Exact Same Shape as W[l]:
Because the update rule subtracts the gradient from the weight matrix (W[l]←W[l]−η∂W[l]∂J), both matrices must have shape (nl,nl−1).
The Transpose Rule for Weight Gradients:
To form an (nl×nl−1) matrix by multiplying the current layer's column error vector δ[l] of shape (nl,1) and the previous layer's activation vector a[l−1] of shape (nl−1,1), you must transpose a[l−1] into a row vector (1×nl−1):
(nl×nl−1)∂W[l]∂L=(nl×1)δ[l]⋅(1×nl−1)(a[l−1])T
Concrete 3-4-2 Network Dimension Walkthrough
Suppose a network has 3 inputs (Layer 1), 4 hidden nodes (Layer 2), and 2 output nodes (Layer 3):
Use the Dependency Tree to visualize how error signals flow backward through activations and weighted sums without getting lost in nested algebra.
Use Binary Cross-Entropy + Sigmoid for binary classification so the a2(1−a2) saturation term cancels out at the output layer, preventing vanishing gradients on confident errors.
Use the 4 Matrix Shape Rules (W[l] is (ncurr,nprev), vectors are (n,1), and ∂W[l]∂L=δ[l](a[l−1])T) to convert any tree derivation into clean, bug-free matrix code.
11. Verification with PyTorch Autograd
You never write backpropagation by hand in practice. PyTorch's autograd records every operation in the forward pass and computes all gradients with loss.backward():
schoolQuestion 1: Why does ∂L/∂b₂ have the fewest terms?
expand_more
Answer: The path from L to b2 is the shortest possible: L→a2→b2 (just 2 branches). The gradient is simply ∂a2∂L⋅∂b2∂a2=(a2−y)⋅1=(a2−y). Shorter path = fewer terms to multiply.
schoolQuestion 2: If w₃ appeared in both z₀ AND z₁'s formula, what would change?
expand_more
Answer: Then w3 would appear at the end of two different branches in the tree — one through z0 and one through z1. You would need to add both paths together (the multivariate chain rule):
∂w3∂L=branch 1path through z0+branch 2path through z1
When a parameter affects the loss through multiple distinct pathways, calculus requires adding the gradients from all paths.
schoolQuestion 3: What causes vanishing gradients in deep networks?
expand_more
Answer: In a 50-layer network, reaching the earliest layers requires multiplying 50+ local derivatives together. If each sigmoid derivative is at most 0.25, multiplying dozens of numbers ≤0.25 shrinks the gradient toward 0 exponentially (0.2550≈10−31). This is why modern architectures use ReLU (σ′(x)=1 for x>0) and residual skip connections.