TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Binary and Categorical Cross-Entropy

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 zz (any real number), and the probability of class 1 is p=σ(z)=1/(1+e−z)p = \sigma(z) = 1/(1 + e^{-z}). For a label y∈{0,1}y \in \{0, 1\} the loss is

ℓ(y,p)=−[ylog⁡p+(1−y)log⁡(1−p)]\ell(y, p) = -\big[ y \log p + (1 - y) \log(1 - p) \big]

which is −log⁡p-\log p when y=1y = 1 and −log⁡(1−p)-\log(1 - p) when y=0y = 0. Substituting the sigmoid and simplifying gives a form that works directly on the logit:

ℓ(y,z)=log⁡(1+ez)−yz,∂ℓ∂z=σ(z)−y=p−y.\ell(y, z) = \log(1 + e^{z}) - y z, \qquad \frac{\partial \ell}{\partial z} = \sigma(z) - y = p - y .

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 pp first and then log⁡p\log p breaks for confident models: σ(40)\sigma(40) rounds to exactly 1.0 in float64, so log⁡(1−p)=log⁡0=−∞\log(1 - p) = \log 0 = -\infty. The logit form never forms pp; np.logaddexp(0, z) computes log⁡(e0+ez)\log(e^0 + e^z) exactly for any zz. This is why PyTorch has BCEWithLogitsLoss and why you should feed it raw logits, not sigmoid outputs.

python · try it yourself
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 (z=40z = 40 for a negative, z=−40z = -40 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 (p−y)/n(p - y)/n matches the central difference to four decimals.

Categorical cross-entropy with softmax

With KK classes the model outputs a logit vector z∈RK\mathbf{z} \in \mathbb{R}^K, and the softmax turns it into probabilities:

pk=ezk∑j=1Kezj,ℓ(y,z)=−log⁡py=−zy+log⁡∑j=1Kezj.p_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}, \qquad \ell(y, \mathbf{z}) = -\log p_y = -z_y + \log \sum_{j=1}^{K} e^{z_j} .

The gradient is again "probabilities minus target", now with a one-hot target ey\mathbf{e}_y:

∂ℓ∂z=p−ey.\frac{\partial \ell}{\partial \mathbf{z}} = \mathbf{p} - \mathbf{e}_y .

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 max⁡jzj\max_j z_j before exponentiating, so the largest exponent is e0=1e^0 = 1 and nothing overflows (Overflow and the Stable Softmax, and the full derivation of the gradient in Softmax and Cross-Entropy Gradient).

python · try it yourself
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 ±1000\pm 1000 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, e1000e^{1000} would be inf and the result nan.

The third example has all logits equal: p=(1/3,1/3,1/3)p = (1/3, 1/3, 1/3), so its loss is log⁡3≈1.099\log 3 \approx 1.099. That is the loss of a model that knows nothing about K=3K = 3 classes, a handy sanity check for the first step of a training run: an untrained network should start near log⁡K\log K.

Why not squared error on probabilities?

You could train a classifier by minimising (p−y)2(p - y)^2. Compare the gradients with respect to the logit for a positive example (y=1y = 1) as the model becomes confidently wrong:

python · try it yourself
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 2(p−y)⋅p(1−p)2(p - y) \cdot p(1 - p), and the sigmoid's derivative p(1−p)p(1 - p) goes to zero exactly when the model is most wrong: at z=−8z = -8 the push is −0.0007-0.0007, so learning stalls. Cross-entropy's log⁡\log cancels that factor, and the gradient stays near −1-1, 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 (n,K)(n, K), integer labels
multi-label (several classes can be true) nn.BCEWithLogitsLoss on KK 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 (1−ε)ey+ε/K(1 - \varepsilon)\mathbf{e}_y + \varepsilon/K, 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 BCEWithLogitsLoss and CrossEntropyLoss. Probabilities fed in are squashed twice.
  • log(p) with p from a sigmoid. Overflows to inf for confident mistakes; use the logit form or clip pp to [10−7,1−10−7][10^{-7}, 1 - 10^{-7}] if you must.
  • A starting loss far from log⁡K\log K. 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 e−0.3≈0.74e^{-0.3} \approx 0.74 on the right class (geometric mean), not "70 % accurate".

Practice

  1. A three-class model outputs p=(0.7,0.2,0.1)\mathbf{p} = (0.7, 0.2, 0.1) and the true class is the second. What are the loss and the gradient with respect to the logits?
Answer

Loss −log⁡0.2≈1.609-\log 0.2 \approx 1.609. Gradient p−e2=(0.7,−0.8,0.1)\mathbf{p} - \mathbf{e}_2 = (0.7, -0.8, 0.1): lower the first and third logits, raise the second. The entries sum to 0.

  1. Show that ddz[log⁡(1+ez)−yz]=σ(z)−y\frac{d}{dz}\big[\log(1 + e^z) - yz\big] = \sigma(z) - y.
Answer

ddzlog⁡(1+ez)=ez1+ez=11+e−z=σ(z)\frac{d}{dz} \log(1 + e^z) = \frac{e^z}{1 + e^z} = \frac{1}{1 + e^{-z}} = \sigma(z), and ddz(yz)=y\frac{d}{dz}(yz) = y.

  1. Why is the per-example binary loss for z=40,y=0z = 40, y = 0 equal to 40 (to within 10−1710^{-17})?
Answer

log⁡(1+e40)−0=40+log⁡(1+e−40)≈40+4×10−18\log(1 + e^{40}) - 0 = 40 + \log(1 + e^{-40}) \approx 40 + 4 \times 10^{-18}. For large positive zz, log⁡(1+ez)≈z\log(1 + e^z) \approx z: the loss grows linearly with a confident mistake.

Test yourself

What is the gradient of softmax cross-entropy with respect to the logits?

  1. p−ey\mathbf{p} - \mathbf{e}_y
  2. −log⁡py-\log p_y
  3. p(1−p)\mathbf{p}(1 - \mathbf{p})
  4. ey/p\mathbf{e}_y / \mathbf{p}

Why does PyTorch provide BCEWithLogitsLoss instead of asking you to apply a sigmoid and then BCELoss?

  1. It is faster to type
  2. Computing the loss from the logit with log-sum-exp avoids log⁡0\log 0 when the sigmoid rounds to 0 or 1
  3. It gives a different gradient
  4. Sigmoid is not differentiable

An untrained 10-class classifier should start with a cross-entropy loss near…

  1. 0
  2. 1
  3. log⁡10≈2.30\log 10 \approx 2.30
  4. 10

A positive example has logit z=−8z = -8. Which loss still gives a strong gradient to fix it?

  1. squared error on pp
  2. cross-entropy
  3. both equally
  4. neither