# 交叉熵

交叉熵是信息论中的一个量，用于衡量当编码方案针对某一分布 q 设计、而实际结果却来自真实分布 p 时，平均需要多少个信息单位（奈特或比特）来编码这些结果。在机器学习中，同一个量取负值并在数据上取平均，就成为概率分类器和语言模型的标准训练损失，通常称为交叉熵损失或对数损失。

| 关键事实 | 详情 |
|---|---|
| 定义 | 对于同一结果集上的分布 p 和 q，\( H(p, q) = -\sum_{x} p(x) \log q(x) \)<sup>[1](https://www.cl.cam.ac.uk/teaching/2021/InfoTheory/InfoTheoryNotes2020.pdf)</sup> |
| 分解 | \( \mathrm{CE}(p, q) = H(p) + D_{\mathrm{KL}}(p \| q) \)，即 p 的熵加上库尔巴克-莱布勒散度<sup>[2](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html)</sup> |
| 最小值 | 交叉熵是非对称的（\( H(p,q) \neq H(q,p) \)），当 \( p = q \) 时取最小值，此时等于 p 的熵<sup>[1](https://www.cl.cam.ac.uk/teaching/2021/InfoTheory/InfoTheoryNotes2020.pdf)</sup> |
| 单位 | 使用自然对数时为奈特，使用以 2 为底的对数时为比特；底的选择决定单位<sup>[2](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html)</sup> |
| 统计学角色 | 对数损失（交叉熵）是一种严格适当评分规则：其期望值仅在预测真实概率时取最小<sup>[3](https://springerlink.fh-diploma.de/article/10.1007/s10994-023-06336-7)</sup> |
| 机器学习用法 | 神经网络分类器的标准训练损失；PyTorch 的 `CrossEntropyLoss` 将 LogSoftmax 和 NLLLoss 合并在一个模块中<sup>[4](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)</sup> |
| 失效模式 | 若某个样本的真实类别被赋予概率零，损失将变为无穷大，因此实现中会对预测概率进行截断<sup>[3](https://springerlink.fh-diploma.de/article/10.1007/s10994-023-06336-7)</sup><sup> • </sup><sup>[5](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html)</sup> |

## 定义与信息论含义

对于同一结果集上的两个概率分布 p(x) 和 q(x)，交叉熵定义为

\[ H(p, q) = -\sum_{x} p(x) \log q(x). \]

它类似于 q 的熵 \( H(q) \)，区别在于期望——即概率加权——是对 p 而非 q 取的<sup>[1](https://www.cl.cam.ac.uk/teaching/2021/InfoTheory/InfoTheoryNotes2020.pdf)</sup>。编码解释非常直接：如果一个编码方案是在假设结果服从 q 的前提下设计的，那么 \( H(p, q) \) 预测的是当结果实际服从 p 时所产生的平均码字长度。这就是错误地假设数据由 q 描述所付出的代价<sup>[1](https://www.cl.cam.ac.uk/teaching/2021/InfoTheory/InfoTheoryNotes2020.pdf)</sup>。SciPy 的文档将同一量表述为 \( \mathrm{CE}(p, q) = -\sum p_k \log q_k \)，即当编码针对 q 优化而真实分布为 p 时，每个符号平均所需的信息单位数<sup>[2](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html)</sup>。

**与熵和 KL 散度的关系。** 交叉熵可以精确分解为

\[ \mathrm{CE}(p, q) = H(p) + D_{\mathrm{KL}}(p \| q), \]

其中 \( D_{\mathrm{KL}}(p \| q) = \sum_{x} p(x) \log \frac{p(x)}{q(x)} \) 是库尔巴克-莱布勒散度，即使用针对 q 优化的编码时多出的码长<sup>[2](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html)</sup><sup> • </sup><sup>[1](https://www.cl.cam.ac.uk/teaching/2021/InfoTheory/InfoTheoryNotes2020.pdf)</sup>。由于对于给定的数据分布，\( H(p) \) 是固定的，因此在模型上最小化交叉熵等价于最小化到真实分布的 KL 散度。该量非负，且仅当模型对每个观测标签都赋予概率 1 时才等于零；在二分类情形下，\( H(y, p) = 0 \) 意味着 \( y_i = 1 \) 蕴含 \( p_i = 1 \)，\( y_i = 0 \) 蕴含 \( p_i = 0 \)，并约定 \( 0 \log 0 = 0 \)<sup>[6](https://indico.cern.ch/event/1326749/sessions/510447/attachments/2714821/5051285/jettsml_lectures.pdf)</sup>。

## 作为损失函数的交叉熵

在统计学和机器学习中，交叉熵以负对数似然的形式出现。对于二值标签 \( y \in \{0,1\} \) 和预测概率 \( p = \Pr(y = 1) \)，对数损失为

\[ L_{\log}(y, p) = -\bigl( y \log p + (1 - y) \log(1 - p) \bigr), \]

这是逻辑回归及其扩展（如神经网络）中使用的损失函数<sup>[5](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html)</sup>。最小化交叉熵等价于最大化似然，这是目标函数的一般特征，称为最大似然原理<sup>[6](https://indico.cern.ch/event/1326749/sessions/510447/attachments/2714821/5051285/jettsml_lectures.pdf)</sup>。

对于有 K 个类别的多分类问题，将真实标签写为独热向量 \( \dot{\mathbf{y}} \)，模型概率向量写为 \( \mathbf{s} \)，则对数损失为 \( \phi_{\mathrm{LL}}(\mathbf{s}, \dot{\mathbf{y}}) = -\sum_{j=1}^{K} y_j \log s_j \)<sup>[3](https://springerlink.fh-diploma.de/article/10.1007/s10994-023-06336-7)</sup>。在单个样本层面，它仅取决于赋予真实类别的概率，但其适当性是在总体期望意义上成立的：若真实类别分布为 [0.8, 0.2, 0.0]，则期望对数损失 \( -(0.8 \log s_1 + 0.2 \log s_2) \) 仅在预测为 [0.8, 0.2, 0.0] 时取最小<sup>[3](https://springerlink.fh-diploma.de/article/10.1007/s10994-023-06336-7)</sup>。

**适当性。** 若预测者通过给出真实分布来最大化期望得分，则该评分规则是适当的；若该最大值唯一，则称为严格适当<sup>[7](https://sites.stat.washington.edu/people/raftery/Research/PDF/Gneiting2007jasa.pdf)</sup>。对数损失和布里尔分数都是严格适当的<sup>[3](https://springerlink.fh-diploma.de/article/10.1007/s10994-023-06336-7)</sup>。这一性质正是当校准概率很重要时交叉熵被优先用作训练损失的原因：使用适当评分规则训练会在训练过程中鼓励概率的细化和校准，而非适当损失则不会<sup>[3](https://springerlink.fh-diploma.de/article/10.1007/s10994-023-06336-7)</sup>。对数评分作为严格适当评分规则的地位至少可以追溯到古德（Good）（1952）<sup>[8](https://doi.org/10.1146%2Fannurev-statistics-042424-050626)</sup>。

## 框架中的实现

**PyTorch。** `torch.nn.CrossEntropyLoss` 的文档说明其适用于训练 C 类分类问题，它将 `LogSoftmax` 和 `NLLLoss` 合并在一个模块中，因此期望输入原始 logits 而非概率<sup>[4](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)</sup>。其构造函数接受逐类的 `weight` 张量用于重新缩放、`ignore_index`（默认 −100）用于指定要忽略的目标值，以及 `label_smoothing` 参数（默认 0.0）<sup>[4](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)</sup>。由于该模块内部应用了 log-softmax，传入已经过 softmax 的输出会对分布进行双重压缩并扭曲损失。

**scikit-learn。** `sklearn.metrics.log_loss` 被描述为对数损失，又称逻辑损失或交叉熵损失，它计算模型预测概率的负对数似然，使用自然对数；预测概率会被截断到 \( [\varepsilon, 1-\varepsilon] \)，其中 \( \varepsilon \) 是该数据类型的机器精度，以防止真实类别概率为零时产生无穷大损失<sup>[5](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html)</sup>。在梯度提升树中，`log_loss` 选项在二分类问题中也称为二项偏差或二元交叉熵，在多分类问题中称为多项式偏差或分类交叉熵<sup>[9](https://scikit-learn.org/stable/auto_examples/model_selection/plot_cost_sensitive_learning.html)</sup>。

**SciPy。** `scipy.stats.entropy` 直接计算香农熵和 KL 散度，并将交叉熵作为二者之和获得，\( \mathrm{CE} = H(p) + D(p \| q) \)；base 参数选择奈特（以 e 为底）或比特（以 2 为底）<sup>[2](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html)</sup>。

## 解释与用途

**编码与模型评估。** 编码视角直接联系到模型评估：如果一个模型在训练集上构建，而测试集具有不同的统计特性，交叉熵评估的是所学模型对该不同测试数据的预测准确程度<sup>[1](https://www.cl.cam.ac.uk/teaching/2021/InfoTheory/InfoTheoryNotes2020.pdf)</sup>。在语言建模中，以每词元比特数表示的交叉熵是标准评估量，困惑度是其指数：十亿词基准报告了一个未剪枝的 Kneser–Ney 五元语法基线模型困惑度为 67.6，并将困惑度降低 35% 描述为交叉熵（比特）降低 10%<sup>[10](https://arxiv.org/abs/1312.3005)</sup>。

**分解为校准与细化。** 诸如对数损失之类的适当评分规则可分解为校准损失——预测与观测事件频率之间的拟合程度——和细化损失——因对不同类别的样本赋予相同概率而产生的损失<sup>[3](https://springerlink.fh-diploma.de/article/10.1007/s10994-023-06336-7)</sup>。因此，低交叉熵同时反映了区分能力和校准，这对训练而言是优点，但也使这个单一数字本身难以解读；临床模型综述指出，对数损失混合了区分度和校准，作为整体指标信息量不大<sup>[11](https://doi.org/10.1016/j.landig.2026.101001)</sup>。

**交叉熵方法。** 另一条独立的研究路线由鲁宾斯坦（Rubinstein）于 1999 年和 2001 年提出，使用交叉熵（KL 散度）作为采样分布之间接近程度的度量。交叉熵方法是一种通用的蒙特卡洛技术，用于稀有事件估计——被视为自适应重要性采样——以及用于优化，其中优化问题被转化为稀有事件估计问题<sup>[12](https://doi.org/10.1002/9781118014967.ch13)</sup>。

**历史渊源。** 交叉熵背后的熵概念来自克劳德·香农（Claude Shannon）1948 年的论文《通信的数学理论》，发表于《贝尔系统技术杂志》第 27 卷，第 379–423 页<sup>[13](https://apice.unibo.it/bin/view/Publication/Shannon1948I?language=en&mode=bibtex)</sup>。交叉熵最小化本身最早由库尔巴克（Kullback）引入，他称之为最小定向散度和最小判别信息<sup>[14](https://bayes.wustl.edu/Manual/CrossEntropyMinimization.pdf)</sup>。

## 变体与实践限定

**加权与平滑形式。** 类别加权重新缩放各类别的贡献以对抗不平衡；PyTorch 通过 `weight` 参数提供此功能<sup>[4](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)</sup>。标签平滑作为 `label_smoothing` 参数提供，用于柔化独热目标。研究变体针对特定问题修改目标函数：由梯度不平衡分析引导的焦点式指数交叉熵损失在 CelebA 上将难学类别的召回率提高了 +1.95%<sup>[15](https://www.sciencedirect.com/science/article/pii/S0925231226010350)</sup>，而 TF-IDF 加权的词元级交叉熵在 LoRA 微调下、跨五个参数规模从 11 亿到 130 亿的仅解码器语言模型，将平均记忆子串长度减少了 14%<sup>[16](https://arxiv.org/abs/2609.11029)</sup>。

**低交叉熵能保证什么、不能保证什么。** 由于对数损失是严格适当的，其最小化会驱动预测概率趋近真实条件分布。但这并不意味着交叉熵更低的模型具有更高的分类准确率，也不意味着低交叉熵在所有方面都能证明概率可信；准确率、适当评分和校准误差是不同家族的评估指标，可能彼此不一致，且存在它们对模型给出不同排序的反例<sup>[17](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=7082155)</sup>。此外，在训练前通过重采样纠正类别不平衡可能损害校准：在逻辑回归模拟和一项卵巢癌案例研究中，所有测试的不平衡纠正方法都导致对少数类概率的严重高估，而未能改善区分度<sup>[18](https://arxiv.org/abs/2202.09101)</sup>。

## References

1. [Information Theory lecture notes, University of Cambridge](https://www.cl.cam.ac.uk/teaching/2021/InfoTheory/InfoTheoryNotes2020.pdf)
2. [scipy.stats.entropy, SciPy v1.18.0 Manual](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html)
3. [Classifier calibration: a survey on how to assess and improve predicted class probabilities, Machine Learning (Springer)](https://springerlink.fh-diploma.de/article/10.1007/s10994-023-06336-7)
4. [torch.nn.CrossEntropyLoss, PyTorch 2.14 documentation](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)
5. [sklearn.metrics.log_loss, scikit-learn 1.9.1 documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html)
6. [Jet tagging machine learning lectures, CERN Indico](https://indico.cern.ch/event/1326749/sessions/510447/attachments/2714821/5051285/jettsml_lectures.pdf)
7. [Gneiting, T. and Raftery, A. E. (2007). Strictly Proper Scoring Rules, Prediction, and Estimation. Journal of the American Statistical Association 102(477)](https://sites.stat.washington.edu/people/raftery/Research/PDF/Gneiting2007jasa.pdf)
8. [Proper Scoring Rules for Estimation and Forecast Evaluation, Annual Review of Statistics](https://doi.org/10.1146%2Fannurev-statistics-042424-050626)
9. [Post-tuning the decision threshold for cost-sensitive learning, scikit-learn examples](https://scikit-learn.org/stable/auto_examples/model_selection/plot_cost_sensitive_learning.html)
10. [Chelba, C. et al. One Billion Word Benchmark for Measuring Progress in Statistical Language Modeling, arXiv:1312.3005](https://arxiv.org/abs/1312.3005)
11. [Critical appraisal of fairness metrics for AI-based clinical prediction models, The Lancet Digital Health](https://doi.org/10.1016/j.landig.2026.101001)
12. [Kroese, D. P., Taimre, T., Botev, Z. I. (2011). Cross-Entropy Method, Wiley Series in Probability and Statistics](https://doi.org/10.1002/9781118014967.ch13)
13. [Shannon, C. E. (1948). A Mathematical Theory of Communication, Bell System Technical Journal 27(3): 379–423](https://apice.unibo.it/bin/view/Publication/Shannon1948I?language=en&mode=bibtex)
14. [Cross-entropy minimization, IEEE Transactions on Information Theory](https://bayes.wustl.edu/Manual/CrossEntropyMinimization.pdf)
15. [Loss Function Assessment: Towards learning hard-to-learn classes, Neurocomputing (ScienceDirect)](https://www.sciencedirect.com/science/article/pii/S0925231226010350)
16. [Rebalancing Token Importance in Language Models with TF-IDF Weighted Cross-Entropy Loss, arXiv:2609.11029](https://arxiv.org/abs/2609.11029)
17. [Minimal counterexamples separating accuracy, proper scoring rules, and calibration error in probabilistic classification, SSRN](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=7082155)
18. [The harm of class imbalance corrections for risk prediction models, arXiv:2202.09101](https://arxiv.org/abs/2202.09101)

---
*Initially written Oct 15, 2026*

Topic: 物质世界与数学 › 数学与统计学 › 统计学与概率论 › Probability theory › Convergence of measures and limit theorems › Probability metrics and distances between measures

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/cross-entropy

English original: https://www.edgepedia.org/cross-entropy
