Theory ofIntelligence
Index
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
∂L∂W[l]=δ[l](a[l−1])T\frac{\partial \mathcal{L}}{\partial W^{[l]}} = \delta^{[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)
  • Method 2: Stanford CS229 Direct Vectorized Derivation & Matrix Dimension Rules
  • Complete Python Implementation (Scalar & Vectorized)

1. Network Architecture & Forward Pass Mechanics

Consider a canonical two-layer feedforward neural network designed for binary classification (y∈{0,1}y \in \{0, 1\}). It takes two input features (x0,x1x_0, x_1), passes them through a hidden layer with two nodes (a0,a1a_0, a_1), and outputs a final prediction (a2a_2). The network contains 9 tunable parameters (θ\theta): six weights (w0…w5w_0 \dots w_5) and three biases (b0,b1,b2b_0, b_1, b_2).

Neural Network Architecture — 2 Inputs, 2 Hidden, 1 Output

TEXT
   Inputs             Hidden Layer            Output Layer           Loss
  (Fixed)             (Sigmoid σ)              (Linear)

                      b₀ ──┐
                           ▼
   x₀ ─── w₀ ──────► [ z₀ ──► a₀ ] ── w₄ ──┐
     ╲  ╱                                   ▼
      ╲╱                                  [ a₂ ] ──────────► L = ½(y - a₂)²
      ╱╲                                    ▲                      ▲
     ╱  ╲                                   │                      │
   x₁ ─── w₃ ──────► [ z₁ ──► a₁ ] ── w₅ ──┘                    b₂ ┘
                           ▲
                      b₁ ──┘
   (Note: w₂ connects x₁ to z₀, and w₁ connects x₀ to z₁)

Forward Pass Equations (Left-to-Right)

Given a training example x=(x0,x1)\mathbf{x} = (x_0, x_1) and its true label yy, we compute the network's output step by step:

  1. Top Hidden Node: z0=w0x0+w2x1+b0  ⟹  a0=σ(z0)z_0 = w_0 x_0 + w_2 x_1 + b_0 \quad \implies \quad a_0 = \sigma(z_0)

  2. Bottom Hidden Node: z1=w1x0+w3x1+b1  ⟹  a1=σ(z1)z_1 = w_1 x_0 + w_3 x_1 + b_1 \quad \implies \quad a_1 = \sigma(z_1)

  3. Output Node (Linear): a2=w4a0+w5a1+b2a_2 = w_4 a_0 + w_5 a_1 + b_2

  4. Squared-Error Loss Function: L=12(y−a2)2L = \frac{1}{2}(y - a_2)^2

where σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}} is the sigmoid activation function. The factor of 12\frac{1}{2} in the loss function is included so that the exponent 22 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\sigma(z) = (1 + e^{-z})^{-1}. By applying the chain rule and adding/subtracting 11 in the numerator, we can write σ′(z)\sigma'(z) purely in terms of σ(z)\sigma(z):

σ′(z)=ddz(1+e−z)−1=−(1+e−z)−2⋅(−e−z)=e−z(1+e−z)2\sigma'(z) = \frac{d}{dz}(1 + e^{-z})^{-1} = -(1 + e^{-z})^{-2} \cdot (-e^{-z}) = \frac{e^{-z}}{(1 + e^{-z})^2}

Adding and subtracting 11 in the numerator yields:

σ′(z)=(11+e−z)(e−z1+e−z)=(11+e−z)(1+e−z−11+e−z)=σ(z)(1−σ(z))\sigma'(z) = \left(\frac{1}{1 + e^{-z}}\right) \left(\frac{e^{-z}}{1 + e^{-z}}\right) = \left(\frac{1}{1 + e^{-z}}\right) \left(\frac{1 + e^{-z} - 1}{1 + e^{-z}}\right) = \sigma(z)\big(1 - \sigma(z)\big)

Computational Advantage

Because we already compute a0=σ(z0)a_0 = \sigma(z_0) and a1=σ(z1)a_1 = \sigma(z_1) during the forward pass, we never have to re-evaluate exponential functions during the backward pass:

∂a0∂z0=a0(1−a0)and∂a1∂z1=a1(1−a1)\frac{\partial a_0}{\partial z_0} = a_0(1 - a_0) \quad \text{and} \quad \frac{\partial a_1}{\partial z_1} = a_1(1 - a_1)


3. Method 1: Building the Multivariable Chain Rule Tree

In multivariable calculus, when a top-level function LL depends on nested intermediate variables, we construct a Dependency Tree.

The 4 Rules of Tree Construction

  1. Start at the final scalar output (LL) and inspect its formula: L=12(y−a2)2L = \frac{1}{2}(y - a_2)^2.
  2. Branch to every changeable variable inside that formula (a2a_2).
  3. Continue or Terminate: If a variable is computed via its own equation (like a2,a0,a1,z0,z1a_2, a_0, a_1, z_0, z_1), draw branches to its components. If a variable is a raw tunable parameter (w0…w5,b0…b2w_0 \dots w_5, b_0 \dots b_2), the branch stops (shown in brackets [ ]).
  4. Treat Dataset Values as Constants: The inputs (x0,x1x_0, x_1) and true label (yy) are fixed observations from the dataset. Since we cannot modify the dataset, they act as constants and never receive branches.

Multivariable Chain Rule Dependency Tree

TEXT
                  ∂a₂/∂w₄ = a₀
               ┌───────────────► [w₄]
               │  ∂a₂/∂b₂ = 1
               ├───────────────► [b₂]
               │  ∂a₂/∂w₅ = a₁
    ∂L/∂a₂     ├───────────────► [w₅]
L ───────────► a₂                                           ┌──► [w₀] (∂z₀/∂w₀ = x₀)
 (a₂ - y)      │  ∂a₂/∂a₀ = w₄     ∂a₀/∂z₀ = a₀(1-a₀)       │
               ├───────────────► a₀ ──────────────────► z₀ ─┼──► [w₂] (∂z₀/∂w₂ = x₁)
               │                                            │
               │                                            └──► [b₀] (∂z₀/∂b₀ = 1)
               │
               │                                            ┌──► [w₁] (∂z₁/∂w₁ = x₀)
               │  ∂a₂/∂a₁ = w₅     ∂a₁/∂z₁ = a₁(1-a₁)       │
               └───────────────► a₁ ──────────────────► z₁ ─┼──► [w₃] (∂z₁/∂w₃ = x₁)
                                                            │
                                                            └──► [b₁] (∂z₁/∂b₁ = 1)

Reading the Tree: All 9 Partial Derivatives

To find the partial derivative of LL with respect to any parameter [θ][\theta], trace the unique path from LL to [θ][\theta] and multiply every branch derivative along that path:

  • Root Error Signal (L→a2L \to a_2): ∂L∂a2=12⋅2(y−a2)⋅(−1)=a2−y\frac{\partial L}{\partial a_2} = \frac{1}{2} \cdot 2(y - a_2) \cdot (-1) = a_2 - y

  • Output Layer Parameters (2-step paths: L→a2→θL \to a_2 \to \theta): ∂L∂w4=(∂L∂a2)(∂a2∂w4)=(a2−y)a0\frac{\partial L}{\partial w_4} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial w_4}\right) = (a_2 - y)a_0 ∂L∂w5=(∂L∂a2)(∂a2∂w5)=(a2−y)a1\frac{\partial L}{\partial w_5} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial w_5}\right) = (a_2 - y)a_1 ∂L∂b2=(∂L∂a2)(∂a2∂b2)=(a2−y)(1)=a2−y\frac{\partial L}{\partial b_2} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial b_2}\right) = (a_2 - y)(1) = a_2 - y

  • Top Hidden Node Parameters (4-step paths: L→a2→a0→z0→θL \to a_2 \to a_0 \to z_0 \to \theta): ∂L∂w0=(∂L∂a2)(∂a2∂a0)(∂a0∂z0)(∂z0∂w0)=(a2−y)w4a0(1−a0)x0\frac{\partial L}{\partial w_0} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial a_0}\right)\left(\frac{\partial a_0}{\partial z_0}\right)\left(\frac{\partial z_0}{\partial w_0}\right) = (a_2 - y)w_4 a_0(1 - a_0)x_0 ∂L∂w2=(∂L∂a2)(∂a2∂a0)(∂a0∂z0)(∂z0∂w2)=(a2−y)w4a0(1−a0)x1\frac{\partial L}{\partial w_2} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial a_0}\right)\left(\frac{\partial a_0}{\partial z_0}\right)\left(\frac{\partial z_0}{\partial w_2}\right) = (a_2 - y)w_4 a_0(1 - a_0)x_1 ∂L∂b0=(∂L∂a2)(∂a2∂a0)(∂a0∂z0)(∂z0∂b0)=(a2−y)w4a0(1−a0)(1)\frac{\partial L}{\partial b_0} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial a_0}\right)\left(\frac{\partial a_0}{\partial z_0}\right)\left(\frac{\partial z_0}{\partial b_0}\right) = (a_2 - y)w_4 a_0(1 - a_0)(1)

  • Bottom Hidden Node Parameters (4-step paths: L→a2→a1→z1→θL \to a_2 \to a_1 \to z_1 \to \theta): ∂L∂w1=(∂L∂a2)(∂a2∂a1)(∂a1∂z1)(∂z1∂w1)=(a2−y)w5a1(1−a1)x0\frac{\partial L}{\partial w_1} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial a_1}\right)\left(\frac{\partial a_1}{\partial z_1}\right)\left(\frac{\partial z_1}{\partial w_1}\right) = (a_2 - y)w_5 a_1(1 - a_1)x_0 ∂L∂w3=(∂L∂a2)(∂a2∂a1)(∂a1∂z1)(∂z1∂w3)=(a2−y)w5a1(1−a1)x1\frac{\partial L}{\partial w_3} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial a_1}\right)\left(\frac{\partial a_1}{\partial z_1}\right)\left(\frac{\partial z_1}{\partial w_3}\right) = (a_2 - y)w_5 a_1(1 - a_1)x_1 ∂L∂b1=(∂L∂a2)(∂a2∂a1)(∂a1∂z1)(∂z1∂b1)=(a2−y)w5a1(1−a1)(1)\frac{\partial L}{\partial b_1} = \left(\frac{\partial L}{\partial a_2}\right)\left(\frac{\partial a_2}{\partial a_1}\right)\left(\frac{\partial a_1}{\partial z_1}\right)\left(\frac{\partial z_1}{\partial b_1}\right) = (a_2 - y)w_5 a_1(1 - a_1)(1)

(Note: Why are there no ++ signs between paths like in general multivariable chain rule problems? Because each weight wiw_i appears in only one place in the network, meaning there is only a single path from LL 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 η\eta:

θnew=θold−η⋅∂L∂θ\theta_{\text{new}} = \theta_{\text{old}} - \eta \cdot \frac{\partial L}{\partial \theta}

Why We Cannot Simply Add or Subtract a Fixed Constant

What if we ignored the derivative equations and simply subtracted a fixed 0.10.1 from every weight whenever the network's output was too high? Two immediate failures occur:

  1. Sign Reversals Through Negative Weights: Suppose output weight w4=−0.8w_4 = -0.8 (negative) and our prediction a2a_2 is too high. Because a0a_0 is multiplied by a negative weight (w4=−0.8w_4 = -0.8), reducing w0w_0 makes a0a_0 smaller, which makes w4a0w_4 a_0 less negative, pushing a2a_2 higher and worsening the error! The chain rule equation: ∂L∂w0=(a2−y)w4a0(1−a0)x0\frac{\partial L}{\partial w_0} = (a_2 - y) w_4 a_0(1 - a_0) x_0 multiplies by w4w_4, automatically flipping the derivative's sign so our subtraction moves w0w_0 in the true error-reducing direction.
  2. Proportional Credit Assignment (Inactive Inputs): Consider z0=w0x0+w2x1z_0 = w_0 x_0 + w_2 x_1. If an input has measurements x0=10x_0 = 10 and x1=0x_1 = 0, weight w2w_2 was multiplied by 00 — it contributed nothing to the output error. Because ∂L∂w2\frac{\partial L}{\partial w_2} multiplies by x1=0x_1 = 0, the formula automatically yields ∂L∂w2=0\frac{\partial L}{\partial w_2} = 0, leaving w2w_2 untouched while giving w0w_0 a large update proportional to x0=10x_0 = 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)(\eta \times \text{derivative}) from that parameter.


5. Worked Numerical Examples (Squared-Error Loss)

The Forward and Backward Pass Execution

Example A: Network Guesses Too Low (Negative Derivatives →\to Weights Increase)

  • Inputs & Target: x0=2.0,x1=1.0x_0 = 2.0, x_1 = 1.0, True Label y=1.0y = 1.0 (Class 1), Learning Rate η=0.5\eta = 0.5
  • Initial Hidden Parameters: w0=w1=w2=w3=b0=b1=0.0w_0 = w_1 = w_2 = w_3 = b_0 = b_1 = 0.0
  • Initial Output Parameters: w4=0.4,w5=0.6,b2=0.0w_4 = 0.4, w_5 = 0.6, b_2 = 0.0

Step 1: Forward Pass

  • z0=(0)(2.0)+(0)(1.0)+0=0  ⟹  a0=σ(0)=0.5z_0 = (0)(2.0) + (0)(1.0) + 0 = 0 \implies a_0 = \sigma(0) = \mathbf{0.5}
  • z1=(0)(2.0)+(0)(1.0)+0=0  ⟹  a1=σ(0)=0.5z_1 = (0)(2.0) + (0)(1.0) + 0 = 0 \implies a_1 = \sigma(0) = \mathbf{0.5}
  • a2=(0.4)(0.5)+(0.6)(0.5)+0.0=0.50a_2 = (0.4)(0.5) + (0.6)(0.5) + 0.0 = \mathbf{0.50}
  • Loss: L=12(1.0−0.5)2=0.125L = \frac{1}{2}(1.0 - 0.5)^2 = \mathbf{0.125}

Step 2: Backward Pass (Plugging into the 9 Derivative Formulas)

  • Root Signal: ∂L∂a2=a2−y=0.5−1.0=−0.5\frac{\partial L}{\partial a_2} = a_2 - y = 0.5 - 1.0 = \mathbf{-0.5}
  • Sigmoid Slopes: a0(1−a0)=0.5(0.5)=0.25a_0(1 - a_0) = 0.5(0.5) = \mathbf{0.25}, and a1(1−a1)=0.25a_1(1 - a_1) = \mathbf{0.25}
  • Output Gradients: ∂L∂w4=(−0.5)(0.5)=−0.25\frac{\partial L}{\partial w_4} = (-0.5)(0.5) = \mathbf{-0.25} ∂L∂w5=(−0.5)(0.5)=−0.25\frac{\partial L}{\partial w_5} = (-0.5)(0.5) = \mathbf{-0.25} ∂L∂b2=−0.50\frac{\partial L}{\partial b_2} = \mathbf{-0.50}
  • Hidden Gradients: ∂L∂w0=(−0.5)(0.4)(0.25)(2.0)=−0.10\frac{\partial L}{\partial w_0} = (-0.5)(0.4)(0.25)(2.0) = \mathbf{-0.10} ∂L∂w2=(−0.5)(0.4)(0.25)(1.0)=−0.05\frac{\partial L}{\partial w_2} = (-0.5)(0.4)(0.25)(1.0) = \mathbf{-0.05} ∂L∂b0=(−0.5)(0.4)(0.25)(1.0)=−0.05\frac{\partial L}{\partial b_0} = (-0.5)(0.4)(0.25)(1.0) = \mathbf{-0.05} ∂L∂w1=(−0.5)(0.6)(0.25)(2.0)=−0.15\frac{\partial L}{\partial w_1} = (-0.5)(0.6)(0.25)(2.0) = \mathbf{-0.15} ∂L∂w3=(−0.5)(0.6)(0.25)(1.0)=−0.075\frac{\partial L}{\partial w_3} = (-0.5)(0.6)(0.25)(1.0) = \mathbf{-0.075} ∂L∂b1=(−0.5)(0.6)(0.25)(1.0)=−0.075\frac{\partial L}{\partial b_1} = (-0.5)(0.6)(0.25)(1.0) = \mathbf{-0.075}

Step 3: Gradient Descent Update (θnew=θold−0.5⋅derivative\theta_{\text{new}} = \theta_{\text{old}} - 0.5 \cdot \text{derivative})

Subtracting negative numbers adds to each parameter:

  • w4new=0.4−(0.5)(−0.25)=0.525w_4^{\text{new}} = 0.4 - (0.5)(-0.25) = \mathbf{0.525}
  • w5new=0.6−(0.5)(−0.25)=0.725w_5^{\text{new}} = 0.6 - (0.5)(-0.25) = \mathbf{0.725}
  • b2new=0.0−(0.5)(−0.50)=0.250b_2^{\text{new}} = 0.0 - (0.5)(-0.50) = \mathbf{0.250}
  • w0new=0.050,w2new=0.025,b0new=0.025w_0^{\text{new}} = \mathbf{0.050}, \quad w_2^{\text{new}} = \mathbf{0.025}, \quad b_0^{\text{new}} = \mathbf{0.025}
  • w1new=0.075,w3new=0.0375,b1new=0.0375w_1^{\text{new}} = \mathbf{0.075}, \quad w_3^{\text{new}} = \mathbf{0.0375}, \quad b_1^{\text{new}} = \mathbf{0.0375}

Step 4: Verification Pass

Re-running (x0=2.0,x1=1.0)(x_0 = 2.0, x_1 = 1.0) with the updated weights gives:

  • z0=(0.050)(2.0)+(0.025)(1.0)+0.025=0.15  ⟹  a0=σ(0.15)≈0.537z_0 = (0.050)(2.0) + (0.025)(1.0) + 0.025 = 0.15 \implies a_0 = \sigma(0.15) \approx \mathbf{0.537}
  • z1=(0.075)(2.0)+(0.0375)(1.0)+0.0375=0.225  ⟹  a1=σ(0.225)≈0.556z_1 = (0.075)(2.0) + (0.0375)(1.0) + 0.0375 = 0.225 \implies a_1 = \sigma(0.225) \approx \mathbf{0.556}
  • a2new=(0.525)(0.537)+(0.725)(0.556)+0.250=0.935a_2^{\text{new}} = (0.525)(0.537) + (0.725)(0.556) + 0.250 = \mathbf{0.935} (Moved from 0.500.50 right up to 0.9350.935 toward target 1.01.0!)
  • Lnew=12(1.0−0.935)2=0.0021L^{\text{new}} = \frac{1}{2}(1.0 - 0.935)^2 = \mathbf{0.0021} (98% error reduction in a single step).

Example B: Network Guesses Too High (Positive Derivatives →\to Weights Decrease)

  • Inputs & Target: x0=4.0,x1=2.0x_0 = 4.0, x_1 = 2.0, True Label y=0.0y = 0.0 (Class 0), Learning Rate η=0.5\eta = 0.5
  • Initial Hidden Parameters: w0=w1=w2=w3=b0=b1=0.0w_0 = w_1 = w_2 = w_3 = b_0 = b_1 = 0.0
  • Initial Output Parameters: w4=0.8,w5=0.4,b2=0.2w_4 = 0.8, w_5 = 0.4, b_2 = 0.2

Step 1: Forward Pass

  • z0=0  ⟹  a0=0.5z_0 = 0 \implies a_0 = \mathbf{0.5}, and z1=0  ⟹  a1=0.5z_1 = 0 \implies a_1 = \mathbf{0.5}
  • a2=(0.8)(0.5)+(0.4)(0.5)+0.2=0.80a_2 = (0.8)(0.5) + (0.4)(0.5) + 0.2 = \mathbf{0.80}
  • Loss: L=12(0.0−0.8)2=0.32L = \frac{1}{2}(0.0 - 0.8)^2 = \mathbf{0.32}

Step 2: Backward Pass

  • Root Signal: ∂L∂a2=0.8−0.0=+0.80\frac{\partial L}{\partial a_2} = 0.8 - 0.0 = \mathbf{+0.80} (Positive because prediction 0.80.8 exceeds target 0.00.0)
  • Output Gradients: ∂L∂w4=(+0.8)(0.5)=+0.40,∂L∂w5=(+0.8)(0.5)=+0.40,∂L∂b2=+0.80\frac{\partial L}{\partial w_4} = (+0.8)(0.5) = \mathbf{+0.40}, \quad \frac{\partial L}{\partial w_5} = (+0.8)(0.5) = \mathbf{+0.40}, \quad \frac{\partial L}{\partial b_2} = \mathbf{+0.80}
  • Hidden Gradients: ∂L∂w0=(+0.8)(0.8)(0.25)(4.0)=+0.64\frac{\partial L}{\partial w_0} = (+0.8)(0.8)(0.25)(4.0) = \mathbf{+0.64} ∂L∂w2=(+0.8)(0.8)(0.25)(2.0)=+0.32\frac{\partial L}{\partial w_2} = (+0.8)(0.8)(0.25)(2.0) = \mathbf{+0.32} ∂L∂b0=(+0.8)(0.8)(0.25)(1.0)=+0.16\frac{\partial L}{\partial b_0} = (+0.8)(0.8)(0.25)(1.0) = \mathbf{+0.16} ∂L∂w1=(+0.8)(0.4)(0.25)(4.0)=+0.32\frac{\partial L}{\partial w_1} = (+0.8)(0.4)(0.25)(4.0) = \mathbf{+0.32} ∂L∂w3=(+0.8)(0.4)(0.25)(2.0)=+0.16\frac{\partial L}{\partial w_3} = (+0.8)(0.4)(0.25)(2.0) = \mathbf{+0.16} ∂L∂b1=(+0.8)(0.4)(0.25)(1.0)=+0.08\frac{\partial L}{\partial b_1} = (+0.8)(0.4)(0.25)(1.0) = \mathbf{+0.08}

Step 3: Parameter Update (θnew=θold−0.5⋅derivative\theta_{\text{new}} = \theta_{\text{old}} - 0.5 \cdot \text{derivative})

Subtracting positive numbers pushes every parameter down:

  • w4new=0.8−(0.5)(0.40)=0.60w_4^{\text{new}} = 0.8 - (0.5)(0.40) = \mathbf{0.60}
  • w5new=0.4−(0.5)(0.40)=0.20w_5^{\text{new}} = 0.4 - (0.5)(0.40) = \mathbf{0.20}
  • b2new=0.2−(0.5)(0.80)=−0.20b_2^{\text{new}} = 0.2 - (0.5)(0.80) = \mathbf{-0.20}
  • w0new=−0.32,w2new=−0.16,b0new=−0.08w_0^{\text{new}} = \mathbf{-0.32}, \quad w_2^{\text{new}} = \mathbf{-0.16}, \quad b_0^{\text{new}} = \mathbf{-0.08}
  • w1new=−0.16,w3new=−0.08,b1new=−0.04w_1^{\text{new}} = \mathbf{-0.16}, \quad w_3^{\text{new}} = \mathbf{-0.08}, \quad b_1^{\text{new}} = \mathbf{-0.04}

Step 4: Verification Pass

Re-running (4.0,2.0)(4.0, 2.0) through the updated parameters yields:

  • z0=(−0.32)(4.0)+(−0.16)(2.0)−0.08=−1.68  ⟹  a0=σ(−1.68)≈0.157z_0 = (-0.32)(4.0) + (-0.16)(2.0) - 0.08 = -1.68 \implies a_0 = \sigma(-1.68) \approx \mathbf{0.157}
  • z1=(−0.16)(4.0)+(−0.08)(2.0)−0.04=−0.84  ⟹  a1=σ(−0.84)≈0.301z_1 = (-0.16)(4.0) + (-0.08)(2.0) - 0.04 = -0.84 \implies a_1 = \sigma(-0.84) \approx \mathbf{0.301}
  • a2new=(0.60)(0.157)+(0.20)(0.301)−0.20=−0.046a_2^{\text{new}} = (0.60)(0.157) + (0.20)(0.301) - 0.20 = \mathbf{-0.046} (Dropped from 0.800.80 right down to −0.046≈0.0-0.046 \approx 0.0!)
  • Lnew=12(0.0−(−0.046))2≈0.001L^{\text{new}} = \frac{1}{2}(0.0 - (-0.046))^2 \approx \mathbf{0.001}

6. Evaluation Metrics: Decoding the Confusion Matrix

While the Loss function LL guides gradient descent with continuous numbers, classification performance is evaluated by thresholding the continuous prediction (c=0c = 0 if a2<0.5a_2 < 0.5 else 11) and tallying four outcomes:

  • Second Word (Positive / Negative) = What the Network Predicted (cc): Positive means c=1c = 1; Negative means c=0c = 0.
  • First Word (True / False) = Whether the Prediction Matched Reality (c==yc == y): True means correct; False means incorrect.
MetricPrediction (cc)True Label (yy)Meaning
TN (True Negative)00Correct Rejection: Network predicted Class 0, actual was Class 0.
TP (True Positive)11Correct Hit: Network predicted Class 1, actual was Class 1.
FP (False Positive)10False Alarm (Type I Error): Network predicted Class 1, actual was Class 0.
FN (False Negative)01Missed 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+TPTN+FP+FN+TP(Overall fraction of correct predictions)\text{Accuracy} = \frac{TN + TP}{TN + FP + FN + TP} \quad \text{(Overall fraction of correct predictions)}
  • Precision: Precision=TPTP+FP(How often positive predictions are actually correct)\text{Precision} = \frac{TP}{TP + FP} \quad \text{(How often positive predictions are actually correct)}
  • Recall (Sensitivity): Recall=TPTP+FN(Fraction of actual positives successfully detected)\text{Recall} = \frac{TP}{TP + FN} \quad \text{(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)=11+e−z2z_2 = w_4 a_0 + w_5 a_1 + b_2 \quad \implies \quad a_2 = \sigma(z_2) = \frac{1}{1 + e^{-z_2}}

  • Binary Cross-Entropy Loss Formula: L=−[yln⁡(a2)+(1−y)ln⁡(1−a2)]L = -\Big[y \ln(a_2) + (1 - y) \ln(1 - a_2)\Big]

Why BCE + Sigmoid Beats Squared Error + Sigmoid

If you apply Squared Error to a sigmoid output, the root gradient with respect to z2z_2 is (a2−y)⋅a2(1−a2)(a_2 - y) \cdot a_2(1 - a_2). When the network is confidently wrong (e.g., y=1,a2=0.001y = 1, a_2 = 0.001), the sigmoid slope a2(1−a2)≈0.001a_2(1 - a_2) \approx 0.001 crushes the gradient (vanishing gradient), slowing learning to a standstill.

With BCE, the derivative with respect to a2a_2 and the sigmoid derivative cancel each other out completely:

∂L∂a2=−ya2+1−y1−a2=a2−ya2(1−a2)\frac{\partial L}{\partial a_2} = -\frac{y}{a_2} + \frac{1 - y}{1 - a_2} = \frac{a_2 - y}{a_2(1 - a_2)}

Multiplying by the sigmoid derivative ∂a2∂z2=a2(1−a2)\frac{\partial a_2}{\partial z_2} = a_2(1 - a_2) via the chain rule:

∂L∂z2=(∂L∂a2)(∂a2∂z2)=[a2−ya2(1−a2)]⋅[a2(1−a2)]=a2−y\frac{\partial L}{\partial z_2} = \left(\frac{\partial L}{\partial a_2}\right) \left(\frac{\partial a_2}{\partial z_2}\right) = \left[\frac{a_2 - y}{a_2(1 - a_2)}\right] \cdot \big[a_2(1 - a_2)\big] = \mathbf{a_2 - y}

The saturation term a2(1−a2)a_2(1 - a_2) vanishes from the denominator and numerator! Even if a2=0.001a_2 = 0.001 when y=1y = 1, the error signal is 0.001−1.0=−0.9990.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.5x_0 = 2.0, x_1 = 1.0, y = 1.0, \eta = 0.5
  • Initial Parameters: w0=w1=w2=w3=b0=b1=0.0w_0 = w_1 = w_2 = w_3 = b_0 = b_1 = 0.0, and w4=−0.8,w5=−1.2,b2=−1.0w_4 = -0.8, w_5 = -1.2, b_2 = -1.0

Step 1: Forward Pass

  • z0=0  ⟹  a0=0.5z_0 = 0 \implies a_0 = \mathbf{0.5}, and z1=0  ⟹  a1=0.5z_1 = 0 \implies a_1 = \mathbf{0.5}
  • z2=(−0.8)(0.5)+(−1.2)(0.5)−1.0=−0.4−0.6−1.0=−2.0z_2 = (-0.8)(0.5) + (-1.2)(0.5) - 1.0 = -0.4 - 0.6 - 1.0 = \mathbf{-2.0}
  • a2=σ(−2.0)=11+e2.0≈0.119a_2 = \sigma(-2.0) = \frac{1}{1 + e^{2.0}} \approx \mathbf{0.119} (11.9%11.9\% predicted probability for Class 1)
  • BCE Loss: L=−[(1.0)ln⁡(0.119)+0]=−ln⁡(0.119)≈2.129L = -\big[(1.0)\ln(0.119) + 0\big] = -\ln(0.119) \approx \mathbf{2.129}

Step 2: Backward Pass (Verifying the Cancellation Numerically)

  • Root Signal directly at z2z_2: δ2=∂L∂z2=a2−y=0.119−1.0=−0.881\delta_2 = \frac{\partial L}{\partial z_2} = a_2 - y = 0.119 - 1.0 = \mathbf{-0.881}
  • Output Gradients: ∂L∂w4=δ2⋅a0=(−0.881)(0.5)=−0.4405\frac{\partial L}{\partial w_4} = \delta_2 \cdot a_0 = (-0.881)(0.5) = \mathbf{-0.4405} ∂L∂w5=δ2⋅a1=(−0.881)(0.5)=−0.4405\frac{\partial L}{\partial w_5} = \delta_2 \cdot a_1 = (-0.881)(0.5) = \mathbf{-0.4405} ∂L∂b2=δ2=−0.8810\frac{\partial L}{\partial b_2} = \delta_2 = \mathbf{-0.8810}
  • Hidden Gradients (Note sign flip due to negative w4,w5w_4, w_5): δ0=∂L∂z0=δ2⋅w4⋅a0(1−a0)=(−0.881)(−0.8)(0.25)=+0.1762\delta_0 = \frac{\partial L}{\partial z_0} = \delta_2 \cdot w_4 \cdot a_0(1 - a_0) = (-0.881)(-0.8)(0.25) = \mathbf{+0.1762} ∂L∂w0=δ0⋅x0=(+0.1762)(2.0)=+0.3524\frac{\partial L}{\partial w_0} = \delta_0 \cdot x_0 = (+0.1762)(2.0) = \mathbf{+0.3524} ∂L∂w2=δ0⋅x1=(+0.1762)(1.0)=+0.1762,∂L∂b0=+0.1762\frac{\partial L}{\partial w_2} = \delta_0 \cdot x_1 = (+0.1762)(1.0) = \mathbf{+0.1762}, \quad \frac{\partial L}{\partial b_0} = \mathbf{+0.1762} δ1=∂L∂z1=δ2⋅w5⋅a1(1−a1)=(−0.881)(−1.2)(0.25)=+0.2643\delta_1 = \frac{\partial L}{\partial z_1} = \delta_2 \cdot w_5 \cdot a_1(1 - a_1) = (-0.881)(-1.2)(0.25) = \mathbf{+0.2643} ∂L∂w1=δ1⋅x0=(+0.2643)(2.0)=+0.5286\frac{\partial L}{\partial w_1} = \delta_1 \cdot x_0 = (+0.2643)(2.0) = \mathbf{+0.5286} ∂L∂w3=δ1⋅x1=(+0.2643)(1.0)=+0.2643,∂L∂b1=+0.2643\frac{\partial L}{\partial w_3} = \delta_1 \cdot x_1 = (+0.2643)(1.0) = \mathbf{+0.2643}, \quad \frac{\partial L}{\partial b_1} = \mathbf{+0.2643}

Step 3: Parameter Update & Verification

  • w4new=−0.8−(0.5)(−0.4405)=−0.5798w_4^{\text{new}} = -0.8 - (0.5)(-0.4405) = \mathbf{-0.5798}
  • w5new=−1.2−(0.5)(−0.4405)=−0.9798w_5^{\text{new}} = -1.2 - (0.5)(-0.4405) = \mathbf{-0.9798}
  • b2new=−1.0−(0.5)(−0.8810)=−0.5595b_2^{\text{new}} = -1.0 - (0.5)(-0.8810) = \mathbf{-0.5595}
  • w0new=0.0−(0.5)(0.3524)=−0.1762,w2new=−0.0881,b0new=−0.0881w_0^{\text{new}} = 0.0 - (0.5)(0.3524) = \mathbf{-0.1762}, \quad w_2^{\text{new}} = \mathbf{-0.0881}, \quad b_0^{\text{new}} = \mathbf{-0.0881}
  • w1new=0.0−(0.5)(0.5286)=−0.2643,w3new=−0.1322,b1new=−0.1322w_1^{\text{new}} = 0.0 - (0.5)(0.5286) = \mathbf{-0.2643}, \quad w_3^{\text{new}} = \mathbf{-0.1322}, \quad b_1^{\text{new}} = \mathbf{-0.1322}

New Forward Pass:

  • z0new=(−0.1762)(2.0)+(−0.0881)(1.0)−0.0881=−0.5286  ⟹  a0≈0.371z_0^{\text{new}} = (-0.1762)(2.0) + (-0.0881)(1.0) - 0.0881 = -0.5286 \implies a_0 \approx \mathbf{0.371}
  • z1new=(−0.2643)(2.0)+(−0.1322)(1.0)−0.1322=−0.7930  ⟹  a1≈0.311z_1^{\text{new}} = (-0.2643)(2.0) + (-0.1322)(1.0) - 0.1322 = -0.7930 \implies a_1 \approx \mathbf{0.311}
  • z2new=(−0.5798)(0.371)+(−0.9798)(0.311)−0.5595=−1.080z_2^{\text{new}} = (-0.5798)(0.371) + (-0.9798)(0.311) - 0.5595 = \mathbf{-1.080}
  • a2new=σ(−1.080)=11+e1.080≈0.254a_2^{\text{new}} = \sigma(-1.080) = \frac{1}{1 + e^{1.080}} \approx \mathbf{0.254}
  • Lnew=−ln⁡(0.254)≈1.370L^{\text{new}} = -\ln(0.254) \approx \mathbf{1.370}

(Predicted probability of Class 1 more than doubled from 11.9%11.9\% to 25.4%25.4\%, and BCE loss dropped from 2.1292.129 to 1.3701.370 in one step!)


8. Method 2: Stanford CS229 Vectorized Derivation & Matrix Dimension Rules

In advanced courses like Stanford CS229, rather than writing separate equations for every weight, parameters are grouped into Matrices (W[l]W^{[l]}) and Column Vectors (a[l],b[l]a^{[l]}, b^{[l]}).

Direct Substitution Derivation (Stanford Whiteboard Method)

To find the gradient of the BCE loss L(i)\mathcal{L}^{(i)} with respect to the output weight matrix W[3]W^{[3]}, substitute y^(i)=a[3]=σ(W[3]a[2]+b[3])\hat{y}^{(i)} = a^{[3]} = \sigma(W^{[3]}a^{[2]} + b^{[3]}) directly into the loss function and differentiate in one vectorized line:

L(i)=−[y(i)log⁡(σ(W[3]a[2]+b[3]))+(1−y(i))log⁡(1−σ(W[3]a[2]+b[3]))]\mathcal{L}^{(i)} = -\left[ y^{(i)}\log\big(\sigma(W^{[3]}a^{[2]} + b^{[3]})\big) + (1 - y^{(i)})\log\big(1 - \sigma(W^{[3]}a^{[2]} + b^{[3]})\big) \right]

Applying (log⁡u)′=1u(\log u)' = \frac{1}{u}, σ′(z)=a[3](1−a[3])\sigma'(z) = a^{[3]}(1 - a^{[3]}), and ∂(W[3]a[2]+b[3])∂W[3]=(a[2])T\frac{\partial (W^{[3]}a^{[2]} + b^{[3]})}{\partial W^{[3]}} = (a^{[2]})^T:

∂L(i)∂W[3]=−[y(i)a[3]⋅a[3](1−a[3])(a[2])T−1−y(i)1−a[3]⋅a[3](1−a[3])(a[2])T]\frac{\partial \mathcal{L}^{(i)}}{\partial W^{[3]}} = -\left[ \frac{y^{(i)}}{a^{[3]}} \cdot a^{[3]}(1 - a^{[3]})(a^{[2]})^T - \frac{1 - y^{(i)}}{1 - a^{[3]}} \cdot a^{[3]}(1 - a^{[3]})(a^{[2]})^T \right]

Expanding and canceling the −y(i)a[3](a[2])T-y^{(i)}a^{[3]}(a^{[2]})^T and +y(i)a[3](a[2])T+y^{(i)}a^{[3]}(a^{[2]})^T terms:

∂L(i)∂W[3]=−[y(i)(1−a[3])(a[2])T−(1−y(i))a[3](a[2])T]\frac{\partial \mathcal{L}^{(i)}}{\partial W^{[3]}} = -\left[ y^{(i)}(1 - a^{[3]})(a^{[2]})^T - (1 - y^{(i)})a^{[3]}(a^{[2]})^T \right] =−[y(i)−y(i)a[3]−a[3]+y(i)a[3]](a[2])T=−[y(i)−a[3]](a[2])T=(a[3]−y(i))(a[2])T= -\left[ y^{(i)} - y^{(i)}a^{[3]} - a^{[3]} + y^{(i)}a^{[3]} \right](a^{[2]})^T = -\left[ y^{(i)} - a^{[3]} \right](a^{[2]})^T = \mathbf{(a^{[3]} - y^{(i)})(a^{[2]})^T}

Averaging over mm training examples gives the total cost gradient:

∂J∂W[3]=1m∑i=1m(a[3](i)−y(i))(a[2](i))T\frac{\partial \mathcal{J}}{\partial W^{[3]}} = \frac{1}{m} \sum_{i=1}^m \big(a^{[3](i)} - y^{(i)}\big)\big(a^{[2](i)}\big)^T

The 4 Unbreakable Rules of Matrix Dimensions

How do you instantly know the shape of every matrix and why (a[2])T(a^{[2]})^T requires a transpose? Follow these four rules:

  1. Activations (a[l],z[l]a^{[l]}, z^{[l]}), Biases (b[l]b^{[l]}), and Error Signals (δ[l]\delta^{[l]}) Are Column Vectors: For a single sample, if Layer ll has nln_l nodes, its vector has shape (nl,1)(n_l, 1).
  2. Weight Matrix W[l]W^{[l]} Has Shape (Current Layer Nodes, Previous Layer Nodes): W[l]∈Rnl×nl−1W^{[l]} \in \mathbb{R}^{n_l \times n_{l-1}} This guarantees that the inner dimensions match during the forward pass: z[l]⏟(nl×1)=W[l]⏟(nl×nl−1)⋅a[l−1]⏟(nl−1×1)+b[l]⏟(nl×1)\underbrace{z^{[l]}}_{(n_l \times 1)} = \underbrace{W^{[l]}}_{(n_l \times n_{l-1})} \cdot \underbrace{a^{[l-1]}}_{(n_{l-1} \times 1)} + \underbrace{b^{[l]}}_{(n_l \times 1)}
  3. A Gradient ∂L∂W[l]\frac{\partial \mathcal{L}}{\partial W^{[l]}} ALWAYS Has the Exact Same Shape as W[l]W^{[l]}: Because the update rule subtracts the gradient from the weight matrix (W[l]←W[l]−η∂J∂W[l]W^{[l]} \leftarrow W^{[l]} - \eta \frac{\partial \mathcal{J}}{\partial W^{[l]}}), both matrices must have shape (nl,nl−1)(n_l, n_{l-1}).
  4. The Transpose Rule for Weight Gradients: To form an (nl×nl−1)(n_l \times n_{l-1}) matrix by multiplying the current layer's column error vector δ[l]\delta^{[l]} of shape (nl,1)(n_l, 1) and the previous layer's activation vector a[l−1]a^{[l-1]} of shape (nl−1,1)(n_{l-1}, 1), you must transpose a[l−1]a^{[l-1]} into a row vector (1×nl−1)(1 \times n_{l-1}): ∂L∂W[l]⏟(nl×nl−1)=δ[l]⏟(nl×1)⋅(a[l−1])T⏟(1×nl−1)\underbrace{\frac{\partial \mathcal{L}}{\partial W^{[l]}}}_{(n_l \times n_{l-1})} = \underbrace{\delta^{[l]}}_{(n_l \times 1)} \cdot \underbrace{(a^{[l-1]})^T}_{(1 \times n_{l-1})}

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):

TEXT
  Layer 1 (Input)         Layer 2 (Hidden)         Layer 3 (Output)
     3 Nodes                  4 Nodes                  2 Nodes
   a^[1]: (3 × 1)           a^[2]: (4 × 1)           a^[3]: (2 × 1)
                  W^[2]: (4 × 3)           W^[3]: (2 × 4)
  • Forward Pass Shapes:

    • Hidden pre-activation: z[2]=W[2]a[1]+b[2]  ⟹  (4×3)(3×1)+(4×1)=(4×1)z^{[2]} = W^{[2]}a^{[1]} + b^{[2]} \implies (4 \times 3)(3 \times 1) + (4 \times 1) = \mathbf{(4 \times 1)}
    • Hidden activation: a[2]=σ(z[2])  ⟹  (4×1)a^{[2]} = \sigma(z^{[2]}) \implies \mathbf{(4 \times 1)}
    • Output pre-activation: z[3]=W[3]a[2]+b[3]  ⟹  (2×4)(4×1)+(2×1)=(2×1)z^{[3]} = W^{[3]}a^{[2]} + b^{[3]} \implies (2 \times 4)(4 \times 1) + (2 \times 1) = \mathbf{(2 \times 1)}
    • Output activation: a[3]=σ(z[3])  ⟹  (2×1)a^{[3]} = \sigma(z^{[3]}) \implies \mathbf{(2 \times 1)}
  • Backward Pass Shapes:

    • Output error vector: δ[3]=a[3]−y  ⟹  (2×1)\delta^{[3]} = a^{[3]} - y \implies \mathbf{(2 \times 1)}
    • Output weight gradient: ∂L∂W[3]=δ(2×1)[3]⋅(a[2])(1×4)T  ⟹  (2×4)\frac{\partial \mathcal{L}}{\partial W^{[3]}} = \delta^{[3]}_{(2 \times 1)} \cdot (a^{[2]})^T_{(1 \times 4)} \implies \mathbf{(2 \times 4)} (Matches W[3]W^{[3]}!)
    • Output bias gradient: ∂L∂b[3]=δ[3]  ⟹  (2×1)\frac{\partial \mathcal{L}}{\partial b^{[3]}} = \delta^{[3]} \implies \mathbf{(2 \times 1)}
    • Hidden error vector (propagated backward via (W[3])T(W^{[3]})^T): δ[2]=((W[3])Tδ[3])⊙σ′(z[2])  ⟹  ((4×2)(2×1))⊙(4×1)=(4×1)\delta^{[2]} = \Big((W^{[3]})^T \delta^{[3]}\Big) \odot \sigma'(z^{[2]}) \implies \Big((4 \times 2)(2 \times 1)\Big) \odot (4 \times 1) = \mathbf{(4 \times 1)}
    • Hidden weight gradient: ∂L∂W[2]=δ(4×1)[2]⋅(a[1])(1×3)T  ⟹  (4×3)\frac{\partial \mathcal{L}}{\partial W^{[2]}} = \delta^{[2]}_{(4 \times 1)} \cdot (a^{[1]})^T_{(1 \times 3)} \implies \mathbf{(4 \times 3)} (Matches W[2]W^{[2]}!)
    • Hidden bias gradient: ∂L∂b[2]=δ[2]  ⟹  (4×1)\frac{\partial \mathcal{L}}{\partial b^{[2]}} = \delta^{[2]} \implies \mathbf{(4 \times 1)}

9. Complete Python Implementation (Scalar vs. Vectorized)

Below is the side-by-side Python implementation showing how the 9 scalar equations from Method 1 collapse into clean matrix operations in Method 2.

PYTHON
import numpy as np

def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))

# =====================================================================
# METHOD 1: SCALAR IMPLEMENTATION (9 Individual Equations)
# =====================================================================
def train_scalar(net, x, y, epochs=1000, eta=0.1):
    N = float(len(x))
    for _ in range(epochs):
        dL = {k: 0.0 for k in net}
        for i in range(len(x)):
            x0, x1, target = x[i, 0], x[i, 1], y[i]

            # Forward Pass
            z0 = net["w0"] * x0 + net["w2"] * x1 + net["b0"]
            a0 = sigmoid(z0)
            z1 = net["w1"] * x0 + net["w3"] * x1 + net["b1"]
            a1 = sigmoid(z1)
            a2 = net["w4"] * a0 + net["w5"] * a1 + net["b2"]

            # Backward Pass (Chain Rule Tree)
            err = a2 - target
            dL["w5"] += err * a1
            dL["w4"] += err * a0
            dL["b2"] += err

            d1 = err * net["w5"] * a1 * (1.0 - a1)
            dL["b1"] += d1
            dL["w1"] += d1 * x0
            dL["w3"] += d1 * x1

            d0 = err * net["w4"] * a0 * (1.0 - a0)
            dL["b0"] += d0
            dL["w0"] += d0 * x0
            dL["w2"] += d0 * x1

        # Gradient Descent Step
        for k in net:
            net[k] -= (eta / N) * dL[k]
    return net

# =====================================================================
# METHOD 2: VECTORIZED MATRIX IMPLEMENTATION (Stanford CS229 Style)
# =====================================================================
def train_vectorized(W2, b2, W3, b3, X, Y, epochs=1000, eta=0.1):
    """
    Shapes for our 2-2-1 network across a single sample:
      a1 (input): (2, 1)
      W2: (2, 2), b2: (2, 1), a2 (hidden): (2, 1)
      W3: (1, 2), b3: (1, 1), a3 (output): (1, 1)
    """
    m = float(len(X))
    for _ in range(epochs):
        dW2 = np.zeros_like(W2)
        db2 = np.zeros_like(b2)
        dW3 = np.zeros_like(W3)
        db3 = np.zeros_like(b3)

        for i in range(len(X)):
            a1 = X[i].reshape(2, 1)       # Shape: (2, 1)
            target = Y[i].reshape(1, 1)   # Shape: (1, 1)

            # 1. Vectorized Forward Pass
            z2 = W2 @ a1 + b2             # (2, 2) @ (2, 1) + (2, 1) -> (2, 1)
            a2 = sigmoid(z2)              # Shape: (2, 1)
            z3 = W3 @ a2 + b3             # (1, 2) @ (2, 1) + (1, 1) -> (1, 1)
            a3 = sigmoid(z3)              # Shape: (1, 1) (Using BCE + Sigmoid)

            # 2. Vectorized Backward Pass
            delta3 = a3 - target          # Shape: (1, 1)
            dW3 += delta3 @ a2.T          # (1, 1) @ (1, 2) -> (1, 2)
            db3 += delta3                 # Shape: (1, 1)

            delta2 = (W3.T @ delta3) * (a2 * (1.0 - a2))  # (2, 1) * (2, 1) -> (2, 1)
            dW2 += delta2 @ a1.T          # (2, 1) @ (1, 2) -> (2, 2)
            db2 += delta2                 # Shape: (2, 1)

        # 3. Matrix Update Step
        W3 -= (eta / m) * dW3
        b3 -= (eta / m) * db3
        W2 -= (eta / m) * dW2
        b2 -= (eta / m) * db2

    return W2, b2, W3, b3

if __name__ == "__main__":
    np.random.seed(42)
    X = np.array([[2.0, 1.0], [4.0, 2.0]])
    Y = np.array([1.0, 0.0])

    # Method 1 Initial setup
    net = {
        "b2": 0.0, "b1": 0.0, "b0": 0.0,
        "w5": 0.6, "w4": 0.4, "w3": 0.0, "w2": 0.0, "w1": 0.0, "w0": 0.0,
    }
    trained_net = train_scalar(net, X, Y, epochs=100, eta=0.5)
    print("Method 1 (Scalar) trained w4, w5:", trained_net["w4"], trained_net["w5"])

    # Method 2 Vectorized setup
    W2 = np.zeros((2, 2))
    b2 = np.zeros((2, 1))
    W3 = np.array([[-0.8, -1.2]])
    b3 = np.array([[-1.0]])
    W2_new, b2_new, W3_new, b3_new = train_vectorized(W2, b2, W3, b3, X, Y, epochs=100, eta=0.5)
    print("Method 2 (Vectorized) trained W3:", W3_new)

10. Summary Checklist for Practitioners

  • 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)a_2(1 - a_2) saturation term cancels out at the output layer, preventing vanishing gradients on confident errors.
  • Use the 4 Matrix Shape Rules (W[l]W^{[l]} is (ncurr,nprev)(n_{\text{curr}}, n_{\text{prev}}), vectors are (n,1)(n, 1), and ∂L∂W[l]=δ[l](a[l−1])T\frac{\partial \mathcal{L}}{\partial W^{[l]}} = \delta^{[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():

PYTHON
import torch

# Fixed data (constants — no gradients)
x0, x1, y = torch.tensor(2.0), torch.tensor(1.0), torch.tensor(1.0)

# Learnable parameters (9 knobs we can tune)
w0 = torch.tensor(0.0, requires_grad=True)
w1 = torch.tensor(0.0, requires_grad=True)
w2 = torch.tensor(0.0, requires_grad=True)
w3 = torch.tensor(0.0, requires_grad=True)
w4 = torch.tensor(0.4, requires_grad=True)
w5 = torch.tensor(0.6, requires_grad=True)
b0 = torch.tensor(0.0, requires_grad=True)
b1 = torch.tensor(0.0, requires_grad=True)
b2 = torch.tensor(0.0, requires_grad=True)

# Forward pass — matching our equations exactly
z0 = w0 * x0 + w2 * x1 + b0
z1 = w1 * x0 + w3 * x1 + b1
a0 = torch.sigmoid(z0)
a1 = torch.sigmoid(z1)
a2 = w4 * a0 + w5 * a1 + b2
L = 0.5 * (y - a2) ** 2

# Backward pass — autograd traces the entire chain-rule tree!
L.backward()

print(f"∂L/∂w5 = {w5.grad:.4f}")  # -0.2500 (Matches Example A)
print(f"∂L/∂w4 = {w4.grad:.4f}")  # -0.2500
print(f"∂L/∂w1 = {w1.grad:.4f}")  # -0.1500
print(f"∂L/∂w0 = {w0.grad:.4f}")  # -0.1000

12. Test Your Understanding

schoolQuestion 1: Why does ∂L/∂b₂ have the fewest terms?
expand_more

Answer: The path from LL to b2b_2 is the shortest possible: L→a2→b2L \to a_2 \to b_2 (just 2 branches). The gradient is simply ∂L∂a2⋅∂a2∂b2=(a2−y)⋅1=(a2−y)\frac{\partial L}{\partial a_2} \cdot \frac{\partial a_2}{\partial b_2} = (a_2 - y) \cdot 1 = (a_2 - 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 w3w_3 would appear at the end of two different branches in the tree — one through z0z_0 and one through z1z_1. You would need to add both paths together (the multivariate chain rule): ∂L∂w3=path through z0⏟branch 1+path through z1⏟branch 2\frac{\partial L}{\partial w_3} = \underbrace{\text{path through } z_0}_{\text{branch 1}} + \underbrace{\text{path through } z_1}_{\text{branch 2}} 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.250.25, multiplying dozens of numbers ≤0.25\le 0.25 shrinks the gradient toward 00 exponentially (0.2550≈10−310.25^{50} \approx 10^{-31}). This is why modern architectures use ReLU (σ′(x)=1\sigma'(x) = 1 for x>0x > 0) and residual skip connections.


  1. Structure of a Neural Network — From single neurons to matrix multiplications and Transformer feedforward blocks.
  2. Loss Functions & Gradient Descent — How optimizers (SGD, Adam) use these gradients to traverse loss surfaces.
  3. Activation Functions — Deep dive into Sigmoid, ReLU, GELU, and Swish across deep architectures.
  4. Deep Learning: Vanishing & Exploding Gradients — Advanced diagnostics and stabilization techniques for deep networks.