{
  "id": "probability-information",
  "module": "math-ml",
  "level": 2,
  "minutes": 35,
  "audiences": [
    "beginner",
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "Probability, Statistics and Information Theory: Bayes, Maximum Likelihood, Cross-Entropy and KL Divergence",
      "description": "Probability, statistics and information theory for machine learning: random variables and distributions, expectation and variance, conditional probability and Bayes' rule, maximum likelihood estimation, entropy, cross-entropy and KL divergence, and their concrete use in classification losses, softmax temperature, knowledge distillation, EM and VAEs. Based on original papers and official documentation, with runnable NumPy and PyTorch examples.",
      "updated": "2026-11-11",
      "takeaways": [
        "A probabilistic model assigns each possible outcome a non-negative number, and the numbers sum to 1. At every step a language model outputs such a discrete distribution over its whole vocabulary, and generating text means sampling from it repeatedly.",
        "Bayes' rule P(A|B) = P(B|A)·P(A) / P(B) combines a prior with evidence into a posterior. When the base rate is low, a positive result can have a low posterior even for an accurate test: with 1% prevalence, 99% sensitivity and a 5% false-positive rate, a positive result means disease only about 16.7% of the time.",
        "Maximum likelihood estimation picks the parameters under which the observed data are most probable. For a classifier, minimising cross-entropy loss is exactly minimising the negative log-likelihood of the training data.",
        "Entropy H(P) is the average number of bits needed to encode outcomes drawn from P (Shannon, 1948); cross-entropy H(P,Q) is the average when the code is designed for Q instead; the difference is the KL divergence KL(P‖Q), which is never negative, is zero only when P = Q, and is not symmetric.",
        "Softmax temperature divides the logits by T before normalising: T > 1 flattens the distribution and raises its entropy, T < 1 sharpens it. Knowledge distillation uses high-temperature soft targets, calibration uses temperature scaling, and text generation uses temperature to control randomness."
      ],
      "faq": [
        {
          "q": "How much probability and statistics do I need for deep learning?",
          "a": "The parts used most when reading papers and tuning models are discrete and continuous distributions, expectation and variance, conditional probability and Bayes' rule, independence, maximum likelihood, entropy, cross-entropy and KL divergence. Measure theory and stochastic processes rarely come up directly in applied LLM work. Chapter 6 of Mathematics for Machine Learning and the probability and information theory sections of D2L cover everything listed."
        },
        {
          "q": "How is cross-entropy loss related to maximum likelihood?",
          "a": "For i.i.d. training examples the likelihood is the product of the probabilities assigned to the correct labels; taking the negative log turns it into a sum of −log q(y). Classification cross-entropy writes the true label as a one-hot distribution P, so H(P,Q) = −log q(y). Minimising the average cross-entropy is therefore the same as maximising the log-likelihood."
        },
        {
          "q": "Why is KL divergence asymmetric, and does the direction matter?",
          "a": "KL(P‖Q) = Σ P(x)·log(P(x)/Q(x)) is weighted by P, so outcomes that P considers likely but Q almost rules out are penalised heavily; the reverse direction is weighted by Q. In this lesson's example KL(P‖Q) = 0.3219 bits and KL(Q‖P) = 0.2781 bits. Maximum-likelihood training corresponds to minimising KL(data‖model), whereas variational inference such as the VAE typically works with KL(approximate posterior‖true posterior), and the two directions lead to different fitting behaviour."
        },
        {
          "q": "Why does PyTorch's CrossEntropyLoss take logits rather than probabilities?",
          "a": "The PyTorch documentation states that the input to CrossEntropyLoss should be the unnormalised logits for each class; the function applies log-softmax and the negative log-likelihood internally, which is numerically more stable. A related pitfall is KLDivLoss: its input must be log-probabilities, and the default reduction='mean' does not return the mathematical KL divergence, so the documentation recommends reduction='batchmean'."
        },
        {
          "q": "Why does a higher temperature make generation more random?",
          "a": "Dividing the logits by T > 1 shrinks the gaps between classes, so the softmax output is flatter, its entropy is higher and low-probability tokens are sampled more often; as T approaches 0 sampling approaches always picking the most likely token (greedy decoding). Holtzman et al. (2019) showed that decoding to maximise likelihood tends to produce bland, repetitive text, which is why practical generation usually combines temperature with top-p (nucleus) sampling."
        }
      ],
      "sources": [
        {
          "title": "Deisenroth, Faisal, Ong: Mathematics for Machine Learning (free official edition, Chapter 6 Probability and Distributions)",
          "url": "https://mml-book.github.io/"
        },
        {
          "title": "Dive into Deep Learning: 2.6 Probability and Statistics",
          "url": "https://d2l.ai/chapter_preliminaries/probability.html"
        },
        {
          "title": "Dive into Deep Learning: 22.11 Information Theory",
          "url": "https://d2l.ai/chapter_mdl-information-theory/mdl-information-theory.html"
        },
        {
          "title": "Dive into Deep Learning: 22.7 Maximum Likelihood",
          "url": "https://d2l.ai/chapter_mdl-probability-statistics/mdl-maximum-likelihood.html"
        },
        {
          "title": "Dive into Deep Learning: 4.1 Softmax Regression",
          "url": "https://d2l.ai/chapter_linear-classification/softmax-regression.html"
        },
        {
          "title": "MacKay: Information Theory, Inference, and Learning Algorithms (free full text from the author)",
          "url": "https://www.inference.org.uk/mackay/itila/"
        },
        {
          "title": "Brown University: Seeing Theory (interactive probability and statistics)",
          "url": "https://seeing-theory.brown.edu/"
        },
        {
          "title": "PyTorch documentation: torch.nn.CrossEntropyLoss",
          "url": "https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html"
        },
        {
          "title": "PyTorch documentation: torch.nn.KLDivLoss",
          "url": "https://docs.pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html"
        },
        {
          "title": "SciPy documentation: Statistical functions (scipy.stats)",
          "url": "https://docs.scipy.org/doc/scipy/reference/stats.html"
        },
        {
          "title": "Shannon (1948), A Mathematical Theory of Communication, Bell System Technical Journal",
          "url": "https://doi.org/10.1002/j.1538-7305.1948.tb01338.x"
        },
        {
          "title": "Kullback and Leibler (1951), On Information and Sufficiency, Annals of Mathematical Statistics",
          "url": "https://projecteuclid.org/euclid.aoms/1177729694"
        },
        {
          "title": "Dempster, Laird and Rubin (1977), Maximum Likelihood from Incomplete Data via the EM Algorithm",
          "url": "https://doi.org/10.1111/j.2517-6161.1977.tb01600.x"
        },
        {
          "title": "Kingma and Welling (2013), Auto-Encoding Variational Bayes",
          "url": "https://arxiv.org/abs/1312.6114"
        },
        {
          "title": "Hinton, Vinyals and Dean (2015), Distilling the Knowledge in a Neural Network",
          "url": "https://arxiv.org/abs/1503.02531"
        },
        {
          "title": "Guo et al. (2017), On Calibration of Modern Neural Networks",
          "url": "https://arxiv.org/abs/1706.04599"
        },
        {
          "title": "Holtzman et al. (2019), The Curious Case of Neural Text Degeneration",
          "url": "https://arxiv.org/abs/1904.09751"
        }
      ],
      "url": "https://aimap.page/en/learn/math-ml/probability-information/",
      "markdown": "**Summary**: At every step a language model outputs a probability distribution; the loss used to train it comes from maximum likelihood; and the gap between two distributions is measured with cross-entropy and KL divergence. This lesson moves from distributions and expectation to conditional probability and Bayes' rule, maximum likelihood, entropy, cross-entropy and KL, and finally softmax and temperature, tying each section to a concrete step in training or generating with large models.\n\nThis lesson belongs to the [Probability, Statistics & Information Theory](/learn/unit/u13-probability) unit. The prerequisite is [Python and NumPy setup](/learn/python-numpy-setup), and [Linear Algebra](/learn/linear-algebra) and [Calculus and Optimization](/learn/calculus-optimization) are recommended first. Continue with [Overfitting, Generalisation and Data Splits](/learn/generalization) and [How LLMs Learn](/learn/how-llms-learn). Related algorithm cards: [logistic regression](/learn/algorithms/logistic-regression), [naive Bayes](/learn/algorithms/naive-bayes), [EM](/learn/algorithms/em), [VAE](/learn/algorithms/vae), [sampling](/learn/algorithms/sampling) and [knowledge distillation](/learn/algorithms/knowledge-distillation).\n\n## Random variables, distributions and expectation\n\nA random variable is a quantity whose outcome is uncertain but whose outcomes each have a definite probability. Two kinds of distribution appear constantly in machine learning:\n\n- **Discrete distributions** have outcomes you can list: a coin flip (Bernoulli), a die roll, or the probability a language model assigns to each token in its vocabulary (categorical). Each probability is non-negative and they sum to 1.\n- **Continuous distributions** take real values and are described by a density, for example the Gaussian (normal) distribution N(μ, σ²). Weight initialisation, the noise added in diffusion models and the latent variables of a VAE all use Gaussians.\n\nThe two summary numbers used most:\n\n```text\nExpectation  E[X]   = Σ x · P(X = x)            (replace the sum with an integral for continuous X)\nVariance     Var[X] = E[(X − E[X])²] = E[X²] − (E[X])²\n```\n\nExpectation is the long-run average and variance measures spread. The average loss reported during training is a sample estimate of the expected loss over the data distribution, and a minibatch stochastic gradient is an unbiased estimate of the full gradient whose variance falls as the batch grows.\n\nTwo random variables are **independent** when their joint probability is the product of the individual ones: P(A, B) = P(A)·P(B). Assuming the training set is independent and identically distributed (i.i.d.) underlies most generalisation analysis; the next lesson, [Overfitting, Generalisation and Data Splits](/learn/generalization), looks at what happens when that assumption breaks.\n\n## Conditional probability and Bayes' rule\n\nThe conditional probability P(A|B) is the probability of A given that B happened, defined as P(A, B) / P(B). Expanding the joint probability in both directions gives Bayes' rule:\n\n```text\nP(A|B) = P(B|A) · P(A) / P(B)\nposterior = likelihood × prior / evidence\n```\n\nA classic example shows why the base rate matters. A disease has 1% prevalence, the test has 99% sensitivity (probability of a positive result for someone who has the disease) and a 5% false-positive rate.\n\n```text\nP(positive) = 0.99 × 0.01 + 0.05 × 0.99 = 0.0594\nP(disease | positive) = 0.99 × 0.01 / 0.0594 ≈ 0.1667\n```\n\nEven with a fairly accurate test, a positive result means disease only about 16.7% of the time, because healthy people are so numerous that false positives outnumber true positives. The same reasoning applies to spam filtering, anomaly detection and other tasks with rare positives, and it is the basis of the [naive Bayes](/learn/algorithms/naive-bayes) classifier.\n\n## Maximum likelihood estimation\n\nGiven observed data D and a model with parameters θ, the **likelihood** L(θ) = P(D | θ) holds the data fixed and treats the parameters as the variable. Maximum likelihood estimation (MLE) picks the θ that maximises L(θ). With independent samples the likelihood is a product, so in practice we take logs to get a sum and negate it to get a minimisation:\n\n```text\nθ* = argmax Π P(xᵢ | θ) = argmin −Σ log P(xᵢ | θ)\n```\n\nTake coin flips: with k heads in n flips the Bernoulli negative log-likelihood is −[k·log p + (n−k)·log(1−p)]; setting the derivative with respect to p to zero gives p* = k/n, the sample frequency. The example below simulates 1,000 flips with true p = 0.7: the sample frequency is 0.678, and on a grid from 0.01 to 0.99 the negative log-likelihood is lowest at exactly 0.68.\n\nMaximum likelihood is everywhere in machine learning. Under Gaussian noise, the maximum-likelihood solution of [linear regression](/learn/algorithms/linear-regression) is least squares; [logistic regression](/learn/algorithms/logistic-regression) and neural-network classifiers are trained on the log-likelihood; and LLM pre-training maximises the log-likelihood of the next token. When the data involve unobserved latent variables, the [EM algorithm](/learn/algorithms/em) of Dempster, Laird and Rubin (1977) finds a maximum-likelihood solution by alternating between estimating the distribution of the latent variables (E-step) and maximising the expected log-likelihood (M-step); Gaussian mixture models are the textbook application.\n\nMaximum likelihood looks only at the data. **Maximum a posteriori** (MAP) estimation also multiplies in a prior P(θ). With a zero-mean Gaussian prior, the negative log adds a term proportional to ‖θ‖², which is exactly L2 regularisation. The next lesson returns to regularisation from the generalisation side.\n\n## Entropy, cross-entropy and KL divergence\n\nIn \"A Mathematical Theory of Communication\" (1948), Shannon used entropy to measure the uncertainty of a distribution. With base-2 logs the unit is bits; with natural logs it is nats, which is what PyTorch losses use by default:\n\n```text\nEntropy        H(P)     = −Σ P(x) · log P(x)\nCross-entropy  H(P, Q)  = −Σ P(x) · log Q(x)\nKL divergence  KL(P‖Q)  =  Σ P(x) · log (P(x) / Q(x)) = H(P, Q) − H(P)\n```\n\nIntuitively, H(P) is the average number of bits per symbol under the best code designed for the true distribution P. If the code is designed for Q instead, the average is H(P, Q) bits, and the extra cost is KL(P‖Q). The divergence introduced by Kullback and Leibler (1951) has three properties worth remembering:\n\n1. **Non-negative**: KL(P‖Q) ≥ 0, with equality if and only if P = Q (Gibbs' inequality). The example below computes KL for 10,000 random pairs of distributions; the minimum is 0.0027 and none is negative.\n2. **Asymmetric**: in general KL(P‖Q) ≠ KL(Q‖P), so it is not a distance. With P = (0.5, 0.25, 0.25) and Q = (0.8, 0.1, 0.1), KL(P‖Q) = 0.3219 bits and KL(Q‖P) = 0.2781 bits.\n3. **Tied to cross-entropy**: when the true distribution P is fixed, H(P) is a constant, so minimising H(P, Q) is equivalent to minimising KL(P‖Q).\n\nThis is why classifiers use cross-entropy as their loss. Writing the true label as a one-hot distribution P (probability 1 on the correct class), cross-entropy reduces to −log Q(y), the negative log-likelihood of the correct class. Minimising cross-entropy, minimising KL(data‖model) and maximum likelihood are three names for the same objective here.\n\nKL divergence also appears directly in large models:\n\n| Setting | Role of KL | Further reading |\n|---|---|---|\n| VAE | The training objective (evidence lower bound) is a reconstruction term minus KL(approximate posterior‖prior), Kingma and Welling (2013) | [VAE card](/learn/algorithms/vae) |\n| Knowledge distillation | The student fits the teacher's high-temperature soft-target distribution, Hinton et al. (2015) | [Knowledge distillation card](/learn/algorithms/knowledge-distillation) |\n| RLHF and preference optimisation | A KL penalty to a reference model keeps the policy from drifting too far | [RLHF card](/learn/algorithms/rlhf), [DPO card](/learn/algorithms/dpo) |\n\n## Softmax, temperature and sampling\n\nThe last layer of a neural network outputs arbitrary real numbers called logits. Softmax turns them into a distribution:\n\n```text\nsoftmax(z)ᵢ = exp(zᵢ / T) / Σⱼ exp(zⱼ / T)        (T is the temperature, T = 1 by default)\n```\n\nImplementations subtract the maximum before exponentiating to avoid overflow; this does not change the result. In the example below, with logits (2.0, 1.0, 0.1) and class 0 correct, softmax gives (0.659, 0.242, 0.099) and the cross-entropy loss is −log 0.659 = 0.4170 nats, matching PyTorch's `F.cross_entropy`.\n\nTemperature changes how peaked the distribution is:\n\n| Temperature | Distribution | Entropy (bits) |\n|---|---|---|\n| T = 0.5 | (0.864, 0.117, 0.019) | 0.655 |\n| T = 1.0 | (0.659, 0.242, 0.099) | 1.222 |\n| T = 2.0 | (0.502, 0.304, 0.194) | 1.481 |\n\nTemperature shows up in three places:\n\n- **Text generation**: the higher T is, the more often low-probability tokens are sampled and the more varied the output; lower T approaches greedy decoding. Holtzman et al. (2019) found that decoding for maximum likelihood produces bland, repetitive text and proposed nucleus (top-p) sampling, which samples only from the smallest set of tokens whose cumulative probability reaches p. See the [sampling card](/learn/algorithms/sampling).\n- **Knowledge distillation**: Hinton et al. (2015) raise the temperature to soften the teacher's outputs so the student also learns the relative sizes of the wrong classes.\n- **Calibration**: Guo et al. (2017) found modern neural networks are often overconfident, and that fitting a single temperature on a validation set (temperature scaling) is a simple, effective calibration method on most datasets.\n\n## Runnable examples\n\nThe code below was run on NumPy 2.5 and its output matches the numbers above.\n\n```python\nimport numpy as np\nrng = np.random.default_rng(0)\n\n# 1) Bayes' rule: 1% prevalence, 99% sensitivity, 5% false-positive rate\nprior, sens, fpr = 0.01, 0.99, 0.05\np_pos = sens * prior + fpr * (1 - prior)\nprint(f\"P(disease|positive) = {sens * prior / p_pos:.4f}\")\n\n# 2) Maximum likelihood: 1,000 coin flips with true p = 0.7\nflips = rng.random(1000) < 0.7\ngrid = np.linspace(0.01, 0.99, 99)\nnll = -(flips.sum() * np.log(grid) + (~flips).sum() * np.log(1 - grid))\nprint(f\"sample frequency {flips.mean():.3f}, grid p with lowest NLL = {grid[nll.argmin()]:.2f}\")\n\n# 3) Entropy, cross-entropy, KL\ndef H(p): return -(p * np.log2(p)).sum()\ndef CE(p, q): return -(p * np.log2(q)).sum()\ndef KL(p, q): return (p * np.log2(p / q)).sum()\nP = np.array([0.5, 0.25, 0.25]); Q = np.array([0.8, 0.1, 0.1])\nprint(f\"H(P)={H(P):.4f} bits  CE(P,Q)={CE(P,Q):.4f}  KL(P||Q)={KL(P,Q):.4f}  KL(Q||P)={KL(Q,P):.4f}\")\nprint(f\"CE - H = {CE(P,Q) - H(P):.4f} (equals KL(P||Q))\")\nks = [KL(a, b) for a, b in (rng.dirichlet(np.ones(5), 2) for _ in range(10000))]\nprint(f\"minimum KL over 10,000 random pairs = {min(ks):.6f} (>= 0)\")\n\n# 4) Cross-entropy loss = negative log-likelihood of the correct class\nlogits = np.array([2.0, 1.0, 0.1]); y = 0\np = np.exp(logits - logits.max()); p /= p.sum()\nprint(f\"softmax={np.round(p, 4)}  -log p[y]={-np.log(p[y]):.4f} nats\")\n\n# 5) Temperature: larger T gives a flatter, higher-entropy distribution\nfor T in (0.5, 1.0, 2.0):\n    q = np.exp(logits / T - (logits / T).max()); q /= q.sum()\n    print(f\"T={T}: p={np.round(q, 3)}  entropy={-(q * np.log2(q)).sum():.3f} bits\")\n```\n\nKey output: P(disease|positive) = 0.1667; sample frequency 0.678, lowest NLL at 0.68; H(P) = 1.5000 bits, CE(P,Q) = 1.8219, KL(P‖Q) = 0.3219, KL(Q‖P) = 0.2781, CE − H = 0.3219; minimum KL over random pairs 0.002657; softmax = (0.659, 0.2424, 0.0986) with loss 0.4170 nats.\n\nA PyTorch cross-check (run on PyTorch 2.15 CPU):\n\n```python\nimport torch, torch.nn.functional as F\nlogits = torch.tensor([[2.0, 1.0, 0.1]]); y = torch.tensor([0])\nprint(\"F.cross_entropy =\", round(F.cross_entropy(logits, y).item(), 4))      # 0.417\nP = torch.tensor([[0.5, 0.25, 0.25]]); Q = torch.tensor([[0.8, 0.1, 0.1]])\nkl = F.kl_div(Q.log(), P, reduction=\"batchmean\")  # input is log Q, target is P, giving KL(P||Q)\nprint(\"KL(P||Q) nats =\", round(kl.item(), 4))                               # 0.2231\n```\n\n0.2231 nats = 0.3219 bits × ln 2, matching the NumPy result. Note that the argument order of `F.kl_div` is the reverse of the mathematical notation: the first argument is the model's log-probabilities and the second is the target distribution.\n\n## Hands-on practice\n\n1. **Unit project**: simulate coin flips and estimate the bias by maximum likelihood, watching how the estimate fluctuates as the sample grows from 10 to 10,000; then compute cross-entropy and KL for two distributions of your choice and confirm that KL ≥ 0 and KL(P‖Q) ≠ KL(Q‖P).\n2. Work through the Basic Probability, Probability Distributions and Bayesian Inference chapters of [Seeing Theory](https://seeing-theory.brown.edu/).\n3. Run the Gaussian mixture model notebook in the [Mathematics for Machine Learning companion repository](https://github.com/mml-book/mml-book.github.io) and match its E-step and M-step to the EM section above.\n4. Call PyTorch's `CrossEntropyLoss` once with logits and once with probabilities, compare the results and explain the difference using the [official documentation](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html).\n\n## Suggested order\n\nBuild intuition with [Seeing Theory](https://seeing-theory.brown.edu/), then put the ideas into code with [D2L section 2.6](https://d2l.ai/chapter_preliminaries/probability.html). For systematic study use Chapter 6 (Probability and Distributions) and Chapter 8 (When Models Meet Data) of [Mathematics for Machine Learning](https://mml-book.github.io/). For information theory read the [D2L information theory appendix](https://d2l.ai/chapter_mdl-information-theory/mdl-information-theory.html), and go deeper with MacKay's [Information Theory, Inference, and Learning Algorithms](https://www.inference.org.uk/mackay/itila/). Then move on to [Overfitting, Generalisation and Data Splits](/learn/generalization)."
    },
    "zh-hans": {
      "title": "概率、统计与信息论：贝叶斯、最大似然、交叉熵与 KL 散度",
      "description": "面向机器学习的概率统计与信息论：随机变量与分布、期望与方差、条件概率与贝叶斯公式、最大似然估计、熵、交叉熵与 KL 散度，以及它们在分类损失、softmax 温度采样、知识蒸馏、EM 与 VAE 中的具体用法。依据原始论文与官方文档，附可运行的 NumPy 与 PyTorch 示例。",
      "updated": "2026-11-11",
      "takeaways": [
        "概率模型给每个可能结果分配一个非负、总和为 1 的数。大模型每一步输出的就是一个覆盖整个词表的离散分布，生成文本就是从这个分布里反复采样。",
        "贝叶斯公式 P(A|B) = P(B|A)·P(A) / P(B) 把先验与证据结合成后验。基础概率很低时，即使检测很准，阳性结果的后验概率也可能不高：患病率 1%、灵敏度 99%、假阳性率 5% 时，阳性者真正患病的概率约 16.7%。",
        "最大似然估计选择让观测数据出现概率最大的参数。对分类模型而言，最小化交叉熵损失就是最小化训练数据的负对数似然，两者是同一个目标。",
        "熵 H(P) 是按真实分布 P 编码所需的平均比特数（Shannon，1948）；交叉熵 H(P,Q) 是用模型分布 Q 编码 P 的平均比特数；两者之差就是 KL 散度 KL(P‖Q)，它恒不小于 0、只在 P=Q 时等于 0，且不对称。",
        "softmax 温度 T 把 logits 除以 T 再归一化：T>1 分布变平、熵升高，T<1 分布变尖。知识蒸馏用高温软标签，模型校准用温度缩放，文本生成用温度控制采样的随机程度。"
      ],
      "faq": [
        {
          "q": "学深度学习需要多少概率统计？",
          "a": "读论文和调模型时最常用的是：离散与连续分布、期望与方差、条件概率与贝叶斯公式、独立性、最大似然、熵、交叉熵与 KL 散度。测度论、随机过程等内容在大模型应用工作中较少直接用到。《Mathematics for Machine Learning》第 6 章与 D2L 的概率和信息论两节覆盖了上述内容。"
        },
        {
          "q": "交叉熵损失和最大似然是什么关系？",
          "a": "对独立同分布的训练样本，似然是各样本正确标签概率的乘积，取负对数后变成各样本 −log q(y) 之和。分类中的交叉熵损失把真实标签写成 one-hot 分布 P，此时 H(P,Q) = −log q(y)。所以最小化平均交叉熵与最大化对数似然等价。"
        },
        {
          "q": "KL 散度为什么不对称？用哪个方向有区别吗？",
          "a": "KL(P‖Q) = Σ P(x)·log(P(x)/Q(x)) 按 P 加权，P 有而 Q 几乎没有的结果会被重罚；反过来则按 Q 加权。本课示例中 KL(P‖Q)=0.3219 比特，KL(Q‖P)=0.2781 比特。最大似然训练对应最小化 KL(数据‖模型)；变分推断（如 VAE）通常最小化 KL(近似后验‖真实后验) 的形式，方向不同会导致拟合行为不同。"
        },
        {
          "q": "为什么 PyTorch 的 CrossEntropyLoss 输入的是 logits 而不是概率？",
          "a": "PyTorch 文档写明 CrossEntropyLoss 的输入应为每个类别未归一化的 logits，函数内部完成 log-softmax 与负对数似然，这样数值更稳定。另一个容易出错的是 KLDivLoss：输入要求是对数概率，默认 reduction='mean' 不等于数学上的 KL，文档建议用 reduction='batchmean'。"
        },
        {
          "q": "温度调高为什么生成更“随机”？",
          "a": "把 logits 除以 T>1 会缩小各类别之间的差距，softmax 后的分布更平，熵更高，低概率词被采到的机会增加；T→0 时接近总是选最大概率词（贪心解码）。Holtzman 等（2019）指出，以似然最大为目标的解码容易产生单调、重复的文本，因此实际生成常把温度与 top-p（核采样）一起使用。"
        }
      ],
      "sources": [
        {
          "title": "Deisenroth、Faisal、Ong：Mathematics for Machine Learning（官方免费版，第 6 章 Probability and Distributions）",
          "url": "https://mml-book.github.io/"
        },
        {
          "title": "Dive into Deep Learning：2.6 Probability and Statistics",
          "url": "https://d2l.ai/chapter_preliminaries/probability.html"
        },
        {
          "title": "Dive into Deep Learning：22.11 Information Theory",
          "url": "https://d2l.ai/chapter_mdl-information-theory/mdl-information-theory.html"
        },
        {
          "title": "Dive into Deep Learning：22.7 Maximum Likelihood",
          "url": "https://d2l.ai/chapter_mdl-probability-statistics/mdl-maximum-likelihood.html"
        },
        {
          "title": "Dive into Deep Learning：4.1 Softmax Regression",
          "url": "https://d2l.ai/chapter_linear-classification/softmax-regression.html"
        },
        {
          "title": "MacKay：Information Theory, Inference, and Learning Algorithms（作者公开全文）",
          "url": "https://www.inference.org.uk/mackay/itila/"
        },
        {
          "title": "Brown University：Seeing Theory（概率与统计交互可视化）",
          "url": "https://seeing-theory.brown.edu/"
        },
        {
          "title": "PyTorch 文档：torch.nn.CrossEntropyLoss",
          "url": "https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html"
        },
        {
          "title": "PyTorch 文档：torch.nn.KLDivLoss",
          "url": "https://docs.pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html"
        },
        {
          "title": "SciPy 文档：Statistical functions (scipy.stats)",
          "url": "https://docs.scipy.org/doc/scipy/reference/stats.html"
        },
        {
          "title": "Shannon（1948），A Mathematical Theory of Communication，Bell System Technical Journal",
          "url": "https://doi.org/10.1002/j.1538-7305.1948.tb01338.x"
        },
        {
          "title": "Kullback、Leibler（1951），On Information and Sufficiency，Annals of Mathematical Statistics",
          "url": "https://projecteuclid.org/euclid.aoms/1177729694"
        },
        {
          "title": "Dempster、Laird、Rubin（1977），Maximum Likelihood from Incomplete Data via the EM Algorithm",
          "url": "https://doi.org/10.1111/j.2517-6161.1977.tb01600.x"
        },
        {
          "title": "Kingma、Welling（2013），Auto-Encoding Variational Bayes",
          "url": "https://arxiv.org/abs/1312.6114"
        },
        {
          "title": "Hinton、Vinyals、Dean（2015），Distilling the Knowledge in a Neural Network",
          "url": "https://arxiv.org/abs/1503.02531"
        },
        {
          "title": "Guo 等（2017），On Calibration of Modern Neural Networks",
          "url": "https://arxiv.org/abs/1706.04599"
        },
        {
          "title": "Holtzman 等（2019），The Curious Case of Neural Text Degeneration",
          "url": "https://arxiv.org/abs/1904.09751"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/math-ml/probability-information/",
      "markdown": "**概要**：语言模型每一步输出的是一个概率分布，训练它用的损失来自最大似然，评价两个分布的差距用的是交叉熵和 KL 散度。本课按“分布与期望 → 条件概率与贝叶斯 → 最大似然 → 熵、交叉熵与 KL → softmax 与温度”的顺序展开，每一节对应到大模型训练或生成中的一个具体环节。\n\n本课属于[概率、统计与信息论](/learn/unit/u13-probability)单元，前置为 [Python 与 NumPy 环境](/learn/python-numpy-setup)，建议先学[线性代数](/learn/linear-algebra)与[微积分与优化](/learn/calculus-optimization)。后续可接[过拟合、泛化与数据划分](/learn/generalization)和[大模型是怎么学会的](/learn/how-llms-learn)。相关算法卡：[逻辑回归](/learn/algorithms/logistic-regression)、[朴素贝叶斯](/learn/algorithms/naive-bayes)、[EM 算法](/learn/algorithms/em)、[VAE](/learn/algorithms/vae)、[采样解码](/learn/algorithms/sampling)、[知识蒸馏](/learn/algorithms/knowledge-distillation)。\n\n## 随机变量、分布与期望\n\n随机变量是“结果不确定、但每种结果有确定概率”的量。机器学习中常见两类分布：\n\n- **离散分布**：结果可以一一列出，例如抛硬币（伯努利分布）、掷骰子、语言模型对词表中每个词给出的概率（类别分布）。每个结果的概率非负，总和为 1。\n- **连续分布**：结果取实数值，用概率密度描述，例如高斯（正态）分布 N(μ, σ²)。权重初始化、扩散模型加入的噪声、VAE 的隐变量都用到高斯分布。\n\n两个最常用的数字特征：\n\n```text\n期望  E[X]   = Σ x · P(X = x)            （连续时把求和换成积分）\n方差  Var[X] = E[(X − E[X])²] = E[X²] − (E[X])²\n```\n\n期望是“长期平均”，方差衡量离散程度。训练时报告的平均损失，就是损失在数据分布上期望的样本估计；小批量随机梯度是全量梯度的无偏估计，其方差随批量增大而减小。\n\n两个随机变量**独立**，指联合概率等于各自概率之积：P(A, B) = P(A)·P(B)。训练集“独立同分布”（i.i.d.）是大多数泛化分析的前提，下一课[过拟合、泛化与数据划分](/learn/generalization)会讨论这个前提被打破时的情况。\n\n## 条件概率与贝叶斯公式\n\n条件概率 P(A|B) 表示“已知 B 发生时 A 的概率”，定义为 P(A, B) / P(B)。把联合概率从两个方向展开，就得到贝叶斯公式：\n\n```text\nP(A|B) = P(B|A) · P(A) / P(B)\n后验    =  似然   ×  先验 / 证据\n```\n\n一个经典例子说明“基础概率”的重要性：某病患病率 1%，检测灵敏度 99%（患者检出阳性的概率），假阳性率 5%。\n\n```text\nP(阳性) = 0.99 × 0.01 + 0.05 × 0.99 = 0.0594\nP(患病 | 阳性) = 0.99 × 0.01 / 0.0594 ≈ 0.1667\n```\n\n即使检测相当准确，阳性者真正患病的概率也只有约 16.7%，因为健康人基数大，假阳性在绝对数量上多于真阳性。同样的推理适用于垃圾邮件过滤、异常检测等正例很少的任务，也是[朴素贝叶斯](/learn/algorithms/naive-bayes)分类器的基础。\n\n## 最大似然估计\n\n给定一组观测数据 D 和带参数 θ 的模型，**似然** L(θ) = P(D | θ) 把数据固定、把参数当作变量。最大似然估计（MLE）选择让 L(θ) 最大的 θ。样本独立时似然是连乘，实践中取对数变成求和，再取负号变成最小化：\n\n```text\nθ* = argmax Π P(xᵢ | θ) = argmin −Σ log P(xᵢ | θ)\n```\n\n以抛硬币为例：n 次中正面 k 次，伯努利模型的负对数似然为 −[k·log p + (n−k)·log(1−p)]，对 p 求导令其为 0，得 p* = k/n，即样本频率。本课示例用 1000 次模拟抛掷（真实 p = 0.7）验证：样本频率为 0.678，在 0.01–0.99 网格上负对数似然最小的点恰为 0.68。\n\n最大似然在机器学习中无处不在：[线性回归](/learn/algorithms/linear-regression)在高斯噪声假设下的最大似然解就是最小二乘；[逻辑回归](/learn/algorithms/logistic-regression)与神经网络分类器的训练目标就是对数似然；大语言模型的预训练目标是最大化下一个词的对数似然。当数据含有未观测的隐变量时，Dempster、Laird 与 Rubin（1977）给出的 [EM 算法](/learn/algorithms/em)通过交替“估计隐变量分布（E 步）”与“最大化期望对数似然（M 步）”求最大似然解，高斯混合模型就是典型应用。\n\n最大似然只看数据。**最大后验估计**（MAP）再乘上参数的先验 P(θ)：若先验是零均值高斯，取负对数后多出的一项正比于 ‖θ‖²，这正是 L2 正则化。下一课会从泛化的角度再讨论正则化。\n\n## 熵、交叉熵与 KL 散度\n\nShannon（1948）在《A Mathematical Theory of Communication》中用熵度量一个分布的不确定性。以 2 为底时单位是比特，以 e 为底时单位是奈特（nats，PyTorch 损失默认使用自然对数）：\n\n```text\n熵       H(P)     = −Σ P(x) · log P(x)\n交叉熵   H(P, Q)  = −Σ P(x) · log Q(x)\nKL 散度  KL(P‖Q)  =  Σ P(x) · log (P(x) / Q(x)) = H(P, Q) − H(P)\n```\n\n直观理解：H(P) 是按真实分布 P 设计最优编码时平均每个符号需要的比特数；如果误用分布 Q 来设计编码，平均需要 H(P, Q) 比特；多花的部分就是 KL(P‖Q)。KL 散度由 Kullback 与 Leibler（1951）提出，有三条性质需要记住：\n\n1. **非负**：KL(P‖Q) ≥ 0，当且仅当 P = Q 时取 0（吉布斯不等式）。本课示例对 1 万对随机分布计算 KL，最小值为 0.0027，没有负值。\n2. **不对称**：一般 KL(P‖Q) ≠ KL(Q‖P)，因此它不是距离。示例中 P = (0.5, 0.25, 0.25)、Q = (0.8, 0.1, 0.1) 时，KL(P‖Q) = 0.3219 比特，KL(Q‖P) = 0.2781 比特。\n3. **与交叉熵的关系**：真实分布 P 固定时 H(P) 是常数，最小化交叉熵 H(P, Q) 与最小化 KL(P‖Q) 等价。\n\n这正是分类模型用交叉熵作损失的原因：把真实标签写成 one-hot 分布 P（正确类别概率为 1），交叉熵简化为 −log Q(y)，即正确类别的负对数似然。所以“最小化交叉熵”“最小化 KL(数据‖模型)”和“最大似然”在这里是同一个目标的三种说法。\n\nKL 散度在大模型中还有几处直接应用：\n\n| 场景 | KL 的作用 | 延伸阅读 |\n|---|---|---|\n| VAE | 训练目标（证据下界）= 重建项 − KL(近似后验‖先验)，Kingma 与 Welling（2013） | [VAE 算法卡](/learn/algorithms/vae) |\n| 知识蒸馏 | 学生模型拟合教师模型的高温软标签分布，Hinton 等（2015） | [知识蒸馏算法卡](/learn/algorithms/knowledge-distillation) |\n| RLHF 与偏好优化 | 用对参考模型的 KL 约束防止策略偏离过远 | [RLHF 算法卡](/learn/algorithms/rlhf)、[DPO 算法卡](/learn/algorithms/dpo) |\n\n## softmax、温度与采样\n\n神经网络最后一层输出的是任意实数 logits。softmax 把它们变成分布：\n\n```text\nsoftmax(z)ᵢ = exp(zᵢ / T) / Σⱼ exp(zⱼ / T)        （T 为温度，默认 T = 1）\n```\n\n实现时会先减去最大值再取指数，避免数值溢出，这不改变结果。本课示例中 logits = (2.0, 1.0, 0.1)、正确类别为第 0 类时，softmax 结果为 (0.659, 0.242, 0.099)，交叉熵损失为 −log 0.659 = 0.4170 奈特，与 PyTorch `F.cross_entropy` 的输出一致。\n\n温度 T 改变分布的“尖锐程度”：\n\n| 温度 | 分布 | 熵（比特） |\n|---|---|---|\n| T = 0.5 | (0.864, 0.117, 0.019) | 0.655 |\n| T = 1.0 | (0.659, 0.242, 0.099) | 1.222 |\n| T = 2.0 | (0.502, 0.304, 0.194) | 1.481 |\n\n温度在三个地方会反复出现：\n\n- **文本生成**：T 越高，低概率词越容易被采到，输出更多样；T 越低越接近贪心解码。Holtzman 等（2019）发现以最大似然为解码目标会产生单调、重复的文本，并提出核采样（top-p），只从累计概率达到 p 的最小词集合中采样。见[采样解码算法卡](/learn/algorithms/sampling)。\n- **知识蒸馏**：Hinton 等（2015）用较高温度软化教师模型的输出，让学生模型也能学到“错误类别之间的相对大小”。\n- **模型校准**：Guo 等（2017）发现现代神经网络普遍过度自信，在验证集上拟合一个温度参数（温度缩放）对多数数据集都是简单有效的校准方法。\n\n## 可运行示例\n\n以下代码在 NumPy 2.5 上实测，输出与上文数字一致。\n\n```python\nimport numpy as np\nrng = np.random.default_rng(0)\n\n# 1) 贝叶斯公式：患病率 1%，灵敏度 99%，假阳性率 5%\nprior, sens, fpr = 0.01, 0.99, 0.05\np_pos = sens * prior + fpr * (1 - prior)\nprint(f\"P(病|阳性) = {sens * prior / p_pos:.4f}\")\n\n# 2) 最大似然：抛硬币 1000 次，真实 p=0.7\nflips = rng.random(1000) < 0.7\ngrid = np.linspace(0.01, 0.99, 99)\nnll = -(flips.sum() * np.log(grid) + (~flips).sum() * np.log(1 - grid))\nprint(f\"样本频率 {flips.mean():.3f}，网格上 NLL 最小的 p = {grid[nll.argmin()]:.2f}\")\n\n# 3) 熵、交叉熵、KL\ndef H(p): return -(p * np.log2(p)).sum()\ndef CE(p, q): return -(p * np.log2(q)).sum()\ndef KL(p, q): return (p * np.log2(p / q)).sum()\nP = np.array([0.5, 0.25, 0.25]); Q = np.array([0.8, 0.1, 0.1])\nprint(f\"H(P)={H(P):.4f} 比特  CE(P,Q)={CE(P,Q):.4f}  KL(P||Q)={KL(P,Q):.4f}  KL(Q||P)={KL(Q,P):.4f}\")\nprint(f\"CE - H = {CE(P,Q) - H(P):.4f}（等于 KL(P||Q)）\")\nks = [KL(a, b) for a, b in (rng.dirichlet(np.ones(5), 2) for _ in range(10000))]\nprint(f\"1 万对随机分布的最小 KL = {min(ks):.6f}（≥0）\")\n\n# 4) 交叉熵损失 = 正确类别的负对数似然\nlogits = np.array([2.0, 1.0, 0.1]); y = 0\np = np.exp(logits - logits.max()); p /= p.sum()\nprint(f\"softmax={np.round(p, 4)}  -log p[y]={-np.log(p[y]):.4f} nats\")\n\n# 5) 温度：T 越大分布越平、熵越高\nfor T in (0.5, 1.0, 2.0):\n    q = np.exp(logits / T - (logits / T).max()); q /= q.sum()\n    print(f\"T={T}: p={np.round(q, 3)}  熵={-(q * np.log2(q)).sum():.3f} 比特\")\n```\n\n实测输出要点：P(病|阳性) = 0.1667；样本频率 0.678，NLL 最小点 0.68；H(P) = 1.5000 比特，CE(P,Q) = 1.8219，KL(P‖Q) = 0.3219，KL(Q‖P) = 0.2781，CE − H = 0.3219；随机分布最小 KL 为 0.002657；softmax = (0.659, 0.2424, 0.0986)，损失 0.4170 奈特。\n\n用 PyTorch 核对（PyTorch 2.15 CPU 实测）：\n\n```python\nimport torch, torch.nn.functional as F\nlogits = torch.tensor([[2.0, 1.0, 0.1]]); y = torch.tensor([0])\nprint(\"F.cross_entropy =\", round(F.cross_entropy(logits, y).item(), 4))      # 0.417\nP = torch.tensor([[0.5, 0.25, 0.25]]); Q = torch.tensor([[0.8, 0.1, 0.1]])\nkl = F.kl_div(Q.log(), P, reduction=\"batchmean\")  # 输入为 log Q，目标为 P，得到 KL(P||Q)\nprint(\"KL(P||Q) nats =\", round(kl.item(), 4))                               # 0.2231\n```\n\n0.2231 奈特 = 0.3219 比特 × ln 2，与 NumPy 结果一致。注意 `F.kl_div` 的参数顺序与数学记号相反：第一个参数是模型分布的对数概率，第二个参数是目标分布。\n\n## 动手练习\n\n1. **单元项目**：模拟抛硬币实验，用最大似然估计偏置，观察样本量从 10 增加到 10000 时估计值的波动；再任取两个分布计算交叉熵与 KL，验证 KL ≥ 0 且 KL(P‖Q) ≠ KL(Q‖P)。\n2. 在 [Seeing Theory](https://seeing-theory.brown.edu/) 中依次完成“基础概率”“概率分布”“贝叶斯推断”三章的交互演示。\n3. 跑 [Mathematics for Machine Learning 配套仓库](https://github.com/mml-book/mml-book.github.io)中的高斯混合模型 Notebook，对照本课的 EM 一节理解 E 步与 M 步。\n4. 用 PyTorch 分别以 logits 和概率调用 `CrossEntropyLoss`，对比结果并对照[官方文档](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)解释差异。\n\n## 推荐学习顺序\n\n先用 [Seeing Theory](https://seeing-theory.brown.edu/) 建立直觉，再按 [D2L 2.6 节](https://d2l.ai/chapter_preliminaries/probability.html)把概念落到代码上；系统学习用 [Mathematics for Machine Learning](https://mml-book.github.io/) 第 6 章（概率与分布）与第 8 章（模型与数据）；信息论部分读 [D2L 信息论附录](https://d2l.ai/chapter_mdl-information-theory/mdl-information-theory.html)，想深入可读 MacKay 的 [Information Theory, Inference, and Learning Algorithms](https://www.inference.org.uk/mackay/itila/)。之后进入[过拟合、泛化与数据划分](/learn/generalization)。"
    }
  }
}