Python / Python Deep Learning and Neural Networks Interview Questions
What loss functions does PyTorch provide for classification and regression, and which to use when?
The choice of loss function should match the output type and the probabilistic assumption about the data-generating process — it is the mathematical link between model predictions and the training signal.
| Task | Loss | PyTorch class | Notes |
|---|---|---|---|
| Binary classification | Binary cross-entropy | nn.BCEWithLogitsLoss | Takes logits (pre-sigmoid); numerically stable |
| Multi-class classification | Cross-entropy | nn.CrossEntropyLoss | Takes logits; combines log-softmax + NLLLoss |
| Regression | MSE | nn.MSELoss | Sensitive to outliers |
| Regression (robust) | MAE / Huber | nn.L1Loss / nn.HuberLoss | Huber blends L1+L2; robust to outliers |
| Multi-label classification | BCE per label | nn.BCEWithLogitsLoss | Each label independent — not mutually exclusive |
| Contrastive / metric learning | Triplet margin | nn.TripletMarginLoss | Learns embeddings |
import torch
import torch.nn as nn
# Binary classification — output is a single logit (no sigmoid)
bce = nn.BCEWithLogitsLoss() # applies sigmoid internally
logit = torch.tensor([2.0, -1.0, 0.5])
label = torch.tensor([1.0, 0.0, 1.0])
loss = bce(logit, label)
# Multi-class — outputs are raw logits per class (no softmax)
ce = nn.CrossEntropyLoss()
logits = torch.randn(8, 10) # batch of 8, 10 classes
targets = torch.randint(0, 10, (8,)) # class indices 0-9
loss = ce(logits, targets)
# Class-weighted cross-entropy — for imbalanced datasets
weights = torch.tensor([1.0]*9 + [10.0]) # up-weight class 9
ce_weighted = nn.CrossEntropyLoss(weight=weights)
# Regression
mse = nn.MSELoss()
huber = nn.HuberLoss(delta=1.0) # L2 for |error|<1, L1 for |error|>1
pred = torch.randn(32, 1)
true = torch.randn(32, 1)
print(mse(pred, true), huber(pred, true))
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...
