Last updated 13 November 2026
What is cross-entropy loss?
Cross-entropy loss measures how far a model's predicted probabilities are from the true labels. For each example it is the negative log of the probability the model gave to the correct class, so a confident wrong answer is punished heavily. Binary cross-entropy (BCE) covers two classes and categorical cross-entropy covers many. On TensorTonic you implement cross-entropy and log loss from scratch, with tests that check your output.
You can implement cross-entropy loss yourself and test it against edge cases such as probabilities of exactly 0 and 1.
When training a classifier (image recognition, spam detection, language modeling), the model outputs probabilities for each class. For a cat image, it might output: (80% Cat, 20% Dog).
The true label is (100% Cat). We need a way to measure how "wrong" the prediction is. Cross-Entropy is that measure.
Why "Cross"?
Entropy measures uncertainty using the true distribution. Cross-Entropy measures uncertainty using a different (predicted) distribution. The "cross" refers to using P to weight but Q to compute information.
BCE vs MSE: which loss should you use?
Use binary cross-entropy for classification and mean squared error for regression. Both are maximum likelihood losses under different assumptions about the target, which is why mixing them up trains badly.
| Binary cross-entropy | Mean squared error | |
|---|---|---|
| Use for | Classification: yes or no labels, probabilities | Regression: continuous targets |
| Likelihood it assumes | Bernoulli | Gaussian noise |
| Gradient with sigmoid, w.r.t. the logit | ||
| Confidently wrong prediction | Large gradient, fast correction | Near-zero gradient, learning stalls |
Intuition: Penalty for Wrong Codes
Imagine you're designing a compression code for English text. You assign short codes to frequent letters ('e', 't') and long codes to rare letters ('z', 'q').
But what if you designed the code based on French letter frequencies? You'd use the wrong code lengths. Some letters would have wastefully long codes, others too short. This inefficiency is measured by Cross-Entropy.
If Q = P (perfect model), Cross-Entropy equals Entropy. If Q is wrong, Cross-Entropy is higher.
The General Formula
For discrete probability distributions P (truth) and Q (prediction):
We average over P (what actually happens) but compute information using Q (our model's probabilities).
Key Relationship
Cross-Entropy = Entropy of P + KL Divergence. Since H(P) is constant (data is fixed), minimizing Cross-Entropy is equivalent to minimizing KL Divergence.
Interactive: Loss Curve
Explore how the loss changes with prediction confidence. Notice the exponential penalty for confident wrong predictions.
Binary Cross-Entropy Loss
Adjust the model's prediction and see how the loss changes. Wrong confident predictions are heavily penalized.
True Label
1
Prediction
0.70
Loss
0.3567
Confidently Correct! The model's prediction aligns with the true label. Low loss.
Binary Cross-Entropy (BCE)
For binary classification (0 or 1), we have one output neuron with Sigmoid activation. Let be the label (0 or 1) and be the prediction.
If y = 1 (Positive)
Loss =
We want close to 1. If it's 0.9, loss is 0.1. If it's 0.001, loss is 6.9!
If y = 0 (Negative)
Loss =
We want close to 0.
Categorical Cross-Entropy (CCE)
For multi-class classification (MNIST digits 0-9, ImageNet 1000 classes), we use Softmax activation. Let be a one-hot vector (e.g., for digit 1).
Since y is one-hot, only the term for the true class survives:
This is why PyTorch's nn.CrossEntropyLoss only needs the class index, not a one-hot vector. The framework handles the one-hot encoding internally!
Interactive: BCE vs CCE
Compare how Binary and Categorical Cross-Entropy compute loss for different scenarios.
Binary vs Categorical Cross-Entropy
Compare how loss is calculated for binary classification (2 classes) vs multi-class classification.
Formula (y = 1)
Key Insight
Binary CE only considers the probability of the true class. As the model becomes more confident (p → 1), loss decreases. Wrong confident predictions (p → 0) have huge loss!
The Beautiful Gradient
One reason Cross-Entropy is preferred: its gradient with Softmax/Sigmoid is remarkably simple.
For Softmax + CCE:
The gradient is simply: prediction minus truth. No log derivatives, no complicated expressions. This is a consequence of the log in Cross-Entropy canceling with the exp in Softmax.
Why This Matters
When the model is very wrong ( far from y), the gradient is large, pushing for fast correction. When the model is nearly right, the gradient is small. The learning rate is "self-adjusting."
Why MSE fails for classification: the gradient
You can use MSE for classification, but it performs poorly due to the vanishing gradient problem.
MSE Problem
With MSE + Sigmoid, the gradient involves .
When z is very wrong (e.g., z = -10 but y = 1), the Sigmoid derivative is nearly 0. Gradient vanishes. Learning stops.
Cross-Entropy Fix
The log in CE cancels the exp in Sigmoid.
Gradient simplifies to . Large error = Large gradient. Learning continues strongly.
Interactive: Gradient Comparison
See the dramatic difference in gradient behavior between MSE and Cross-Entropy. Notice how MSE gradients vanish when the prediction is very wrong!
MSE vs Cross-Entropy: Gradient Comparison
See why Cross-Entropy is preferred: gradients stay large when the model is wrong, enabling faster learning.
Gradient Magnitude
MSE Gradient
Includes σ'(z) which vanishes when very wrong!
CE Gradient
Simple difference! Large error = large gradient.
The Problem with MSE
When the prediction is far from the truth (ŷ ≈ 0 but y = 1), the sigmoid derivative σ'(z) ≈ 0. This causes the MSE gradient to vanish, even though the model is very wrong!
Cross-Entropy avoids this: the log cancels the exp in sigmoid, giving a clean gradient that's proportional to the error. Learning never stalls.
Derivation from Maximum Likelihood
Cross-Entropy isn't arbitrary. It emerges naturally from Maximum Likelihood Estimation (MLE) assuming a Bernoulli distribution for binary classification.
The Derivation
Likelihood:
For Bernoulli:
Log-Likelihood:
Negative Log-Likelihood = Binary Cross-Entropy!
This connection shows that minimizing Cross-Entropy is equivalent to maximizing the likelihood of observing the training data. It's the principled statistical foundation for why this loss function works.
Interactive: MLE to BCE
Visualize the transformation from Likelihood to Cross-Entropy Loss. See how maximizing likelihood is equivalent to minimizing BCE.
Python implementation
In practice you compute cross-entropy from logits, not probabilities, so that very large or very small logits do not overflow or take the log of zero. The listing also compares the BCE and MSE gradients for one confidently wrong prediction.
import numpy as np
def bce_from_logits(z, y):
"""Binary cross-entropy from raw logits, stable for large |z|."""
return np.mean(np.maximum(z, 0) - z * y + np.log1p(np.exp(-np.abs(z))))
def cce_from_logits(z, y):
"""Categorical cross-entropy; z: [n, classes] logits, y: integer labels."""
z = z - z.max(axis=1, keepdims=True) # stable log-softmax
log_probs = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
return -np.mean(log_probs[np.arange(len(y)), y])
sigmoid = lambda z: 1 / (1 + np.exp(-z))
# One badly wrong prediction: true label 1, logit -10
z, y = np.array([-10.0]), np.array([1.0])
p = sigmoid(z)
grad_bce = p - y # dL/dz for BCE
grad_mse = 2 * (p - y) * p * (1 - p) # dL/dz for MSE on the probability
print(f"BCE loss = {bce_from_logits(z, y):.3f}")
print(f"dBCE/dz = {grad_bce[0]:.5f}")
print(f"dMSE/dz = {grad_mse[0]:.5f}")
print(f"CCE loss = {cce_from_logits(np.array([[2.0, 0.5, -1.0]]), np.array([0])):.3f}")BCE loss = 10.000 dBCE/dz = -0.99995 dMSE/dz = -0.00009 CCE loss = 0.241
With the true label 1 and a logit of -10, the BCE gradient is close to -1 and pushes hard toward the right answer, while the MSE gradient is about 11,000 times smaller. PyTorch's BCEWithLogitsLoss and CrossEntropyLoss apply the same stable formulas and expect logits, not probabilities.
ML Applications
Image Classification (CNNs)
ImageNet, CIFAR, MNIST: all use Categorical Cross-Entropy. ResNet, VGG, EfficientNet models are trained with CCE + Softmax to classify thousands of object categories.
Binary variant used for single-label detection (cat vs not-cat).
Natural Language Processing
Language models (GPT, BERT) predict next tokens using CCE over vocabulary, and perplexity is the exponential of that loss. Sentiment analysis uses BCE (positive/negative). Named Entity Recognition uses CCE per token.
Perplexity (model quality metric) is simply exp(Cross-Entropy).
Medical Diagnosis
Binary classification for disease detection (tumor/no tumor). Multi-class for disease type classification. Focal Loss (variant of CE) used for imbalanced medical datasets.
Calibrated probabilities matter for clinical decisions.
Recommender Systems
Click prediction (will user click? BCE). Multi-task learning with multiple BCE losses. Learning to rank using listwise CE.
Companies like Netflix, YouTube use variants for content recommendation.
Reinforcement Learning
Policy gradient methods use CE to train action distributions. Actor-Critic models optimize policy using CCE over discrete action spaces.
PPO, A3C algorithms rely on Cross-Entropy for policy updates.
Generative Models
Variational Autoencoders (VAEs) use BCE for binary data reconstruction. GANs use BCE in discriminator training. Diffusion models use variants for denoising objectives.
Critical for modern generative AI (Stable Diffusion, DALL-E).
Practice this
On TensorTonic you implement this from scratch and test it in the browser.
- Implement Cross-Entropy Loss: compute categorical cross-entropy from class probabilities with stable logs.
- Log Loss (Binary Cross-Entropy): implement the binary case from this lesson.
- Softmax + Cross-Entropy Gradient: derive the prediction-minus-truth gradient yourself.
- Binary Focal Loss: implement the cross-entropy variant that down-weights easy examples.
More problems include Binary Log Loss per Sample, Implement Numerically Stable Softmax and Implement the Sigmoid Function.
Frequently asked questions
What is the difference between binary and categorical cross-entropy?
Binary cross-entropy covers two classes, using one sigmoid output and the loss −[y ln(ŷ) + (1 − y) ln(1 − ŷ)]. Categorical cross-entropy covers many classes with a softmax output, and because the label is one-hot, only the term for the true class survives, giving −ln(ŷ_true).
Why does cross-entropy use a log?
The log comes from maximum likelihood estimation, because the negative log of the Bernoulli likelihood of the labels is exactly binary cross-entropy. Minimizing cross-entropy is therefore equivalent to maximizing the likelihood of observing the training data.
What is the difference between BCELoss and BCEWithLogitsLoss in PyTorch?
BCELoss expects probabilities, so you apply a sigmoid first, while BCEWithLogitsLoss takes raw logits and applies the sigmoid and binary cross-entropy in one step. The combined version computes the loss as max(z, 0) − z·y + log(1 + e^(−|z|)), which never takes the log of zero or overflows for large logits, so it is the safer choice. It also accepts a pos_weight argument that up-weights the positive class when the data is imbalanced.