Forward Pass, Backpropagation & Gradient Descent
Lesson opener
In one line: Forward pass - how inputs become predictions layer by layer.
Why it matters: You must compute predictions before measuring error.
Before this lesson: Neural networks intro / Applied ML statistics
Before you start
| Resource | Link |
|---|---|
| Previous | Neural networks intro |
| Next | First Keras model |
| Prerequisites | Neural networks intro, Applied ML statistics |
| Time | ~55 minutes |
What you will learn
- Forward pass — how inputs become predictions layer by layer
- Backpropagation as guess → check → adjust (intuition, not full calculus)
- Gradient descent — the engine that updates weights
- Maximum likelihood estimation (MLE) connection from Applied ML statistics
Forward pass — prediction flow
The problem it solves: Given current weights, what does the network predict for this Mumbai customer's tenure and spend?
Forward pass walks data input → hidden → output, applying weights, biases, and activations at each neuron.
x = [tenure=24, spend=₹3200]
↓ Layer 1: z₁ = W₁x + b₁, a₁ = ReLU(z₁)
↓ Layer 2: z₂ = W₂a₁ + b₂, ŷ = σ(z₂) = 0.73 churn riskWHY You must compute predictions before measuring error.
WHEN Every training step and every production inference call.
Hand sketch (one hidden neuron, one output):
- Inputs: \(x_1 = 24\), \(x_2 = 3200\)
- Hidden: \(z_h = 0.1 x_1 + 0.0002 x_2 - 1\), \(a_h = \max(0, z_h)\)
- Output: \(z_o = 0.5 a_h - 0.2\), \(\hat{y} = \sigma(z_o)\)
Plug numbers in a spreadsheet — that is forward pass.
Loss — how wrong was the guess?
For binary churn, binary cross-entropy (log loss):
\[
L = -\big[ y \log(\hat{y}) + (1-y) \log(1-\hat{y}) \big]
\]
- \(y\) = true label (0 or 1)
- \(\hat{y}\) = predicted probability
WHY Loss is a single number the network minimises.
WHEN Comparing training steps — loss should trend down (until overfitting).
MLE connection from stat4: Minimising cross-entropy on Bernoulli outcomes is equivalent to maximum likelihood estimation — finding weights that make observed churn labels most probable. Same idea behind LogisticRegression().fit() — neural nets generalise to many parameters.
Why this loss is full of \(\log\): eˣ, log & loss.
Gradient descent — adjust weights downhill
Imagine loss as a hilly landscape over thousands of weights. Gradient descent takes small steps in the direction that reduces loss.
\[
w_{\text{new}} = w_{\text{old}} - \eta \frac{\partial L}{\partial w}
\]
- \(\eta\) = learning rate (step size)
- \(\frac{\partial L}{\partial w}\) = how much loss changes if you nudge weight \(w\)
Bridge lesson (plain English + tiny walk): Loss & gradient descent.
| Learning rate | Effect |
|---|---|
| Too large | Bounces around, diverges |
| Too small | Training takes forever |
| Just right | Smooth loss decrease |
WHY Manual grid search on weights is impossible in deep nets — gradient descent automates it.
WHEN Every .fit() in Keras uses variants (Adam, SGD).
Indian analogy: Tuning masala in a Hyderabad biryani pot — taste (check loss), add less salt (adjust weights), repeat — not random throws.
Backpropagation — guess, check, adjust
Backprop efficiently computes \(\frac{\partial L}{\partial w}\) for all weights using the chain rule — errors flow backward from output to input.
Plain English loop:
- Guess — forward pass → \(\hat{y}\)
- Check — compute loss vs true \(y\)
- Adjust — backprop finds gradient per weight
- Step — gradient descent updates weights
- Repeat for next batch / epoch
Forward: x → ... → ŷ → loss
Backward: ∂loss/∂w for each layer (chain rule)
Update: w ← w - η * gradientWHY Backprop makes deep networks trainable — without it, only tiny nets are feasible.
WHEN You don't implement it by hand; Keras/TensorFlow does — but you debug learning rate and loss curves.
Batch vs stochastic gradient descent
| Variant | What it uses per step |
|---|---|
| Batch GD | Entire dataset |
| SGD | One row |
| Mini-batch | 32–256 rows (default in Keras) |
WHY Mini-batches balance speed and stable gradients.
WHEN batch_size=32 in model.fit() — see lesson 4.
NumPy intuition — one weight update
import numpy as np
# Single weight, single feature — logistic neuron
X = np.array([1.0, 2.0, 3.0])
y = np.array([0.0, 0.0, 1.0])
w, b = 0.0, 0.0
lr = 0.1
for epoch in range(200):
z = w * X + b
y_hat = 1 / (1 + np.exp(-z))
# dL/dz for cross-entropy + sigmoid simplifies to (y_hat - y)
dz = y_hat - y
dw = np.mean(dz * X)
db = np.mean(dz)
w -= lr * dw
b -= lr * db
print(f"Learned w={w:.3f}, b={b:.3f}")Breaking it down:
- Loop = manual training epochs
y_hat - y— error signal driving update- Same math Keras runs with matrices
Use this when: demystifying what happens inside .fit().
Common training problems
| Symptom | Likely cause | Try |
|---|---|---|
| Loss flat | Learning rate too low | Increase lr or check data scale |
| Loss explodes | Learning rate too high | Reduce lr, normalize inputs |
| Train loss ↓, test bad | Overfitting | Early stopping (dl4) |
Essential concepts
| Concept | Role |
|---|---|
| Forward pass | Compute predictions |
| Loss | Measure error |
| Backprop | Gradients for all weights |
| Gradient descent | Update weights |
| MLE | Probabilistic justification (stat4) |
Practice
Do this now: Run the NumPy training loop. Plot loss per epoch (optional). Write three bullets: forward pass, backprop purpose, link to MLE from stat4.
Checklist
- [ ] Forward pass described as layer-by-layer computation
- [ ] Backprop explained as guess-check-adjust
- [ ] Learning rate tradeoff understood
- [ ] MLE connection to cross-entropy loss
- [ ] Next: First Keras model