Skip to main content
Congratulations — you’ve reached the hands-on portion. In this lesson we build and train a simple convolutional neural network (CNN) in PyTorch and walk through standard training and validation loops. Quick review: in PyTorch you define a model by creating a class that inherits from nn.Module. The class typically implements two methods:
  • __init__ — define layers and components of the network.
  • forward — define the forward pass through those layers to produce predictions.
Below is a compact, commonly used example: a simple CNN for image classification.
Create a model instance and move it to the appropriate device (CPU or GPU). PyTorch makes device selection straightforward:
Example printed model structure (console output):
Tip: Always confirm that your model and data are on the same device. Moving only the model to GPU and forgetting to move the inputs will cause runtime errors.

Loss, optimizer, and hyperparameters

For multi-class classification use CrossEntropyLoss. A simple optimizer to start with is SGD with momentum.
A small example hyperparameter set for this demo:

Data loaders

Make sure you have train_loader and val_loader prepared as torch.utils.data.DataLoader instances. Each loader should yield batches in the form (inputs, labels). The training and validation loops below assume those are available.

Minimal training loop (no validation)

Typical training loop steps:
  1. model.train() to enable training-time behaviors (dropout, batchnorm updates).
  2. Iterate batches: zero gradients, forward pass, compute loss, backward pass, optimizer step.
  3. Accumulate running loss to monitor progress.
Sample output (illustrative):

Training with validation

Validation helps monitor generalization and spot overfitting. For validation:
  • Use model.eval() to disable dropout and use running statistics for batchnorm.
  • Wrap the validation loop in torch.no_grad() to avoid computing gradients.
  • Do not call loss.backward() or optimizer.step() during validation.
Combined training + validation loop:
Example output (illustrative):
Validation loss decreasing along with training loss is a good sign of generalization. If training loss keeps decreasing but validation loss plateaus or increases, that indicates overfitting — consider regularization, data augmentation, or early stopping.

Notes and best practices

  • Always move inputs and labels to the same device as the model: inputs = inputs.to(device); labels = labels.to(device).
  • Use model.train() when training to enable dropout and batchnorm updates; use model.eval() when validating or testing to disable them.
  • Wrap validation/testing code in with torch.no_grad(): to save memory and computation.
  • The demo uses N_EPOCHS = 3 for brevity — production models typically require many more epochs.
  • To improve performance consider:
    • Increasing epochs and using early stopping based on validation loss.
    • Adjusting learning rate and using learning rate schedules (e.g., ReduceLROnPlateau, StepLR).
    • Using data augmentation and regularization (dropout, weight decay).
    • Switching to adaptive optimizers (Adam) and monitoring their behavior compared to SGD with momentum.
    • Monitoring additional metrics such as accuracy, precision, recall, or confusion matrix for classification.

Quick reference table

You now have a basic, repeatable workflow for defining a PyTorch model, training it, and validating its performance.

Watch Video

Practice Lab