Image classifier training loop
It's time to train the image classifier! You will use the Net
you defined earlier and train it to distinguish between seven cloud types.
To define the loss and optimizer, you will need to use functions from torch.nn
and torch.optim
, imported for you as nn
and optim
, respectively. You don't need to change anything in the training loop itself: it's exactly like the ones you wrote before, with some additional logic to print the loss during training.
This exercise is part of the course
Intermediate Deep Learning with PyTorch
Exercise instructions
- Define the model using your
Net
class withnum_classes
set to7
and assign it tonet
. - Define the loss function as cross-entropy loss and assign it to
criterion
. - Define the optimizer as Adam, passing it the model's parameters and the learning rate of
0.001
, and assign it tooptimizer
. - Start the training for-loop by iterating over training
images
andlabels
ofdataloader_train
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define the model
____ = ____
# Define the loss function
____ = ____
# Define the optimizer
____ = ____
for epoch in range(3):
running_loss = 0.0
# Iterate over training batches
____
optimizer.zero_grad()
outputs = net(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
epoch_loss = running_loss / len(dataloader_train)
print(f"Epoch {epoch+1}, Loss: {epoch_loss:.4f}")