Python / PyTorch Fundamentals Interview Questions
What loss functions does PyTorch provide and how do you choose the right one?
The loss function defines the training objective. PyTorch's torch.nn module provides loss classes for classification, regression, and more specialised tasks. Choosing the wrong loss for your task is one of the most common beginner mistakes.
| Loss | Class | Input shape | Use case |
|---|---|---|---|
| MSELoss | nn.MSELoss() | pred & target same shape | Regression |
| L1Loss | nn.L1Loss() | pred & target same shape | Regression, robust to outliers |
| CrossEntropyLoss | nn.CrossEntropyLoss() | logits (N,C), target (N,) int64 | Multi-class classification |
| BCELoss | nn.BCELoss() | probabilities (N,), target (N,) float | Binary classification (after sigmoid) |
| BCEWithLogitsLoss | nn.BCEWithLogitsLoss() | raw logits (N,), target (N,) float | Binary classification (numerically stable) |
| NLLLoss | nn.NLLLoss() | log-probabilities (N,C) | Used after LogSoftmax manually |
import torch import torch.nn as nn # Γ’ΒΒΓ’ΒΒ Regression: MSE mse = nn.MSELoss() pred = torch.tensor([2.5, 3.0, 4.1]) target = torch.tensor([3.0, 3.0, 4.0]) loss = mse(pred, target) # mean((pred-target)^2) # Γ’ΒΒΓ’ΒΒ Multi-class classification: CrossEntropyLoss ce = nn.CrossEntropyLoss() logits = torch.randn(8, 5) # batch=8, 5 classes Γ’ΒΒ RAW logits targets = torch.randint(0, 5, (8,)) # class indices, dtype long loss = ce(logits, targets) # Γ’ΒΒΓ’ΒΒ Binary classification: BCEWithLogitsLoss (preferred over BCELoss) bce = nn.BCEWithLogitsLoss() # combines Sigmoid + BCE, numerically stable logits_binary = torch.randn(8, 1) targets_binary = torch.randint(0, 2, (8, 1)).float() loss = bce(logits_binary, targets_binary) # Γ’ΒΒΓ’ΒΒ Class-weighted CrossEntropy for imbalanced data class_weights = torch.tensor([1.0, 1.0, 5.0, 1.0, 1.0]) # upweight class 2 ce_weighted = nn.CrossEntropyLoss(weight=class_weights) # Γ’ΒΒΓ’ΒΒ Custom loss function class FocalLoss(nn.Module): def __init__(self, gamma=2.0): super().__init__() self.gamma = gamma self.ce = nn.CrossEntropyLoss(reduction="none") def forward(self, logits, targets): ce_loss = self.ce(logits, targets) pt = torch.exp(-ce_loss) focal = ((1 - pt) ** self.gamma * ce_loss).mean() return focal
More Related questions...