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!
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!
Batch size and Learning Rate are coupled hyperparameters — doubling batch size changes GPU throughput, VRAM usage, and gradient noise!
Knowing exact step counts (steps = ceil(N / B) * epochs) is essential when configuring Cosine LR schedules and checkpoint intervals.
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!)
With N = 1,000 examples, batch_size = 100, and 5 epochs, how many total weight updates (iterations) occur?
- Understand the core weight-update rule as walking downhill on a loss landscape
- Diagnose too-small vs. just-right vs. too-large Learning Rates () from training loss behavior
- Compute exact Iterations per Epoch and Total Gradient Steps from dataset size , batch size , and epochs
- Explain why Mini-Batch Gradient Descent (
B = 32..256) beats both Pure SGD (B = 1) and Full-Batch GD (B = N)
+4.0 and , subtract 0.04 from to lower the loss!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 ). Too tiny a stride takes forever; too huge a leap launches you across the valley into NaN!
1. Gradient Descent & The Learning Rate (η)
Training starts with random weights (high loss). On each step, we compute the gradient (which points uphill) and move in the negative direction: .
- too small: Loss barely budges after 50 epochs.
- just right: Loss drops steeply then levels off smoothly.
- too large: Loss bounces wildly or explodes to
NaN!
2. Epochs vs. Mini-Batches vs. Iterations
These three terms appear in every PyTorch script:
- Batch Size (): 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 ( iterations).
Epoch vs. Batch Size vs. Iteration Calculator (N = 1,280)
3. Why Mini-Batch Gradient Descent Wins on GPUs
- Pure SGD (): Extreme gradient noise and terrible GPU utilization (1 vector at a time).
- Full-Batch GD (): Crashes GPU VRAM on 1M images and only updates weights once per full dataset scan!
- Mini-Batch GD ( to ): Saturates GPU Tensor Cores with parallel matrix math while keeping just enough stochastic noise to escape sharp bad minima!
If your training loss immediately jumps to NaN on Iteration 3, what is the FIRST hyperparameter you should check?
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!
Mini-Batch Gradient Descent Stepper (w ← w − η ∇L)
Watch each mini-batch compute a gradient and nudge weights steadily down the loss bowl.
Every Modern Neural Network Training Run
Mini-batch stochastic optimization powers everything from laptop MNIST experiments to 10,000-GPU LLM pre-training.
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}")
shuffle=True on the Validation or Test DataLoader (unnecessary) or forgetting shuffle=True on the Training DataLoader (hurts convergence!).shuffle=True for train_loader and shuffle=False for val_loader / test_loader!N = 2,000 samples with batch_size = 50 for 4 epochs. How many total iterations (weight updates) run?