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

Cross-Entropy

Cross-entropy measures the difference between two probability distributions โ€” specifically, how well a model's predicted distribution matches the true distribution of labels. It is, without exaggeration, the single most widely used loss function in all of deep learning classification.

Formula

\[ H(p, q) = -\sum_x p(x)\log q(x) \]

\(p\) is the true distribution (for a labeled example, this is 1 for the correct class and 0 for every other class), and \(q\) is the model's predicted distribution (its softmax output). Because \(p\) is zero everywhere except the correct class \(y\), the sum collapses to a single term:

\[ H(p,q) = -\log q(y) \]

This is the loss for one example: the negative log of the probability the model assigned to the correct class. This exactly matches the negative log-likelihood derived in Maximum Likelihood Estimation.

Numerical Example

A 3-class classifier predicts \(q = [0.7, 0.2, 0.1]\) for classes [cat, dog, bird]. The true label is "cat" (\(p=[1,0,0]\)).

\[ H(p,q) = -\log(0.7) \approx 0.357 \]

If instead the model had predicted \(q=[0.1, 0.2, 0.7]\) (confidently wrong), the loss would be \(-\log(0.1) \approx 2.303\) โ€” much higher, correctly penalizing the confidently incorrect prediction far more heavily than a merely uncertain one.

Loss vs Confidence โ€” Why the Curve Matters

predicted probability of correct class (q(y)) loss loss → ∞ as q(y) → 0

Cross-entropy loss explodes as the model's predicted probability for the correct class approaches zero โ€” confidently wrong predictions are punished severely.

Code

import torch
import torch.nn as nn

loss_fn = nn.CrossEntropyLoss()   # expects raw logits, NOT softmax probabilities -- it applies softmax internally

logits = torch.tensor([[2.0, 0.5, -1.0]])   # raw scores for [cat, dog, bird]
true_label = torch.tensor([0])                # index 0 = "cat" is correct

loss = loss_fn(logits, true_label)
print(loss.item())   # a single scalar loss value

Binary Cross-Entropy โ€” The Two-Class Special Case

\[ \text{BCE} = -[y\log(\hat{y}) + (1-y)\log(1-\hat{y})] \]

For binary classification, this simplified form is used with a sigmoid output instead of softmax โ€” covered in full in the Loss Functions category next.

Common Mistakes

  • Applying softmax manually before passing predictions to PyTorch's nn.CrossEntropyLoss โ€” it already applies log_softmax internally for numerical stability; applying softmax twice silently produces a wrong (usually much smaller) gradient signal.
  • Forgetting cross-entropy is not symmetric: \(H(p,q) \ne H(q,p)\) in general โ€” the order matters, and deep learning always uses the true labels as \(p\) and the model's predictions as \(q\).

Interview Relevance

Q: "Why does cross-entropy loss penalize a confidently wrong prediction so much more than mean squared error would?" Cross-entropy is \(-\log q(y)\), which grows toward infinity as the predicted probability for the correct class approaches zero โ€” the logarithm's shape makes the penalty explode for confidently wrong predictions. MSE on probabilities grows only quadratically, penalizing the same mistake far less severely, which is part of why cross-entropy trains classifiers faster and more reliably.

Practice Question

A binary classifier predicts \(\hat y = 0.05\) for an example whose true label is 1 (positive). Compute the binary cross-entropy loss for this single example, and explain why it's a large value.

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

Cross-Entropy โ€“ FAQs

Quick answers about learning Cross-Entropy in Deep Learning.

This free note from CodingNow 2.0 explains Cross-Entropy 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 Cross-Entropy, is 100% free with no signup required.
With focused practice, most students grasp Cross-Entropy 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