Cross-Entropy
Cross-entropy is the average code length when data from are encoded with a code built for . It is also the most used loss function in machine learning. This lesson develops it as an information quantity; Cross-Entropy as a Loss applies it to training models.
Definition
Because , cross-entropy is never below the entropy: , with equality only for . The best model of a source is the source itself.
import numpy as np
P = np.array([0.5, 0.25, 0.125, 0.125])
for name, Q in [("Q = P", P), ("uniform", np.ones(4) / 4), ("reversed", P[::-1]), ("almost P", np.array([0.45, 0.3, 0.125, 0.125]))]:
print(f"{name:9s} H(P,Q) = {-np.sum(P * np.log2(Q)):.4f} bits")
print("entropy H(P) =", float(-np.sum(P * np.log2(P))))Q = P H(P,Q) = 1.7500 bits
uniform H(P,Q) = 2.0000 bits
reversed H(P,Q) = 2.6250 bits
almost P H(P,Q) = 1.7602 bits
entropy H(P) = 1.75
Code lengths in action
With code lengths (rounded up for a real code), the average length is the cross-entropy. Here a prefix code designed for the uniform distribution and one designed for the true distribution compress the same message:
import numpy as np
rng = np.random.default_rng(0)
P = np.array([0.5, 0.25, 0.125, 0.125])
msg = rng.choice(4, size=100_000, p=P)
code_true = ["0", "10", "110", "111"] # lengths log2(1/P)
code_flat = ["00", "01", "10", "11"] # lengths log2(1/uniform)
for name, code in [("matched code", code_true), ("uniform code", code_flat)]:
bits = sum(len(code[s]) for s in msg)
print(f"{name}: {bits / msg.size:.4f} bits/symbol")matched code: 1.7482 bits/symbol
uniform code: 2.0000 bits/symbol
The matched code reaches the entropy 1.75; the uniform code pays bits extra per symbol.
Empirical cross-entropy
In practice we do not know ; we have samples from it. The empirical cross-entropy of a model is the average negative log-probability of the samples:
By the law of large numbers it converges to . This is the number a language model reports as its loss, and is its perplexity (Perplexity).
import numpy as np
rng = np.random.default_rng(1)
P = np.array([0.6, 0.3, 0.1]); Q = np.array([0.5, 0.3, 0.2])
exact = -np.sum(P * np.log2(Q))
for n in [10, 1000, 100_000]:
x = rng.choice(3, size=n, p=P)
print(f"n = {n:6d}: empirical {-np.mean(np.log2(Q[x])):.4f} exact {exact:.4f}")n = 10: empirical 1.3381 exact 1.3533
n = 1000: empirical 1.3611 exact 1.3533
n = 100000: empirical 1.3532 exact 1.3533
Binary cross-entropy
For a binary label and a predicted probability of class 1:
This is cross-entropy between the one-hot label and the prediction, usually in nats.
import numpy as np
y = np.array([1, 0, 1, 1, 0]); q = np.array([0.9, 0.2, 0.6, 0.99, 0.4])
bce = -(y * np.log(q) + (1 - y) * np.log(1 - q))
print("per example:", np.round(bce, 4))
print("mean:", round(float(bce.mean()), 4), "nats")per example: [0.1054 0.2231 0.5108 0.0101 0.5108]
mean: 0.272 nats
In software
torch.nn.CrossEntropyLossandtf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)take logits and compute stably (Softmax and Cross-Entropy Gradient).sklearn.metrics.log_lossis the empirical cross-entropy in nats.- Losses are usually in nats; divide by to get bits.
Exercises
Exercise 1: Uniform model
Data come from and the model is . What is ?
Answer
1 bit.
Solution
Every symbol costs bit under the uniform code, whatever is.
Exercise 2: Overconfidence
A classifier predicts probability 0.001 for the true class. What is its cross-entropy loss for this example, in nats?
Answer
About 6.91 nats.
Solution
. A confident wrong prediction is punished heavily; as the loss goes to infinity.
Exercise 3: Decomposition (code)
For and , verify .
Answer
Both sides are about 1.6125 bits.
Solution
import numpy as np
P = np.array([0.2, 0.5, 0.3]); Q = np.array([0.3, 0.3, 0.4])
cross = -np.sum(P * np.log2(Q))
print(round(float(cross), 4), round(float(-np.sum(P * np.log2(P)) + np.sum(P * np.log2(P / Q))), 4))1.6125 1.6125
Test yourself
Cross-entropy is smallest when…
- Q = P
- Q is uniform
- Q is one-hot
- P is uniform
The empirical cross-entropy of a model on a test set is…
- the average negative log-probability of the test samples
- the entropy of the test labels
- the accuracy
- the KL divergence between train and test sets
Using a code built for Q on data from P costs on average how many extra bits per symbol?
- none