Chapter 3 of 42 · ~18 min read & lab+70 XP
Chapter 3 · Deep Learning

How Neural Networks Learn: Gradient Descent, Learning Rate, Mini-Batches & Epochs

Crystal-clear intuition for how training actually works: walking downhill via Gradient Descent (w ← w − η∇L), why Learning Rate makes or breaks training, and the exact math of Epochs vs. Mini-Batches vs. Iterations!

Why ML Engineers & Data Scientists Actually Need This

90% of early Deep Learning confusion comes from mixing up Epochs vs. Iterations or picking a Learning Rate that is 100× too high and explodes loss to NaN!

ML / AI Engineer

Batch size and Learning Rate are coupled hyperparameters — doubling batch size changes GPU throughput, VRAM usage, and gradient noise!

Data Scientist

Knowing exact step counts (steps = ceil(N / B) * epochs) is essential when configuring Cosine LR schedules and checkpoint intervals.

Interview & Debug Edge

Frequent screening question: 'Dataset has 10,000 samples, batch size is 200, and you train for 5 epochs — how many weight updates (iterations) happen?' (Answer: 50 × 5 = 250!)

Step 0 · Test Your Gut Before Any Math!

With N = 1,000 examples, batch_size = 100, and 5 epochs, how many total weight updates (iterations) occur?

What You Will Master in This Chapter
  • Understand the core weight-update rule w←w−η∂L∂ww \leftarrow w - \eta \frac{\partial L}{\partial w} as walking downhill on a loss landscape
  • Diagnose too-small vs. just-right vs. too-large Learning Rates (η\eta) from training loss behavior
  • Compute exact Iterations per Epoch and Total Gradient Steps from dataset size NN, batch size BB, and epochs EE
  • Explain why Mini-Batch Gradient Descent (B = 32..256) beats both Pure SGD (B = 1) and Full-Batch GD (B = N)
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
wt+1=wt−η∇wL(wt)w_{t+1} = w_t - \eta \nabla_w \mathcal{L}(w_t)Say aloud:“New weight equals old weight minus learning rate times gradient of loss”
Plain-English Meaning
The universal update rule of Deep Learning: measure the slope (∇wL\nabla_w \mathcal{L}) and take a step of size η\eta downhill (opposite the slope).
Everyday Example
If slope = +4.0 and η=0.01\eta = 0.01, subtract 0.04 from ww to lower the loss!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Imagine standing blindfolded on a foggy mountainside trying to reach the lowest valley (minimum loss). You feel the slope under your boots (gradient) and take a stride downhill (learning rate η\eta). Too tiny a stride takes forever; too huge a leap launches you across the valley into NaN!

1. Gradient Descent & The Learning Rate (η)

Effect of Learning Rate η on Gradient Descent ConvergenceToo Small (η = 0.0001)Tiny baby steps — crawls!Just Right (η = 0.01)Smooth convergence to min ✓Too Large (η = 1.5)Overshoots & explodes → NaN!
Learning Rate η controls step size down the loss bowl: too small crawls forever; just right converges smoothly; too large overshoots and explodes to NaN!

Training starts with random weights (high loss). On each step, we compute the gradient ∇wL\nabla_w \mathcal{L} (which points uphill) and move in the negative direction: w←w−η∇wLw \leftarrow w - \eta \nabla_w \mathcal{L}.

  • η\eta too small: Loss barely budges after 50 epochs.
  • η\eta just right: Loss drops steeply then levels off smoothly.
  • η\eta too large: Loss bounces wildly or explodes to NaN!

2. Epochs vs. Mini-Batches vs. Iterations

Epoch vs. Mini-Batch vs. Iteration (Dataset N = 1,000, Batch B = 100)B1B2B3B4B5B6B7B8B9B1010 Mini-Batches = 10 Iterations (Weight Updates) = 1 Full Epoch!Train for 5 Epochs → 5 × 10 = 50 total optimizer.step() updates
Dataset = 1,000 examples, Batch Size = 100 → 1 Epoch = 10 Iterations (weight updates). Epochs count full passes over the dataset; Iterations count gradient steps!

These three terms appear in every PyTorch script:

  • Batch Size (BB): Number of examples processed together in one GPU forward/backward pass.
  • Iteration (Step): One weight update (optimizer.step()) on one mini-batch.
  • Epoch: One complete pass through the entire training dataset (⌈N/B⌉\lceil N / B \rceil iterations).
Animated Mini-Lab • 1.3

Epoch vs. Batch Size vs. Iteration Calculator (N = 1,280)

Iterations / Epoch
20
Total Weight Updates
100

3. Why Mini-Batch Gradient Descent Wins on GPUs

Batch Size Trade-Off: Pure SGD (B=1) vs. Mini-Batch (B=64) vs. Full-Batch (B=N)Pure SGD (B = 1)Very noisy · No GPU parallelismMini-Batch (B = 32–256)Fast GPU GEMM + generalizes best ✓Full-Batch (B = N)OOM VRAM · Slow 1 step / epoch
Mini-Batch Gradient Descent hits the sweet spot: smoother than noisy Batch=1 SGD, yet vastly faster on GPUs (and escapes sharp local minima better!) than Full-Batch GD!
  • Pure SGD (B=1B = 1): Extreme gradient noise and terrible GPU utilization (1 vector at a time).
  • Full-Batch GD (B=NB = N): Crashes GPU VRAM on 1M images and only updates weights once per full dataset scan!
  • Mini-Batch GD (B=32B = 32 to 256256): Saturates GPU Tensor Cores with parallel matrix math while keeping just enough stochastic noise to escape sharp bad minima!
Pause & Check · Quick Intuition Pulse

If your training loss immediately jumps to NaN on Iteration 3, what is the FIRST hyperparameter you should check?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

If examples are sorted by class (all cats first, then all dogs), each mini-batch has biased gradients that violently pull weights back and forth. shuffle=True ensures every mini-batch is a balanced mini-snapshot of the dataset!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Mini-Batch Gradient Descent stepper descend the loss curve across 5 iterations.
Interactive Animation • 1.3 Deep Lab

Mini-Batch Gradient Descent Stepper (w ← w − η ∇L)

Watch each mini-batch compute a gradient and nudge weights steadily down the loss bowl.

Iter 1 / 5
Iter 1
L = 1.42
Iter 2
L = 0.96
Iter 3
L = 0.58
Iter 4
L = 0.31
Iter 5
L = 0.14
0%
Batch #1 · Loss 1.42
Intuition Takeaway: Neural networks learn via Mini-Batch Gradient Descent (w←w−η∇wLw \leftarrow w - \eta \nabla_w \mathcal{L}): Iterations count batch weight updates, Epochs count full dataset passes, and Learning Rate η\eta is the single most important hyperparameter.
Where This Powers Real ML, Deep Learning & Generative AI

Every Modern Neural Network Training Run

Mini-batch stochastic optimization powers everything from laptop MNIST experiments to 10,000-GPU LLM pre-training.

Production NumPy & PyTorch Code Patterns
import torch
from torch.utils.data import DataLoader, TensorDataset

# Mini-batch SGD loop demonstrating epochs, batch size, and learning rate
torch.manual_seed(0)
X = torch.randn(200, 4)
true_w = torch.tensor([[2.0], [-1.5], [0.8], [3.0]])
y = X @ true_w + 0.5 + 0.1 * torch.randn(200, 1)

loader = DataLoader(TensorDataset(X, y), batch_size=32, shuffle=True)
model = torch.nn.Linear(4, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

for epoch in range(1, 6):
    epoch_loss = 0.0
    for xb, yb in loader:
        optimizer.zero_grad()
        loss = torch.nn.functional.mse_loss(model(xb), yb)
        loss.backward()        # compute dL/dw and dL/db
        optimizer.step()       # w <- w - lr * grad
        epoch_loss += loss.item() * len(xb)
    print(f"Epoch {epoch} | Train MSE: {epoch_loss / len(X):.4f}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Setting shuffle=True on the Validation or Test DataLoader (unnecessary) or forgetting shuffle=True on the Training DataLoader (hurts convergence!).
Best Practice: Always set shuffle=True for train_loader and shuffle=False for val_loader / test_loader!
Chapter Mastery Check (+70 XP)
Score: 0 / 1
1You train on N = 2,000 samples with batch_size = 50 for 4 epochs. How many total iterations (weight updates) run?

Apply What You Learned — Solve Matching Coding Problems