TExcelTAD
Home › Information Theory › Cross-Entropy

Cross-Entropy

Cross-entropy is the average code length when data from PP are encoded with a code built for QQ. 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

H(P,Q)=−∑xP(x)log⁡2Q(x)=H(P)+DKL(P∥Q)H(P, Q) = -\sum_x P(x)\log_2 Q(x) = H(P) + D_{\text{KL}}(P \parallel Q)

Because DKL≥0D_{\text{KL}} \ge 0, cross-entropy is never below the entropy: H(P,Q)≥H(P)H(P, Q) \ge H(P), with equality only for Q=PQ = P. The best model of a source is the source itself.

python · try it yourself
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 ℓ(x)=log⁡21Q(x)\ell(x) = \log_2 \frac{1}{Q(x)} (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:

python · try it yourself
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 DKL(P∥U)=0.25D_{\text{KL}}(P \parallel U) = 0.25 bits extra per symbol.

Empirical cross-entropy

In practice we do not know PP; we have samples x1,…,xnx_1, \dots, x_n from it. The empirical cross-entropy of a model QQ is the average negative log-probability of the samples:

H^=−1n∑i=1nlog⁡2Q(xi)\hat H = -\frac{1}{n}\sum_{i=1}^n \log_2 Q(x_i)

By the law of large numbers it converges to H(P,Q)H(P, Q). This is the number a language model reports as its loss, and 2H^2^{\hat H} is its perplexity (Perplexity).

python · try it yourself
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 y∈{0,1}y \in \{0, 1\} and a predicted probability qq of class 1:

BCE(y,q)=−ylog⁡q−(1−y)log⁡(1−q)\text{BCE}(y, q) = -y\log q - (1 - y)\log(1 - q)

This is cross-entropy between the one-hot label and the prediction, usually in nats.

python · try it yourself
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.CrossEntropyLoss and tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) take logits and compute −log⁡softmax-\log \text{softmax} stably (Softmax and Cross-Entropy Gradient).
  • sklearn.metrics.log_loss is the empirical cross-entropy in nats.
  • Losses are usually in nats; divide by ln⁡2\ln 2 to get bits.

Exercises

Exercise 1: Uniform model

Data come from P=(0.9,0.1)P = (0.9, 0.1) and the model is Q=(0.5,0.5)Q = (0.5, 0.5). What is H(P,Q)H(P, Q)?

Answer

1 bit.

Solution

Every symbol costs log⁡22=1\log_2 2 = 1 bit under the uniform code, whatever PP 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

−ln⁡0.001=6.908-\ln 0.001 = 6.908. A confident wrong prediction is punished heavily; as q→0q \to 0 the loss goes to infinity.

Exercise 3: Decomposition (code)

For P=(0.2,0.5,0.3)P = (0.2, 0.5, 0.3) and Q=(0.3,0.3,0.4)Q = (0.3, 0.3, 0.4), verify H(P,Q)=H(P)+DKL(P∥Q)H(P, Q) = H(P) + D_{\text{KL}}(P \parallel Q).

Answer

Both sides are about 1.6125 bits.

Solution
python · try it yourself
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 H(P,Q)H(P, Q) is smallest when…

  1. Q = P
  2. Q is uniform
  3. Q is one-hot
  4. P is uniform

The empirical cross-entropy of a model on a test set is…

  1. the average negative log-probability of the test samples
  2. the entropy of the test labels
  3. the accuracy
  4. 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?

  1. DKL(P∥Q)D_{\text{KL}}(P \parallel Q)
  2. DKL(Q∥P)D_{\text{KL}}(Q \parallel P)
  3. H(Q)H(Q)
  4. none