Cross-entropy is a fundamental concept in information theory that measures the difference between two probability distributions. It calculates the average number of bits needed to identify an event from one probability distribution using the coding scheme optimized for another distribution.
Basic Cross-Entropy Formula
For two discrete probability distributions P and Q defined over the same set of events X, the cross-entropy is calculated as:
H(P, Q) = -∑(x∈X) P(x) × log(Q(x))[1][6]
Where:
- P(x) is the probability of event x in the true distribution P
- Q(x) is the probability of event x in the predicted distribution Q
- log is typically the base-2 logarithm (giving results in bits)[1]
If you use the natural logarithm (base-e) instead, the results will be in units called nats rather than bits[1].
Cross-Entropy for Continuous Distributions
For continuous probability distributions with probability density functions p and q, the formula becomes:
H(P, Q) = -∫ p(x) × log(q(x)) dx[6]
This is the integral form of the discrete formula above.
Relationship with Other Concepts
Cross-entropy can be expressed in terms of entropy and Kullback-Leibler (KL) divergence:
H(P, Q) = H(P) + KL(P || Q)[1]
Where:
- H(P) = -∑(x∈X) P(x) × log(P(x)) is the entropy of distribution P
- KL(P || Q) = ∑(x∈X) P(x) × log(P(x)/Q(x)) is the KL divergence of Q from P[1]
Cross-Entropy in Machine Learning
Binary Classification
For binary classification problems, the cross-entropy formula is often written as:
H = -∑[y_i × log(p_i) + (1-y_i) × log(1-p_i)][7]
Where:
- y_i is the true label (0 or 1)
- p_i is the predicted probability for class 1
Multi-Class Classification
For multi-class classification, the formula is:
H = -∑_i y_i × log(p_i)[3][7]
Where:
- y_i is often a one-hot encoded vector representing the true class
- p_i is the predicted probability for each class
Example Calculation
For a simple example with discrete probability distributions:
- P = [0.10, 0.40, 0.50] (true distribution)
- Q = [0.80, 0.15, 0.05] (predicted distribution)
The cross-entropy H(P, Q) = -(0.10 × log₂(0.80) + 0.40 × log₂(0.15) + 0.50 × log₂(0.05)) = 3.288 bits[1]
Cross-entropy is always positive, and it equals the entropy of the distribution if the two probability distributions are identical[1]. The minimum value of cross-entropy is achieved when the predicted distribution matches the true distribution exactly.