Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Intermediate Deep Learning with PyTorch

Cursus bekijken

Oefeninstructies

  • Define the model using your Net class with num_classes set to 7 and assign it to net.
  • 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 to optimizer.
  • Start the training for-loop by iterating over training images and labels of dataloader_train.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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}")
Code bewerken en uitvoeren