1. PyTorch Training Loop
A training loop repeatedly:- Takes input data.
- Makes predictions.
- Calculates loss.
- Calculates gradients.
- Updates model weights.
- Repeats for multiple epochs.
Basic structure
Flow
2. What is an Epoch?
An epoch means the model has gone through the entire training dataset once.3. What is a Batch?
Instead of giving the entire dataset to the model at once, we divide it into smaller groups called batches. Example:4. zero_grad()
PyTorch accumulates gradients by default.
Therefore, we clear the previous gradients before calculating new ones.
5. loss.backward()
This performs backpropagation.
6. optimizer.step()
This updates the model parameters using the calculated gradients.
7. Adam Optimizer
Adam = Adaptive Moment Estimation Adam is one of the most commonly used optimizers in deep learning.Why Adam?
Compared with basic SGD, Adam generally:- Converges quickly
- Adapts the learning rate for individual parameters
- Works well for many neural networks
- Requires relatively little manual tuning
8. Learning Rate
The learning rate controls how much the model changes its weights during each update.9. Adam Example
10. Learning-Rate Scheduler
A learning-rate scheduler changes the learning rate during training. Instead of keeping:11. StepLR Scheduler
One simple scheduler isStepLR.