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

Binary Cross-Entropy

Binary cross-entropy (BCE) is cross-entropy specialized for the two-class case โ€” the standard loss for any binary classification network, always paired with a sigmoid output.

Formula

\[ \text{BCE} = -\frac{1}{n}\sum_{i=1}^n \big[y_i\log(\hat{y}_i) + (1-y_i)\log(1-\hat{y}_i)\big] \]

\(y_i \in \{0,1\}\) is the true label, \(\hat{y}_i \in (0,1)\) is the model's predicted probability (from sigmoid). Only one of the two terms is ever "active" for a given example: if \(y_i=1\), the second term vanishes (\(1-y_i=0\)) and the loss is \(-\log(\hat y_i)\); if \(y_i=0\), the first term vanishes and the loss is \(-\log(1-\hat y_i)\) โ€” exactly the general cross-entropy formula from Cross-Entropy, specialized to 2 classes.

Numerical Example

Three examples: \(y=1, \hat y=0.9\) โ†’ \(-\log(0.9)\approx0.105\). \(y=0, \hat y=0.2\) โ†’ \(-\log(1-0.2)=-\log(0.8)\approx0.223\). \(y=1, \hat y=0.3\) โ†’ \(-\log(0.3)\approx1.204\) (a confidently wrong-ish prediction, penalized much more heavily).

\[ \text{BCE} = \frac{0.105+0.223+1.204}{3} \approx 0.511 \]

The Critical Implementation Detail: BCELoss vs BCEWithLogitsLoss

PyTorch LossExpects as InputApplies Sigmoid Internally?
nn.BCELossAlready-sigmoided probabilities in (0,1)No โ€” you must apply torch.sigmoid() yourself first
nn.BCEWithLogitsLossRaw logits (any real number)Yes โ€” combines sigmoid + BCE in one numerically stable operation

BCEWithLogitsLoss is generally preferred: computing \(\log(\sigma(z))\) directly (rather than computing \(\sigma(z)\) first, then taking its log separately) avoids numerical instability for very negative or very positive logits โ€” the same numerical-stability principle behind softmax's max-subtraction trick from Softmax Function.

Code

import torch
import torch.nn as nn

# Correct: BCEWithLogitsLoss expects raw logits, applies sigmoid internally
logits = torch.tensor([2.0, -1.5, 0.5])
labels = torch.tensor([1.0, 0.0, 1.0])
loss_fn = nn.BCEWithLogitsLoss()
print(loss_fn(logits, labels))

# Equivalent but less numerically stable: manual sigmoid + BCELoss
probs = torch.sigmoid(logits)
loss_fn_manual = nn.BCELoss()
print(loss_fn_manual(probs, labels))   # same result, computed less safely

Common Mistakes

  • Applying sigmoid manually and then using BCEWithLogitsLoss โ€” this double-applies sigmoid, exactly the same class of bug flagged for softmax + CrossEntropyLoss.
  • Using BCELoss directly on raw logits (forgetting the sigmoid entirely) โ€” this passes values outside (0,1) into a log-based formula that expects probabilities, producing nonsensical (often NaN) losses.

Interview Relevance

Q: "Why does PyTorch recommend BCEWithLogitsLoss over manually applying sigmoid then BCELoss?" Numerical stability โ€” computing the log of a sigmoid output separately can lose precision or produce NaN for extreme logit values, while BCEWithLogitsLoss combines the sigmoid and log-loss computation into a single, more numerically stable operation (similar to how CrossEntropyLoss combines softmax and log internally).

Practice Question

For a single example with true label \(y=0\) and predicted probability \(\hat y = 0.05\), compute the binary cross-entropy loss. Is this a small or large loss value, and does that match your intuition for a confident, correct prediction?

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

Binary Cross-Entropy โ€“ FAQs

Quick answers about learning Binary Cross-Entropy in Deep Learning.

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