Epochs, batches and validation
Batches, steps and epochs
An epoch is one pass through the training dataset in the simple finite-data setting. A batch is a subset of examples used to compute one gradient estimate. A step is one optimizer update; gradient accumulation and skipped steps can make the relationship between batches and steps more complicated. With five examples, batch size two and no dropped remainder, the batches have sizes 2, 2 and 1, giving three updates per epoch when each batch triggers one step. Batch size affects memory, gradient noise and update frequency; it does not automatically improve accuracy.
A tiny training loop
Use the same model y_hat = w × x and the mean squared loss across a batch. The batch gradient averages 2(wx − y)x for each row, all evaluated at the same w. Update once per batch, dividing by its actual length. The three synthetic rows below all have x = 1 and y = 2; with batch size 2, rate 0.25 and w = 0, successive updates move w to 1, 1.5, 1.75 and 1.875. The code prints epoch 1 with 1.5 and epoch 2 with 1.875. It intentionally preserves order; realistic training may shuffle independent examples while respecting time or group constraints. This is a scalar model, not a general neural-network trainer.
def batch_step(rows, w, rate): if not rows: raise ValueError("A batch must not be empty") gradient = sum(2 * (w*x-y) * x for x, y in rows) / len(rows) return w - rate * gradient
def train_epoch(rows, w, rate, batch_size): if not rows or batch_size <= 0: raise ValueError("Need rows and positive batch size") for start in range(0, len(rows), batch_size): w = batch_step(rows[start:start+batch_size], w, rate) return w
rows = [(1, 2), (1, 2), (1, 2)]w = 0for epoch in range(1, 3): w = train_epoch(rows, w, 0.25, 2) print(epoch, w)Validation and learning curves
Use training rows to compute gradients. Evaluate the same checkpoint on a separate validation set without updating weights. Compare losses with consistent reduction, units and evaluation conditions; dropout or regularization can make training logs not directly comparable to validation metrics. If training loss falls while validation loss rises persistently, overfitting is a plausible explanation, not proof; investigate split quality, noise, distribution shift and evaluation code. If both remain high, inspect capacity, optimization, data quality and the baseline. Keep the test set untouched until the model and selection rules are fixed.
Early stopping and restoring the best checkpoint
For this example a strict decrease in validation loss counts as improvement; patience is the number of consecutive completed epochs without improvement allowed before stopping. Ties are not improvements. With losses [8, 4, 3, 4, 5, 2] and patience 2, epoch 3 is best and training stops at epoch 5, so the final hypothetical value at epoch 6 is never observed. Restore the parameters saved at epoch 3, not epoch 5. The function returns (best_epoch, stop_epoch), using one-based numbering, and works on a recorded or hypothetical loss sequence; it does not actually save weights. Real implementations may use min_delta, warm-up, different metrics and explicit checkpoint restoration. The second example returns (4, 4) because a new low follows a single tie.
def select_checkpoint(validation_losses, patience): if not validation_losses or patience < 1: raise ValueError("Need losses and positive patience") best = 0 stale = 0 for i in range(1, len(validation_losses)): if validation_losses[i] < validation_losses[best]: best = i stale = 0 else: stale += 1 if stale == patience: return best + 1, i + 1 return best + 1, len(validation_losses)
print(select_checkpoint([8, 4, 3, 4, 5, 2], 2))print(select_checkpoint([5, 4, 4, 3], 2))Regularization and debugging
L2 regularization adds a term such as λ × sum(w²) to the training objective, discouraging large weights; its gradient adds 2λw under this convention. Dropout randomly masks activations during training under a specified scaling convention, and is generally disabled at ordinary evaluation. These methods can reduce overfitting but may hurt an already underfit model. A typical autodiff loop clears old gradients, computes predictions and loss, backpropagates, then steps the optimizer. Gradient accumulation is intentional only when configured correctly. Check nonfinite losses, learning rate, shape mismatches, data leakage and the baseline before choosing a bigger model. Framework behavior and exact APIs need version-specific verification.
Practice and next steps
Given training losses [9, 6, 4, 2] and validation losses [8, 5, 6, 7], with patience 2, choose epoch 2 and stop after epoch 4. Explain why selecting on test loss would invalidate an independent final evaluation. A saved checkpoint should include the model parameters and relevant preprocessing metadata; resuming training may also need optimizer state, random state and scheduler state. Next: choose an architecture and compare framework training and inference workflows.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Epochs, batches and validation quiz
Check calculations and training decisions.
Five rows, batch size two, no dropped remainder: how many updates per epoch if each batch produces one update?
In the lesson’s mean-gradient batch update, the last batch contains one row instead of the nominal two. What divisor is used?
Training loss decreases while validation loss increases over several epochs. Which response is appropriate?
For the lesson’s strict-improvement checkpoint rule with patience 2, what (best epoch, stopping epoch) is returned for losses [8,4,3,4,5,2]?
At what point should a reserved final test partition be evaluated?