Cross-entropy and KL divergence — measuring the gap between distributions
Cross-entropy and KL divergence -- measuring the gap between distributions
Cross-entropy is the most commonly used loss function for classification tasks. KL divergence measures how dissimilar two probability distributions are.
Concept analysis
The previous chapter covered entropy—measuring the degree of randomness within a single distribution. The two concepts in this chapter measure the gap between two distributions, which directly determines the design of the loss function in classification tasks.
Cross-entropy
[ H(p, q) = -\sum_x p(x) \log q(x) ]
Meaning: how much information is, on average, spent when encoding data from the true distribution p using the predicted distribution q.
KL Divergence (Relative Entropy)
[ D_{KL}(p | q) = \sum_x p(x) \log \frac{p(x)}{q(x)} = \underbrace{H(p,q)}{Cross-Entropy} - \underbrace{H(p)}{True Entropy} ]
Meaning: The extra information lost when q replaces p. KL ≥ 0, and equals 0 when p=q.
KL DivergenceAsymmetric:D_KL(p||q) ≠ D_KL(q||p), so it is not a true "distance".
When the true distribution p is one-hot (deterministic), H(p)=0, and cross-entropy equals KL divergence.
Why use cross-entropy instead of MSE for classification?
The gradient of cross-entropy + Softmax is ( \hat{y} - y ) (prediction - true), which is concise and efficient.
The gradient of MSE + Softmax approaches 0 when predicting confidence—gradient vanishing, unable to learn.
Real-life example
**Cipherbook design
You write a letter using a set of codes (short codes represent common characters, long codes represent rare characters).
But if your password is designed based on English frequency, and you write it in Chinese—the encoding efficiency is low.
The extra bits wasted when encoding data with true distribution p using an incorrect distribution q = KL divergence.
Python hands-on practice
Example
import
numpy
as
np
def
cross_entropy
(
p
,
q
)
:
return
-np.
sum
(
p * np.
log
(
q +
1e-10
)
)
p_true
=
np.
array
(
[
1.0
,
0.0
,
0.0
]
)
Real: Category 0
for
q
,
desc
in
[
(
[
0.9
,
0.05
,
0.05
]
,
"Good prediction"
)
,
(
[
0.4
,
0.3
,
0.3
]
,
"blurry"
)
,
(
[
0.1
,
0.8
,
0.1
]
,
"Error"
)
]
:
(
f
"{desc}: Cross-entropy={cross_entropy(p_true, q):.4f}"
)
Compare the gradients of CE and MSE
(
"\nPrediction is very poor (y_pred=0.01, true=1): CE gradient=-100, MSE gradient=-1.98"
)
(
"CE gives a large gradient when the prediction is wrong -> learns fast"
)
Running output:
Original prompt (Chinese, left untranslated)
好预测: 交叉熵=0.1054
模糊: 交叉熵=0.9163
错误: 交叉熵=2.3026
预测很差(y_pred=0.01, 真=1): CE梯度=-100, MSE梯度=-1.98
CE在预测错误时给出大梯度 → 学得快
Cross-Entropy vs MSE Gradient Comparison
Application Scenarios in AI
Standard for Classification Tasks: Cross-Entropy Loss
PyTorch's nn.CrossEntropyLoss and TensorFlow's categorical_crossentropy are the default loss functions for classification tasks. Internally, they integrate Softmax + Negative Log Likelihood—a single loss function that performs both activation and loss calculation, resulting in a very simple gradient form: ( \nabla = \hat{y} - y ).
Why Not Use MSE for Classification? Gradient Characteristics Determine Efficiency
When the model predicts incorrectly (e.g., the true class probability should be close to 1 but is predicted as 0.01), the cross-entropy gradient is approximately -100—providing a very strong correction signal. In the same situation, the MSE gradient is only -1.98—making it almost impossible to learn. This explains why MSE converges very slowly or not at all in classification tasks.
KL Divergence in Knowledge Distillation
Knowledge Distillation: Training a small model (student) using the Softmax output of a large model (teacher) as soft labels. The student must not only match the true labels but also minimize the gap between its output distribution and the teacher's distribution via KL divergence. Soft labels contain similarity information between classes (e.g., the output probabilities for "cat" and "tiger" are higher than for "car"), which is implicit knowledge that one-hot labels lack.
KL divergence regularization term of VAE
The loss function of VAE = reconstruction error + KL(N(μ,σ²) || N(0,I)). The KL term constrains the latent distribution output by the encoder not to deviate too far from the standard normal distribution for each sample—this acts as a regularizer, ensuring the latent space is continuous and smooth, allowing samples from different classes to transition smoothly in the latent space.
KL constraint in RLHF
When models like ChatGPT are fine-tuned using RLHF (Reinforcement Learning from Human Feedback), a KL divergence constraint is added to the optimization objective: do not let the current policy deviate too far from the initial SFT model. This prevents the model from outputting strange text just to please the reward model, thus maintaining generation quality.