Binary and Categorical Cross-Entropy
Almost every classifier you will train, from logistic regression to a large language model, minimises the same loss: cross-entropy, the negative log of the probability the model gave to the correct class. It rewards confident right answers a little, punishes confident wrong answers a lot, and its gradient with respect to the logits is the simplest one in machine learning: predicted probability minus target. This lesson implements the binary and the multiclass version in a way that cannot overflow, checks the gradients, and shows why squared error is the wrong loss for probabilities.
Binary cross-entropy (log loss)
A binary model outputs a logit (any real number), and the probability of class 1 is . For a label the loss is
which is when and when . Substituting the sigmoid and simplifying gives a form that works directly on the logit:
That is the whole gradient: the error in probability space. It comes from maximum likelihood with a Bernoulli model (Maximum Likelihood and Cross-Entropy), and its name from information theory: it is the cross-entropy between the label distribution and the model's (Entropy and KL Divergence).
Why the logit form
Computing first and then breaks for confident models: rounds to exactly 1.0 in float64, so . The logit form never forms ; np.logaddexp(0, z) computes exactly for any . This is why PyTorch has BCEWithLogitsLoss and why you should feed it raw logits, not sigmoid outputs.
import numpy as np
def bce_naive(y, z): # from logits, the textbook way
p = 1 / (1 + np.exp(-z))
return np.mean(-(y * np.log(p) + (1 - y) * np.log(1 - p)))
def bce_stable(y, z): # log(1 + e^z) - y z, computed with logaddexp
return np.mean(np.logaddexp(0, z) - y * z)
def bce_grad(y, z): # d loss / d z
return (1 / (1 + np.exp(-z)) - y) / len(y)
y = np.array([1.0, 0.0, 1.0, 0.0])
z = np.array([2.0, -1.0, -3.0, 0.5])
print("naive ", round(bce_naive(y, z), 6), " stable", round(bce_stable(y, z), 6))
h = 1e-6
num = np.array([(bce_stable(y, z + h * e) - bce_stable(y, z - h * e)) / (2 * h) for e in np.eye(4)])
print("gradient (p - y)/n:", np.round(bce_grad(y, z), 4), " numeric:", np.round(num, 4))
z_big = np.array([40.0, -40.0]) # very confident and wrong
y_big = np.array([0.0, 1.0])
with np.errstate(all="ignore"):
print("confident mistakes: naive", bce_naive(y_big, z_big), " stable", round(bce_stable(y_big, z_big), 3))naive 1.115714 stable 1.115714
gradient (p - y)/n: [-0.0298 0.0672 -0.2381 0.1556] numeric: [-0.0298 0.0672 -0.2381 0.1556]
confident mistakes: naive inf stable 40.0
On ordinary logits both versions agree (1.115714). On two confident mistakes ( for a negative, for a positive) the naive version returns inf, which would turn every weight into nan after one backward pass, while the stable one returns the correct loss of 40 per example. The analytic gradient matches the central difference to four decimals.
Categorical cross-entropy with softmax
With classes the model outputs a logit vector , and the softmax turns it into probabilities:
The gradient is again "probabilities minus target", now with a one-hot target :
Each row of the gradient sums to zero, because adding the same constant to every logit does not change the softmax. The same fact gives the numerically safe log-sum-exp: subtract before exponentiating, so the largest exponent is and nothing overflows (Overflow and the Stable Softmax, and the full derivation of the gradient in Softmax and Cross-Entropy Gradient).
import numpy as np
from sklearn.metrics import log_loss
def log_softmax(Z):
Zs = Z - Z.max(axis=1, keepdims=True) # shift: same result, no overflow
return Zs - np.log(np.exp(Zs).sum(axis=1, keepdims=True))
def ce(y, Z): # y: integer labels, Z: logits (n, K)
return -np.mean(log_softmax(Z)[np.arange(len(y)), y])
def ce_grad(y, Z): # (softmax - one-hot) / n
P = np.exp(log_softmax(Z))
P[np.arange(len(y)), y] -= 1
return P / len(y)
Z = np.array([[2.0, 0.5, -1.0],
[0.1, 0.2, 3.0],
[1.0, 1.0, 1.0]])
y = np.array([0, 1, 2])
print("cross-entropy", round(ce(y, Z), 4))
h, num = 1e-6, np.zeros_like(Z)
for i in range(3):
for k in range(3):
E = np.zeros_like(Z); E[i, k] = h
num[i, k] = (ce(y, Z + E) - ce(y, Z - E)) / (2 * h)
print("analytic gradient matches numeric:", np.allclose(ce_grad(y, Z), num, atol=1e-8))
print("gradient rows sum to", np.round(ce_grad(y, Z).sum(axis=1), 12) + 0.0)
P = np.exp(log_softmax(Z))
print("sklearn log_loss ", round(log_loss(y, P), 4))
print("huge logits still fine:", round(ce(np.array([0]), np.array([[1000.0, 0.0, -1000.0]])), 4) + 0.0,
round(ce(np.array([2]), np.array([[1000.0, 0.0, -1000.0]])), 1))cross-entropy 1.4165
analytic gradient matches numeric: True
gradient rows sum to [0. 0. 0.]
sklearn log_loss 1.4165
huge logits still fine: 0.0 2000.0
Our loss equals scikit-learn's log_loss (1.4165), the gradient passes the check, and logits of are no problem: the correct class costs 0.0, the wrong one exactly 2000 (the gap between its logit and the largest). With a naive softmax, would be inf and the result nan.
The third example has all logits equal: , so its loss is . That is the loss of a model that knows nothing about classes, a handy sanity check for the first step of a training run: an untrained network should start near .
Why not squared error on probabilities?
You could train a classifier by minimising . Compare the gradients with respect to the logit for a positive example () as the model becomes confidently wrong:
import numpy as np
sigmoid = lambda z: 1 / (1 + np.exp(-z))
y = 1.0
print(" logit z p dBCE/dz dMSE/dz")
for z in [-8.0, -4.0, -1.0, 0.0, 2.0]:
p = sigmoid(z)
g_bce = p - y # cross-entropy on the logit
g_mse = 2 * (p - y) * p * (1 - p) # squared error on the probability
print(f"{z:6.1f} {p:.4f} {g_bce:8.4f} {g_mse:8.4f}") logit z p dBCE/dz dMSE/dz
-8.0 0.0003 -0.9997 -0.0007
-4.0 0.0180 -0.9820 -0.0347
-1.0 0.2689 -0.7311 -0.2875
0.0 0.5000 -0.5000 -0.2500
2.0 0.8808 -0.1192 -0.0250
With squared error the gradient is , and the sigmoid's derivative goes to zero exactly when the model is most wrong: at the push is , so learning stalls. Cross-entropy's cancels that factor, and the gradient stays near , the largest possible, for a confident mistake. Combined with its probabilistic meaning, that is why cross-entropy is the default for classification.
In the libraries
| Task | PyTorch | Takes |
|---|---|---|
| binary, one logit per example | nn.BCEWithLogitsLoss(pos_weight=...) |
raw logits, float targets 0/1 |
| multiclass, one label per example | nn.CrossEntropyLoss(weight=..., label_smoothing=...) |
raw logits , integer labels |
| multi-label (several classes can be true) | nn.BCEWithLogitsLoss on logits |
one independent sigmoid per class |
CrossEntropyLoss applies log-softmax itself; adding your own softmax layer before it is a classic bug that still trains, just badly. Its weight and BCEWithLogitsLoss's pos_weight reweight classes for imbalanced data. Label smoothing replaces the one-hot target by , which stops the model from pushing logits to infinity and often improves calibration. In scikit-learn, LogisticRegression minimises this loss (Logistic Regression, Softmax Regression) and sklearn.metrics.log_loss evaluates it.
Pitfalls
- Sigmoid or softmax before the loss. Feed logits to
BCEWithLogitsLossandCrossEntropyLoss. Probabilities fed in are squashed twice. log(p)withpfrom a sigmoid. Overflows toinffor confident mistakes; use the logit form or clip to if you must.- A starting loss far from . A fresh model with a loss of 20 on 10 classes has exploding initial logits (check the initialisation).
- Reading the loss as accuracy. A loss of 0.3 means an average probability of about on the right class (geometric mean), not "70 % accurate".
Practice
- A three-class model outputs and the true class is the second. What are the loss and the gradient with respect to the logits?
Answer
Loss . Gradient : lower the first and third logits, raise the second. The entries sum to 0.
- Show that .
Answer
, and .
- Why is the per-example binary loss for equal to 40 (to within )?
Answer
. For large positive , : the loss grows linearly with a confident mistake.
Test yourself
What is the gradient of softmax cross-entropy with respect to the logits?
Why does PyTorch provide BCEWithLogitsLoss instead of asking you to apply a sigmoid and then BCELoss?
- It is faster to type
- Computing the loss from the logit with log-sum-exp avoids when the sigmoid rounds to 0 or 1
- It gives a different gradient
- Sigmoid is not differentiable
An untrained 10-class classifier should start with a cross-entropy loss near…
- 0
- 1
- 10
A positive example has logit . Which loss still gives a strong gradient to fix it?
- squared error on
- cross-entropy
- both equally
- neither