Manual calculation of cross-entropy loss
Manual calculation of cross-entropy loss
Construct a prediction sequence from "random guess" to "very confident" and observe how the cross-entropy value decreases.
After learning this case study, you will understand: why cross-entropy is used instead of MSE for classification tasks—it punishes confident but incorrect predictions more "severely" than MSE.
Real-life introduction
**Exam grading—getting it wrong is worse than not answering
Two students' performance on a multiple-choice question (the answer is A): Xiao Hong predicts A with a probability of 0.5 (uncertain but in the right direction), while Xiao Ming predicts C with a probability of 0.95 (very confidently wrong). Although Xiao Hong is uncertain, she is in the right direction, but Xiao Ming is not only wrong but also very confident—this kind of error is more unforgivable.
Cross-entropy loss is like this scoring standard: reward confidence when predicting correctly, and penalize confidence when predicting incorrectly.
Intuitive understanding
The true label is "cat" (one-hot = [1, 0, 0]). The model's output simulating from "random guessing" to "becoming increasingly accurate" is:
- Completely random guess [0.33, 0.33, 0.34] → Loss 1.10
- Very confident and correct [0.98, 0.01, 0.01] → Loss 0.02
- Very confident but incorrect [0.02, 0.9, 0.08] → Loss 3.91 (nearly 4 times higher than random guessing!)
The last value is worth noting: because -log(0.02) ≈ 3.91, while -log(0.33) ≈ 1.10.
Mathematical definition
[ H(p, q) = -\sum_{i=1}^{C} p_i \cdot \log(q_i) ]
(p) is the true distribution (one-hot), and (q) is the predicted distribution. For a "confident but wrong" prediction, Cross-Entropy = -log(0.02) ≈ 3.91, MSE = (1-0.02)^2 ≈ 0.96. The penalty of Cross-Entropy is 12 times that of MSE.
Python Hands-on Practice
Example
import
numpy
as
np
def
cross_entropy
(
p_true
,
q_pred
,
eps
=
1e-12
)
:
q_pred
=
np.
clip
(
q_pred
,
eps
,
1
- eps
)
return
-np.
sum
(
p_true * np.
log
(
q_pred
)
)
True label: cat (class 0)
p_true
=
np.
array
(
[
1
,
0
,
0
]
)
[cat, dog, bird]
predictions
=
{
"completely random (uniform)"
np.
array
(
[
0.33
,
0.33
,
0.34
]
)
,
"A bit of a feeling"
: np.
array
(
[
0.5
,
0.3
,
0.2
]
)
,
"gradually reliable"
: np.
array
(
[
0.7
,
0.2
,
0.1
]
)
,
"well-trained"
: np.
array
(
[
0.9
,
0.07
,
0.03
]
)
,
"Very confident and correct"
: np.
array
(
[
0.98
,
0.01
,
0.01
]
)
,
"Very confident but wrong!"
: np.
array
(
[
0.02
,
0.9
,
0.08
]
)
,
}
(
"RUNOOB cross-entropy loss comparison (true: cat=[1,0,0])\n"
)
(
f
"{'Prediction Description':<20} {'Loss':<10} {'Analysis'}"
)
(
"-"
52
)
for
name
,
q
in
predictions.
items
(
)
:
loss
=
cross_entropy
(
p_true
,
q
)
if
loss
2
: analysis
=
"Severe error!"
elif
loss
0.5
: analysis
=
"Direction is correct but uncertain"
else
: analysis
=
"Very good"
(
f
"{name:<20} {loss:<10.4f} {analysis}"
)
MSE vs Cross-Entropy Comparison
q_bad
=
predictions
[
"Very confident but wrong!"
]
mse_bad
=
np.
mean
(
(
p_true - q_bad
)
**
2
)
ce_bad
=
cross_entropy
(
p_true
,
q_bad
)
(
f
"\nRUNOOB confident but wrong: MSE={mse_bad:.4f}, CrossEntropy={ce_bad:.4f} (Severe {ce_bad/mse_bad:.0f}x)"
)
Original prompt (Chinese, left untranslated)
RUNOOB 交叉熵损失对比 (真实: 猫=[1,0,0])
预测描述 损失 分析
----------------------------------------------------
完全瞎猜 (均匀) 1.0986 方向对但不确定
有点感觉 0.6931 方向对但不确定
逐渐靠谱 0.3567 很好
训练较好 0.1054 很好
非常自信且正确 0.0202 很好
非常自信但错误! 3.9120 严重错误!
RUNOOB 自信但错误时: MSE=0.3260, 交叉熵=3.9120 (严厉 12x)
Application scenarios in AI
| Scenario | Loss function used |
|---|---|
| Image classification | CategoricalCrossEntropy |
| Language model | The sum of cross-entropy at each token position—the objective function for GPT training |
| Knowledge distillation | Cross-entropy using soft labels from the teacher model |