Deep Learning · Beginner Lesson
Training a Neural Network: The Complete Loop From Data to Better Predictions
Creating a neural network only gives us a collection of layers with untrained weights. A training loop is the repeated procedure that shows the network examples, measures its mistakes, corrects its weights and checks whether those corrections also help on unseen data. This lesson follows one batch through every operation and explains what should happen at the end of an epoch.
What Does “Training” Actually Mean?
Imagine a factory camera that must label a product as acceptable or defective. At first, its weights are random, so its answers are poor. Training does not give the camera one long instruction. It performs thousands of small correction cycles:
examples → predictions → measured mistakes → gradients → corrected weights
The word loop matters because the same operations are repeated. One repetition for one batch is a training step. Repeating steps until the complete training set has been used once creates an epoch. Repeating epochs gives the weights many opportunities to improve.
Essential Terms Before We Build the Loop
Training example
One input together with its correct target, such as one product image and its defect label.
Batch
A small group of examples processed together before one weight update.
Training step / iteration
One complete batch cycle: predict, calculate loss, backpropagate and update.
Epoch
One pass through all examples in the training set.
Validation set
Separate examples used to measure the current model without changing its weights.
Metric
A human-readable measurement such as accuracy or MAE, reported alongside the training loss.
What Happens to One Batch?
Suppose a batch contains 16 product images and 16 correct labels. The six operations below form one meaningful unit. Each step exists because the next one depends on it.
Load inputs and targets
The data loader supplies image tensors and their correct labels. Inspect their shape, value range and labels before trusting the loop.
Clear gradients from the previous batch
PyTorch normally adds new gradients to existing ones. optimizer.zero_grad() removes the old values so this batch produces a fresh correction.
Run the forward pass
The batch travels through the current network. The model produces raw output scores called logits. No weights change yet.
Calculate the batch loss
The loss function compares the logits with the correct labels and returns one average penalty for this batch.
Run the backward pass
loss.backward() calculates a gradient for every trainable weight. A gradient tells how that weight influenced the loss.
Update the weights
optimizer.step() uses the gradients and learning rate to change the weights. This is the only step in this cycle that actually changes the model.
Why the order matters: loss cannot be calculated before a prediction exists; gradients cannot be calculated before a loss exists; and the optimizer cannot make an informed update before gradients exist.
How Batches Form an Epoch
Processing the entire dataset at once may not fit in memory. Instead, the data loader divides it into batches. For N examples and batch size B:
Formula
updates per epoch = ⌈N ÷ B⌉
The ceiling brackets ⌈ ⌉ mean round upward because a smaller final batch still needs to be processed.
Small batch
Frequent, noisier updates and lower memory use.
Large batch
Smoother gradient estimate but more memory and fewer updates per epoch.
One epoch
A unit for scheduling validation, checkpoints and learning-rate changes.
A Complete Weight Update With Small Numbers
To see what the loop accomplishes, use the one-weight model ŷ = wx. It receives input x = 2 and should produce target y = 4. Start with w = 0.5, learning rate η = 0.1 and loss L = ½(ŷ − y)².
Input x
2
Target y
4
Starting w
0.5
Learning rate η
0.1
Forward
ŷ = wx = 0.5 × 2 = 1
Loss
L = ½(1 − 4)² = 4.5
Backward
∂L/∂w = (ŷ − y)x = (1 − 4) × 2 = −6
Update
w_new = w − η(∂L/∂w) = 0.5 − 0.1(−6) = 1.1
Verify the next step
ŷ_new = 1.1 × 2 = 2.2; L_new = ½(2.2 − 4)² = 1.62
What changed?
One batch update moved w from 0.5 to 1.1 and reduced loss from 4.5 to 1.62. The next batch repeats the same six operations using the new weight. Training is many small improvements like this.
Training and Validation Have Different Jobs
Training performance answers, “Is the optimizer fitting the examples it is allowed to learn from?” Validation performance answers, “Do those learned patterns also work on separate examples?” If validation examples update the weights, they are no longer an honest test of generalization.
| Question | Training pass | Validation pass |
|---|---|---|
| Which data? | Training batches | Held-out validation batches |
| Model mode? | model.train() | model.eval() |
| Calculate gradients? | Yes | No |
| Update weights? | Yes | Never |
| Random augmentation? | Usually yes | No; use deterministic preprocessing |
| Main purpose | Learn parameters | Measure and choose checkpoints/settings |
model.eval() does not calculate accuracy and does not disable gradients by itself. It changes the behaviour of layers such as dropout and batch normalization. torch.no_grad() separately prevents gradient recording, saving memory and computation.
How to Read Training Curves
At the end of each epoch, record average training loss and validation loss. A single point cannot show a trend, but the shape across several epochs can reveal whether learning is useful, overfitting or stalled.
Healthy learning
Overfitting
Learning has stalled
| Pattern | Likely meaning | What to check next |
|---|---|---|
| Both losses fall | The model is learning patterns that transfer. | Continue while validation improves; save the best checkpoint. |
| Training falls, validation rises | The model is increasingly memorizing training-specific details. | Use early stopping, data augmentation, weight decay, dropout or more representative data. |
| Both remain flat | The learning signal may be ineffective or the pipeline may be broken. | Check labels, gradients, learning rate, frozen parameters and loss/output compatibility. |
| Loss becomes NaN or explodes | Numerical instability or excessively large updates. | Inspect input scale, learning rate, loss math and gradient norms. |
The Tiny-Data Test: Check the Loop Before Tuning the Model
Before a long training run, take perhaps 10–20 clean examples and deliberately ask the model to memorize them. This is not the final goal. It is a diagnostic test: a sufficiently capable network should be able to drive training loss very low on such a tiny set.
1. Create the test
Use a fixed tiny batch with verified inputs and labels. Temporarily reduce augmentation and regularization.
2. Try to memorize
Train repeatedly on only those examples and watch training loss and accuracy.
3. Interpret
If loss cannot become very small, fix the data, model, gradients or loop before tuning generalization.
What the test does not prove: memorizing 20 examples only shows that the training path can fit them. It does not prove the model will generalize to new factory images.
A Complete PyTorch Training and Validation Loop
This code mirrors the diagrams exactly. The inner loop performs one correction per training batch. The second loop measures validation batches without gradients or updates.
for epoch in range(num_epochs):
# ----- TRAIN: weights change -----
model.train()
train_loss_sum = 0.0
for inputs, targets in train_loader: # 1. load batch
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad() # 2. clear old gradients
logits = model(inputs) # 3. forward pass
loss = loss_fn(logits, targets) # 4. calculate loss
loss.backward() # 5. backward pass
optimizer.step() # 6. update weights
train_loss_sum += loss.item() * inputs.size(0)
train_loss = train_loss_sum / len(train_loader.dataset)
# ----- VALIDATE: weights do not change -----
model.eval()
val_loss_sum = 0.0
correct = 0
with torch.no_grad():
for inputs, targets in val_loader:
inputs, targets = inputs.to(device), targets.to(device)
logits = model(inputs)
val_loss_sum += loss_fn(logits, targets).item() * inputs.size(0)
correct += (logits.argmax(dim=1) == targets).sum().item()
val_loss = val_loss_sum / len(val_loader.dataset)
val_accuracy = correct / len(val_loader.dataset)
print(epoch + 1, train_loss, val_loss, val_accuracy)| Code | Plain meaning | Common mistake it prevents |
|---|---|---|
| model.train() | Turn on training behaviour | Accidentally leaving dropout disabled |
| optimizer.zero_grad() | Remove gradients from the previous batch | Unwanted gradient accumulation |
| loss.backward() | Calculate current gradients | Optimizer stepping with no new direction |
| optimizer.step() | Change the weights | Thinking backward itself updates parameters |
| model.eval() | Use inference behaviour | Validation changing with dropout/BatchNorm mode |
| torch.no_grad() | Do not record a backward graph | Wasting validation memory and computation |
Built-In Training or a Custom Loop?
A custom loop is valuable for understanding and unusual training logic, but it also creates more opportunities for mistakes. Use the simplest interface that supports the actual experiment.
| Situation | Recommended approach | Why |
|---|---|---|
| Ordinary classification or regression | Built-in fit/trainer | Less boilerplate; callbacks and metrics are already integrated |
| Learn how training works | Small explicit loop | Every operation remains visible |
| Several losses or optimizers | Custom step or custom loop | You control exactly what updates and when |
| GANs, reinforcement learning, gradient accumulation | Custom loop | The algorithm does not fit one standard forward-loss-update cycle |
| Production experiment tracking | Framework loop plus callbacks when possible | Reduces custom state and resuming errors |
A Debugging Order That Saves Time
When training fails, changing the architecture first usually hides the real problem. Check the pipeline from the earliest input to the final update.
1. Inspect one batch
Print shapes, data type, minimum, maximum and several labels. Display images after preprocessing.
2. Check the forward output
Confirm output shape, finite values and the expected logits/probabilities for the loss.
3. Check loss on known cases
A better hand-made prediction should receive lower loss than a worse one.
4. Check gradients
Verify important parameters have non-None, finite gradient values and sensible norms.
5. Check the update
Compare one weight before and after optimizer.step(); it should change during training only.
6. Run the tiny-data test
Prove the model can fit 10–20 examples before adding regularization or more layers.
Common Mistakes
| Mistake | What goes wrong | Correction |
|---|---|---|
| Do not clear gradients | Current and earlier batch gradients are added | Call zero_grad each step unless accumulation is intentional |
| Validate in training mode | Dropout and BatchNorm behave incorrectly for evaluation | Call model.eval() before validation |
| Update on validation data | Validation stops being independent | Never call backward or optimizer.step in validation |
| Average batch means incorrectly | Small final batch can receive too much influence | Accumulate loss × batch size, then divide by example count |
| Watch accuracy only | Confidence and loss problems remain hidden | Track task metrics and loss together |
| Use the test set every epoch | Model choices indirectly overfit the test set | Tune on validation; evaluate test once choices are frozen |
What to remember
One batch creates one correction
Load → clear → forward → loss → backward → update.
One epoch visits the training set once
Batch size determines the number of updates per epoch.
Validation measures; it never teaches
Use evaluation mode, no gradients and no weight updates.
Curves are diagnostic evidence
Compare training and validation trends, then investigate causes in order.