Training is the process of adjusting a model’s parameters so it can perform a task using examples. A neural network learns useful representations as its weights and biases change, rather than relying entirely on features designed by hand. The goal is not just to fit the training examples, but to work well on unseen data from the same data-generating process. section 1.2 section 6.1.6
A training loop repeatedly runs the model, measures how far its output is from the target, and updates its parameters to reduce that error. In PyTorch, a loss function measures the error, autograd computes gradients, and an optimizer uses those gradients to make updates. section 1.5 section 6.2.2
A typical PyTorch training step follows this order:
- Run a batch of inputs through the model and compute the loss against the targets. section 8.4
- Clear old gradients with optimizer.zero_grad(), then call loss.backward() to calculate new gradients. section 8.4
- Call optimizer.step() to update the parameters, and record useful measures such as loss. section 8.4
# In[31]:
import datetime #1
def training_loop(n_epochs, optimizer, model, loss_fn, train_loader):
for epoch in range(1, n_epochs + 1): #2
start_time = datetime.datetime.now()
loss_train = 0.0
for imgs, labels in train_loader: #3
outputs = model(imgs) #4
loss = loss_fn(outputs, labels) #5
optimizer.zero_grad() #6
loss.backward() #7
optimizer.step() #8
loss_train += loss.item() #9
end_time = datetime.datetime.now()
epoch_duration = (end_time - start_time).total_seconds()
if epoch == 1 or epoch % 10 == 0:
print('{} Epoch {}, Training loss {:.6f}, Time {:.2f}s'.format(
datetime.datetime.now(), epoch,
loss_train / len(train_loader), epoch_duration)) #10
This loop puts the steps together, with an outer loop over epochs and an inner loop over batches. section 8.4
An epoch is one complete pass through the training dataset. A training step usually processes one batch, so a dataset split into several batches takes several steps per epoch. Shuffling and training on small batches gives an approximate gradient for each update rather than one calculated from the entire dataset. section 5.4.3 section 7.2.5
Fitting a temperature model
A linear model can learn to predict one thermometer’s readings from another’s. If the learning rate is too large, updates can overshoot and loss can grow to infinity. A smaller learning rate can stabilize the updates; rescaling the input can also make the gradients more manageable. section 5.4.3 section 5.4.4
Training loss alone does not establish how well a model will generalize. Check performance on a separate validation set as training progresses. For validation in PyTorch, set the model to eval() mode and disable gradient calculation with torch.no_grad(). section 6.1.6 section 15.7.3
Beyond classification
The same loop can train different tasks by changing the model and loss. A diffusion model, for example, learns to predict noise added to an image using mean squared error between predicted and actual noise. A segmentation model instead trains on images and their corresponding masks. section 10.6.1 section 15.7.3























