Python / PyTorch Fundamentals Interview Questions
What is overfitting and what regularization techniques does PyTorch support to address it?
Overfitting occurs when a model memorises the training data instead of learning generalisable patterns β visible as low training loss but high validation loss. PyTorch provides several built-in tools to combat overfitting.
| Technique | How to apply | Effect |
|---|---|---|
| Dropout | nn.Dropout(p=0.5) layer | Randomly zeroes activations during training, preventing co-adaptation |
| Weight decay (L2) | optimizer weight_decay= parameter | Penalises large weights, encourages simpler models |
| Early stopping | Manual: track val_loss, stop when it plateaus | Prevents training past the point of generalisation |
| Data augmentation | torchvision.transforms | Increases effective dataset size and diversity |
| Batch Normalization | nn.BatchNorm1d/2d | Stabilises training; has a mild regularising side effect |
| Label smoothing | CrossEntropyLoss(label_smoothing=0.1) | Prevents overconfident predictions |
import torch import torch.nn as nn class RegularizedNet(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.bn1 = nn.BatchNorm1d(256) self.drop = nn.Dropout(p=0.5) # 50% dropout self.fc2 = nn.Linear(256, 10) def forward(self, x): x = torch.relu(self.bn1(self.fc1(x))) x = self.drop(x) # active in train(), off in eval() return self.fc2(x) model = RegularizedNet() # Weight decay Γ’ΒΒ L2 penalty added by the optimizer optimizer = torch.optim.AdamW( model.parameters(), lr=1e-3, weight_decay=1e-2, # penalise large weights ) # Label smoothing Γ’ΒΒ softens hard one-hot targets criterion = nn.CrossEntropyLoss(label_smoothing=0.1) # Early stopping pattern best_val_loss = float("inf") patience, patience_counter = 5, 0 for epoch in range(100): train_loss = train_one_epoch(model, train_loader, optimizer, criterion, device) val_loss, _ = validate(model, val_loader, criterion, device) if val_loss < best_val_loss: best_val_loss = val_loss patience_counter = 0 torch.save(model.state_dict(), "best_model.pt") # save best checkpoint else: patience_counter += 1 if patience_counter >= patience: print(f"Early stopping at epoch {epoch}") break
More Related questions...