๐Ÿ”ฅLimited Offer: Get 50% OFFon AI & Full Stack Courses๐Ÿ”ฅ
Back to Deep Learning Notes
Topic #353

PyTorch Loss Functions

A practical reference catalog of PyTorch's built-in loss functions โ€” every one already covered conceptually in the Loss Functions category, with exact syntax and the input-format details that most often trip people up.

Common Loss Functions, Quick Reference

LossPyTorch ClassExpectsConcept Note
MSEnn.MSELoss()Raw values for both prediction and targetMean Squared Error
MAEnn.L1Loss()Raw values for bothMean Absolute Error
Binary cross-entropynn.BCEWithLogitsLoss()Raw logits (NOT sigmoid-activated) + float labelsBinary Cross-Entropy
Categorical cross-entropynn.CrossEntropyLoss()Raw logits (NOT softmax-activated) + integer class indicesCategorical Cross-Entropy
Huber lossnn.HuberLoss(delta=1.0)Raw values for bothHuber Loss
KL divergencenn.KLDivLoss()Log-probabilities (first arg) + probabilities (second arg)KL Divergence Loss

Code โ€” The Two Most Error-Prone Losses

import torch
import torch.nn as nn

# CrossEntropyLoss: raw logits + INTEGER class indices (not one-hot, not softmax-applied)
logits = torch.tensor([[2.0, 0.5, -1.0]])
labels = torch.tensor([0])                # integer index, not [1, 0, 0]
loss = nn.CrossEntropyLoss()(logits, labels)

# BCEWithLogitsLoss: raw logits + FLOAT labels (0.0 or 1.0)
logits_binary = torch.tensor([1.5])
labels_binary = torch.tensor([1.0])        # float, not int
loss_binary = nn.BCEWithLogitsLoss()(logits_binary, labels_binary)

Common Mistakes

  • Applying softmax/sigmoid manually before passing predictions to CrossEntropyLoss/BCEWithLogitsLoss โ€” as flagged throughout this hub, this double-applies the activation and corrupts gradients.
  • Passing float labels to CrossEntropyLoss (which needs integer class indices) or integer labels to BCEWithLogitsLoss (which needs floats) โ€” PyTorch will often raise a clear type error here, but it's a common first-time mistake.
  • Using reduction='sum' when 'mean' (the default) was intended, or vice versa โ€” this changes the loss's effective scale relative to the learning rate, silently affecting training dynamics.

Interview Relevance

Q: "Why does nn.CrossEntropyLoss expect raw logits rather than softmax probabilities as input?" It applies log_softmax internally, computed in a numerically stable, combined way (avoiding the precision issues of computing softmax and then taking its log as two separate steps). Passing already-softmaxed probabilities would apply softmax twice, producing a mathematically incorrect loss and corrupted gradients.

Practice Question

For a binary classification model's raw output logit of 2.3 and a true label of 1, which PyTorch loss class would you use directly, without any manual activation applied first?

Want to go beyond the notes?

Join CodingNow 2.0's Deep Learning course โ€” live mentorship, real projects, and 100% placement support.

Enroll Now โ€” Free Demo Available

PyTorch Loss Functions โ€“ FAQs

Quick answers about learning PyTorch Loss Functions in Deep Learning.

This free note from CodingNow 2.0 explains PyTorch Loss Functions in Deep Learning โ€” concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Deep Learning topic on CodingNow 2.0, including PyTorch Loss Functions, is 100% free with no signup required.
With focused practice, most students grasp PyTorch Loss Functions in 1โ€“3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) โ€” expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now