TExcelTAD
Home › Information Theory › Cross-Entropy as a Loss

Cross-Entropy as a Loss

Almost every classifier and language model is trained by minimizing cross-entropy. Information theory explains why this is the right loss: minimizing it is maximum likelihood, it measures the model's code length for the labels, and its gap to the best possible value is a KL divergence. Maximum Likelihood and Cross-Entropy and Softmax and Cross-Entropy Gradient derive the deep-learning mechanics; this lesson focuses on the information view.

Three views of one loss

For labels yiy_i and a model qθ(y∣x)q_\theta(y \mid x), the training loss is

L(θ)=−1n∑i=1nlog⁡qθ(yi∣xi)\mathcal{L}(\theta) = -\frac{1}{n}\sum_{i=1}^n \log q_\theta(y_i \mid x_i)
View Interpretation
statistics negative average log-likelihood: minimizing it is maximum likelihood
coding the average number of nats (or bits) to encode the labels with the model's code
divergence empirical cross-entropy H(P^,qθ)=H(P^)+DKL(P^∥qθ)H(\hat P, q_\theta) = H(\hat P) + D_{\text{KL}}(\hat P \parallel q_\theta), so minimizing it pulls the model toward the data

The floor: conditional entropy

No model can push the expected loss below H(Y∣X)H(Y \mid X), the label uncertainty that remains given the features (Joint and Conditional Entropy). The excess over that floor is the average KL divergence between the true conditional and the model:

E[−log⁡q(Y∣X)]=H(Y∣X)+EX[DKL(P(⋅∣X)∥q(⋅∣X))]E[-\log q(Y \mid X)] = H(Y \mid X) + E_X\left[D_{\text{KL}}(P(\cdot \mid X) \parallel q(\cdot \mid X))\right]
python · try it yourself
import numpy as np
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(0)
n = 50_000
x = rng.normal(size=(n, 1))
p_true = 1 / (1 + np.exp(-(2.0 * x[:, 0] - 0.5)))         # true P(y=1 | x)
y = (rng.random(n) < p_true).astype(int)
floor = np.mean(-(p_true * np.log(p_true) + (1 - p_true) * np.log(1 - p_true)))
model = LogisticRegression(C=1e6).fit(x, y)
q = model.predict_proba(x)[:, 1]
loss = np.mean(-(y * np.log(q) + (1 - y) * np.log(1 - q)))
const = np.mean(y)
baseline = np.mean(-(y * np.log(const) + (1 - y) * np.log(1 - const)))
print(f"H(Y|X) (floor):          {floor:.4f} nats")
print(f"logistic regression loss: {loss:.4f} nats")
print(f"constant model loss:      {baseline:.4f} nats  (= H(Y), ignores x)")
H(Y|X) (floor):          0.4541 nats
logistic regression loss: 0.4557 nats
constant model loss:      0.6827 nats  (= H(Y), ignores x)

The fitted model comes within 0.002 nats of the floor; the gap between the constant model and the floor is I(X;Y)I(X; Y), the information the feature carries about the label.

Why not squared error or accuracy?

  • Accuracy is not differentiable and ignores confidence.
  • Squared error on probabilities gives tiny gradients for confident wrong predictions. Cross-entropy punishes them heavily: predicting probability 10−410^{-4} for the true class costs 9.29.2 nats.
  • Cross-entropy is a proper scoring rule: its expected value is minimized only by reporting the true probabilities, so the model is rewarded for being calibrated.
python · try it yourself
import numpy as np

true_p = 0.7                                      # the label is 1 with probability 0.7
qs = np.linspace(0.01, 0.99, 99)
ce = -(true_p * np.log(qs) + (1 - true_p) * np.log(1 - qs))
sq = true_p * (1 - qs)**2 + (1 - true_p) * qs**2
print("cross-entropy minimized at q =", round(float(qs[ce.argmin()]), 2))
print("squared error minimized at q =", round(float(qs[sq.argmin()]), 2))
print("gradient magnitude at q = 0.01 for a true label 1:  CE", round(1 / 0.01, 1), "  squared", round(2 * 0.99, 2))
cross-entropy minimized at q = 0.7
squared error minimized at q = 0.7
gradient magnitude at q = 0.01 for a true label 1:  CE 100.0   squared 1.98

Both scores are proper (they are minimized at 0.7), but only cross-entropy's gradient grows without bound as a wrong prediction becomes more confident.

Label smoothing and its cost

Label smoothing replaces the one-hot target with (1−ϵ)(1 - \epsilon) on the true class and ϵK−1\frac{\epsilon}{K - 1} on the others. The loss then has a floor of at least the entropy of the smoothed target, and the optimal prediction is never fully confident:

python · try it yourself
import numpy as np

K = 10
for eps in [0.0, 0.05, 0.1, 0.2]:
    target = np.full(K, eps / (K - 1)); target[0] = 1 - eps
    nz = target > 0
    print(f"eps = {eps:.2f}: loss floor = entropy of target = {float(-np.sum(target[nz] * np.log(target[nz]))) + 0.0:.4f} nats, "
          f"best confidence {1 - eps:.2f}")
eps = 0.00: loss floor = entropy of target = 0.0000 nats, best confidence 1.00
eps = 0.05: loss floor = entropy of target = 0.3084 nats, best confidence 0.95
eps = 0.10: loss floor = entropy of target = 0.5448 nats, best confidence 0.90
eps = 0.20: loss floor = entropy of target = 0.9398 nats, best confidence 0.80

In software

  • Frameworks fuse softmax and cross-entropy (torch.nn.CrossEntropyLoss, tf.nn.softmax_cross_entropy_with_logits) and compute logsumexp stably; never take log(softmax(z)) in two separate steps.
  • sklearn.metrics.log_loss reports the empirical cross-entropy in nats; divide by np.log(2) for bits.
  • A model's validation cross-entropy minus the best achievable value is a direct measure of how much it could still improve, which is the basis of scaling-law fits (Scaling Laws).

Exercises

Exercise 1: Units

A classifier's loss is 0.693 nats per example. What is that in bits, and what simple model achieves it on a balanced binary task?

Answer

1 bit; the model that always predicts 0.5.

Solution

0.693=ln⁡20.693 = \ln 2 nats =1= 1 bit. Predicting 12\frac{1}{2} for both classes costs ln⁡2\ln 2 on every example.

Exercise 2: Uniform over K classes

What is the cross-entropy loss of a model that predicts the uniform distribution over 1000 classes?

Answer

About 6.91 nats.

Solution

ln⁡1000=6.908\ln 1000 = 6.908. An untrained ImageNet classifier starts near this value.

Exercise 3: Information in a feature (code)

In the lesson's simulation, estimate I(X;Y)I(X; Y) in bits as the difference between the constant model's loss and the floor.

Answer

About 0.33 bits.

Solution
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
n = 50_000
x = rng.normal(size=n)
p = 1 / (1 + np.exp(-(2.0 * x - 0.5)))
y = (rng.random(n) < p).astype(int)
floor = np.mean(-(p * np.log(p) + (1 - p) * np.log(1 - p)))
c = y.mean()
HY = -(c * np.log(c) + (1 - c) * np.log(1 - c))
print(round(float((HY - floor) / np.log(2)), 4), "bits")
0.3297 bits

Test yourself

Minimizing cross-entropy loss on training labels is equivalent to…

  1. maximum likelihood estimation
  2. minimizing accuracy
  3. maximizing the entropy of the model
  4. minimizing squared error

The lowest possible expected cross-entropy for predicting Y from X is…

  1. H(Y∣X)H(Y \mid X)
  2. 0
  3. H(Y)H(Y)
  4. I(X;Y)I(X; Y)

Why is cross-entropy called a proper scoring rule?

  1. Its expectation is minimized by reporting the true probabilities
  2. It is always positive
  3. It equals accuracy
  4. It is bounded