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.
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 useCrossEntropyLoss. A simple optimizer to start with is SGD with momentum.
Data loaders
Make sure you havetrain_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:model.train()to enable training-time behaviors (dropout, batchnorm updates).- Iterate batches: zero gradients, forward pass, compute loss, backward pass, optimizer step.
- Accumulate running loss to monitor progress.
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()oroptimizer.step()during validation.
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; usemodel.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 = 3for 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.