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 and a model , the training loss is
| 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 , so minimizing it pulls the model toward the data |
The floor: conditional entropy
No model can push the expected loss below , 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:
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 , 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 for the true class costs 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.
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 on the true class and 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:
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 computelogsumexpstably; never takelog(softmax(z))in two separate steps. sklearn.metrics.log_lossreports the empirical cross-entropy in nats; divide bynp.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
nats bit. Predicting for both classes costs 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
. An untrained ImageNet classifier starts near this value.
Exercise 3: Information in a feature (code)
In the lesson's simulation, estimate in bits as the difference between the constant model's loss and the floor.
Answer
About 0.33 bits.
Solution
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…
- maximum likelihood estimation
- minimizing accuracy
- maximizing the entropy of the model
- minimizing squared error
The lowest possible expected cross-entropy for predicting Y from X is…
- 0
Why is cross-entropy called a proper scoring rule?
- Its expectation is minimized by reporting the true probabilities
- It is always positive
- It equals accuracy
- It is bounded