Why “training” needs vocabulary
In the last sub-chapter we walked through a single backprop step. Real models take millions of those steps. To talk about that process precisely, engineers use three words constantly: iteration, epoch, and batch size. Get these straight and the rest of training is mostly bookkeeping.
The training loop — one beat at a time
Every modern deep-learning trainer, whether 50 lines of NumPy or a 100k-line PyTorch project, executes this same five-step rhythm:
- Load a batch — pull
Bexamples from the training set. - Forward pass — compute predictions for those
Bexamples. - Compute loss — compare predictions to ground truth.
- Backward pass — compute gradients of loss w.r.t. every weight.
- Update weights — nudge weights in the direction that reduces loss.
That five-step cycle is one iteration. Repeat it until you’ve seen every training example once — that’s one epoch. Repeat epochs until the validation loss stops improving.
Civil-engineering analogy
Training a network is like calibrating a draft structural-design code from historical project data:
- One mini-batch = updating provisions after reviewing a small handful of past projects.
- One epoch = re-reading the entire case database front to back.
- Validation set = a separate set of independent bridges held aside to test whether the code generalizes.
- Test set = a sealed envelope of cases opened only once at the very end — the final, unbiased report card.
Iteration, epoch, batch size
These three numbers are tied by a simple equation. Memorize it.
The fundamental relation
iterations per epoch = ceil( Ntrain / batch_size )
If you have 50,000 training examples and a batch size of 64, one epoch is ceil(50000 / 64) = 782 iterations. Train for 30 epochs and the optimizer takes 782 × 30 = 23,460 weight updates.
Iteration (a.k.a. step)
One forward + backward + update on a single mini-batch. The smallest atomic unit of training.
When you read “loss at step 5,000,” this is what is meant.
Epoch
One complete pass through the entire training dataset. The model has now “seen” every example exactly once (assuming no oversampling).
Most papers report results “after N epochs.”
Batch size B
Number of examples processed together in a single iteration. The gradient is averaged across these B examples before the update.
Common values: 8, 16, 32, 64, 128, 256, 512, 1024.
Dataset size N
The total number of training examples. Distinct from the validation and test counts, which are held out.
Modern image datasets: 104–109 examples.
Train / Validation / Test
You never train on all your data. A portion is sacrificed for honest evaluation — otherwise you cannot tell whether your model has actually learned something or simply memorized the answers.
The three-way split
Typical ratios: 70/15/15 or 80/10/10 for medium datasets, and as little as 98/1/1 when you have millions of examples (1% of 10M is still 100k — plenty for evaluation).
- Training set: the model learns from these. Weights are updated using their gradients.
- Validation set: the model is evaluated on these every epoch. Used to pick the best epoch, tune learning rate, decide when to stop. The model never trains on them, but you (the engineer) do use them to make decisions — so they become contaminated over time.
- Test set: opened exactly once, at the end, to report the final number. Never used for any tuning.
Why a separate validation set?
Because any decision you make using the test set turns it into a validation set. You only get one truly clean estimate of generalization — protect it.
Stratified sampling
For imbalanced datasets (95% safe / 5% defective), random splitting can leave the rare class missing from validation. Stratified sampling preserves the class ratio inside each split.
Time-based splits
For time-series (e.g., concrete-curing sensor data), random splitting leaks the future into the past. Always split chronologically: train on weeks 1–30, validate on 31–33, test on 34–36.
Group-aware splits
If multiple photos of the same bridge appear in your dataset, all of them must go to the same split. Otherwise the model sees the same bridge in training and validation — an instant leak.
Reading learning curves
Plot training loss and validation loss against epochs. The shape of those two lines tells you everything you need to know about the health of your training run.
Underfitting
Both train and validation loss are high and barely decreasing. The model lacks the capacity (or hasn’t trained long enough) to fit the data.
Fix: bigger model, longer training, better features, lower regularization.
Just right
Both losses decrease together and plateau close to each other. The small gap between them is normal and represents the model’s honest generalization error.
Action: stop training, save model.
Overfitting
Train loss keeps falling but validation loss bottoms out and starts rising. The model is memorizing training noise.
Fix: more data, regularization, dropout, early stopping (we cover these in 6.8).
Early stopping — the simplest regularizer
Watch the validation loss every epoch. The moment it stops improving for, say, 5 epochs in a row (the “patience”), kill the run and load the weights from the best epoch. That’s it. Free regularization.
best_val = float("inf")
patience, bad = 5, 0
for epoch in range(max_epochs):
model.train()
for xb, yb in train_loader: # one iteration each
pred = model(xb)
loss = loss_fn(pred, yb)
loss.backward()
optimizer.step()
optimizer.zero_grad()
model.eval()
val_loss = evaluate(model, val_loader)
if val_loss < best_val:
best_val = val_loss
save_checkpoint(model)
bad = 0
else:
bad += 1
if bad >= patience:
print(f"Early stop at epoch {epoch}")
break
Training Loop Visualizer
Watch a small synthetic regression model train in real time. Pick a model complexity and see whether the curves stay flat (underfit), converge nicely (just right), or diverge (overfit).
The blue curve is training loss; the orange curve is validation loss. Try High complexity and watch the orange curve eventually rise — classic overfitting.
Batch size: small vs. large
Batch size is one of the few hyperparameters that touches everything: speed, memory, gradient quality, generalization, and required learning rate. Here’s the cheat sheet.
Small batches (8 – 32)
- Noisy gradients — each step jitters around the “true” gradient.
- Often better generalization — the noise acts like a regularizer.
- Slower per-epoch wall-clock time on GPU (under-utilized hardware).
- Lower memory footprint.
- Can use a higher learning rate without diverging.
Large batches (256 – 1024+)
- Smooth gradients — closer to the true full-dataset gradient.
- Faster per-epoch on modern GPUs (better parallelism).
- Often worse final generalization without careful tuning.
- Higher memory footprint — can blow up VRAM.
- Usually need to scale the learning rate up proportionally (linear-scaling rule).
Batch Size Effect
Three identical models trained on the same data with three different batch sizes. Watch the texture of each loss curve — B=8 jitters wildly, B=256 glides.
All three runs use the same learning rate and dataset. Notice how B=8 takes more iterations but its noisy descent often reaches a better final loss.
Shuffling, stratification, augmentation
Three habits that separate a working training pipeline from a broken one.
Shuffle every epoch
If your dataset is sorted by class (all cracks first, then all spalls, then all corrosion), an unshuffled iterator hands the model an entire epoch of one class before showing any of the next. The result is wild oscillation in the loss and unstable training. Shuffling at the start of every epoch fixes this.
The validation and test sets are not shuffled — consistency matters more than order there.
Stratified sampling for imbalanced data
If 95% of your bridge inspections are “safe” and 5% are “defective,” a random batch of 32 will sometimes contain zero defective examples — the loss on that step says nothing about the rare class. Stratified samplers ensure each batch contains a controlled mix.
Data augmentation in the pipeline
For images, the same example is resampled with random crop, flip, brightness, and rotation each time it’s loaded. The model effectively sees a different version every epoch, multiplying the apparent dataset size. This is the single most effective regularizer for vision models — we explore it in detail in 6.8.
Civil Engineering Application
Iterative Design Process
Neural network training mirrors the iterative analysis cycle in structural design: assume dimensions → compute forces → check adequacy → adjust → repeat. Each epoch is one full design iteration. Batch size is how many load cases you check before making adjustments.
Overfitting on Limited Field Data
CE datasets are often small (30-100 borehole logs, 50-200 concrete tests). Training too many epochs causes the model to memorize noise in test results rather than learning true material behavior. The validation curve is your early warning system — when it starts rising, stop training.
Quiz
Four short questions. Click any option to reveal the explanation.
1 You have 80,000 training examples and a batch size of 32. How many iterations is one epoch?
2 Training loss keeps falling but validation loss is rising. What is happening?
3 Why hold out a separate test set in addition to a validation set?
4 A colleague switches from batch size 32 to 256 with no other changes and the model now diverges. What is the most likely fix?
What you should walk away with
- Training is a tight five-step loop: load → forward → loss → backward → update.
- One iteration = one mini-batch. One epoch = one pass over the whole training set.
iterations_per_epoch = ceil(N / batch_size).- Always split data into train, validation, and test — and respect the boundaries.
- Diagnose runs by reading the train/val loss curves: flat = underfit, diverging = overfit, parallel = healthy.
- Small batches generalize better but train slower; large batches need scaled-up learning rates.
- Shuffle every epoch, stratify when classes are imbalanced, and augment only the training set.
Tune epochs and batch size — watch the loss curve respond
Larger batches → smoother loss. Smaller batches → noisier but often faster generalisation. Slide both and watch the live training curve confirm the textbook.