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
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...
