The Training Loop, Step by Step
Every model you have trained so far, from LinearRegression().fit(X, y) to a neural network, hides the same small program inside fit. Scikit-learn often hides it behind a closed-form solution or a specialised solver, but anything trained by gradients (logistic regression with SGD, every neural network, gradient-boosted trees in a different form) runs a training loop: take a batch of examples, make predictions, measure how wrong they are, work out which way to move each parameter, move it a little, and repeat. When you can write that loop yourself, the knobs of every deep-learning library (batch_size, epochs, lr, scheduler, callbacks) stop being magic.
This lesson names each step of the loop and runs it once in NumPy on the simplest model there is. The next three lessons grow it into a complete loop for logistic regression, for a small neural network, and then show the same loop in PyTorch.
The anatomy of one training run
| Step | What happens | Where in code |
|---|---|---|
| 1 batch | take examples from the shuffled training set | X[idx] |
| 2 forward | run the inputs through the model with the current parameters | z = X_b @ w + b |
| 3 prediction | the model's output (a number, a probability, a vector of class scores) | y_hat |
| 4 loss | one number that says how wrong the batch predictions are, | np.mean((y_hat - y_b) ** 2) |
| 5 backprop | the gradient : how the loss changes when each parameter moves | grad_w = ... |
| 6 update | the optimizer moves the parameters against the gradient | w -= lr * grad_w |
| 7 next batch / epoch | repeat until every example has been seen once: that is one epoch | for epoch ...: for batch ...: |
| 8 validation | measure the loss or metric on held-out data, with no updates | val_loss = ... |
| 9 save | keep a copy (checkpoint) of the parameters when validation improves | best = w.copy() |
The update in step 6 is, for plain gradient descent with learning rate ,
Everything else in this course plugs into one of these boxes. Losses are box 4 (MSE, MAE, Huber, cross-entropy). Optimizers are box 6 (SGD, Adam). Metrics and validation strategies are box 8. Early stopping and checkpointing are box 9.
Two loops, three words
- An iteration (or step) is one pass through boxes 1 to 6: one batch, one parameter update.
- An epoch is one pass over the whole training set. With training examples and batch size there are steps per epoch.
- The training run is many epochs. Its length is set by an epoch budget, a time budget or early stopping.
So 800 examples with give steps per epoch, and 20 epochs are 500 updates. The lesson on batch size, iterations and epochs looks at how changes the noise of each step.
A complete loop in 30 lines
Here is the whole loop for linear regression, with the mean squared error. The data are synthetic, generated from known weights and bias , so you can see whether training finds them. The gradient of the batch MSE is
import numpy as np
rng = np.random.default_rng(0)
true_w, true_b = np.array([2.0, -3.0, 0.5]), 1.0
X = rng.normal(size=(1000, 3))
y = X @ true_w + true_b + rng.normal(scale=0.5, size=1000) # noise sd 0.5
X_tr, y_tr, X_val, y_val = X[:800], y[:800], X[800:], y[800:] # train / validation
w, b = np.zeros(3), 0.0 # parameters
lr, batch_size, epochs = 0.05, 32, 8
best_val, best = np.inf, None
for epoch in range(epochs):
order = rng.permutation(len(X_tr)) # shuffle once per epoch
for start in range(0, len(X_tr), batch_size):
idx = order[start:start + batch_size] # 1 batch
Xb, yb = X_tr[idx], y_tr[idx]
y_hat = Xb @ w + b # 2-3 forward, prediction
err = y_hat - yb
loss = np.mean(err ** 2) # 4 loss
grad_w = 2 * Xb.T @ err / len(idx) # 5 gradients
grad_b = 2 * err.mean()
w -= lr * grad_w # 6 update
b -= lr * grad_b
train_loss = np.mean((X_tr @ w + b - y_tr) ** 2)
val_loss = np.mean((X_val @ w + b - y_val) ** 2) # 8 validation
if val_loss < best_val: # 9 keep the best
best_val, best = val_loss, (w.copy(), b)
print(f"epoch {epoch + 1} train MSE {train_loss:.4f} val MSE {val_loss:.4f}")
print("best val MSE", round(best_val, 4))
print("learned w", best[0].round(3), " b", round(best[1], 3))epoch 1 train MSE 0.3591 val MSE 0.3688
epoch 2 train MSE 0.2496 val MSE 0.2730
epoch 3 train MSE 0.2491 val MSE 0.2725
epoch 4 train MSE 0.2487 val MSE 0.2687
epoch 5 train MSE 0.2488 val MSE 0.2701
epoch 6 train MSE 0.2490 val MSE 0.2725
epoch 7 train MSE 0.2492 val MSE 0.2708
epoch 8 train MSE 0.2488 val MSE 0.2693
best val MSE 0.2687
learned w [ 1.979 -2.977 0.526] b 1.015
Read the output top to bottom:
- Epoch 1 does most of the work. Each epoch is 25 updates (), and after the first 25 the training MSE is already 0.3591, down from 13.3 for the all-zero start.
- Then it flattens near 0.25. That is the noise floor: the labels contain noise with standard deviation 0.5, so even the true weights have an expected MSE of . No model can do better on average.
- Validation wobbles. With a constant learning rate, every mini-batch step jiggles the parameters, so the validation MSE moves up and down between 0.2687 and 0.2730 after epoch 2. The best epoch was the 4th, and that is the copy the loop kept.
- The learned parameters and are close to the true and . The remaining gap is the noise in 800 examples, not a failure of the optimizer.
Linear regression has a closed-form solution, so you would never train it this way in practice. Its value here is that every quantity can be checked by hand. The same nine boxes with a different forward pass and gradient give you logistic regression and neural networks.
What the loop leaves out (for now)
This loop already has the shape of every training loop in this course. Real loops add:
- a learning-rate schedule that changes across epochs (schedules and warm-up);
- regularisation inside the loss or the update (weight decay and dropout);
- early stopping: end the run when validation stops improving for a few epochs, then restore the best checkpoint;
- gradient clipping before the update (clipping) and mixed precision for speed (float16 and bfloat16);
- logging of the losses and metrics, so you can draw learning curves later.
Pitfalls
- Forgetting to shuffle. If the training file is sorted (all class 0 first, or by date), unshuffled batches pull the parameters back and forth. Shuffle once per epoch, as the loop above does with a new permutation.
- Updating during validation. Box 8 only measures. In PyTorch that means
model.eval()andtorch.no_grad(); in NumPy, simply do not touch the parameters. - Saving a reference instead of a copy.
best = wstores a reference to the same array, which the next update changes in place.w.copy()stores the values. - Judging training by the training loss alone. A falling training loss only says the optimizer works. Whether the model generalises is what the validation loss says.
Practice
- A training set has 50,000 images and the batch size is 128. How many parameter updates happen in 10 epochs (the last batch of each epoch is smaller)?
Answer
steps per epoch, so updates in 10 epochs.
- In the example, change
lrto0.5. What do you expect, and why?
Answer
For this problem the features have unit variance, so the MSE's curvature along each weight is about , and plain gradient descent is stable only for in the full-batch case. With it still converges, faster, but each mini-batch step is noisier; push above about 1 and the losses grow without bound. The lesson on gradient descent and the learning rate shows this in a lab.
- Why does the loop compute
train_lossagain after the epoch instead of averaging the batch losses?
Answer
The batch losses were measured with parameters that kept changing during the epoch, so their average describes a moving model. Re-evaluating at the end of the epoch measures the training loss of the parameters you would actually keep, on the same footing as the validation loss. (Many libraries report the running average anyway because it is free; it lags slightly behind.)
Test yourself
What is one iteration (step) of the training loop?
- One pass over the whole training set
- One batch: forward pass, loss, gradients and one parameter update
- One evaluation on the validation set
- One complete training run
With 1,200 training examples and batch size 50, how many steps are in one epoch?
- 50
- 24
- 1,200
- 60
Which step must never change the parameters?
- The optimizer update
- Backpropagation
- Validation
- The forward pass during training
Why does the loop store w.copy() rather than w as the best weights?
- Copies are faster to read
wis updated in place, so a plain reference would silently change with every later step- NumPy cannot store references
- To save memory