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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
