Skip to content
English

Switch theme

Math & Machine Learning Foundations

Probability, Statistics and Information Theory: Bayes, Maximum Likelihood, Cross-Entropy and KL Divergence

Intermediate 35 min For: Beginners / Researchers

Key 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.

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.

This lesson belongs to the Probability, Statistics & Information Theory unit. The prerequisite is Python and NumPy setup, and Linear Algebra and Calculus and Optimization are recommended first. Continue with Overfitting, Generalisation and Data Splits and How LLMs Learn. Related algorithm cards: logistic regression, naive Bayes, EM, VAE, sampling and knowledge distillation.

Random variables, distributions and expectation

A 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:

  • 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.
  • 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.

The two summary numbers used most:

Expectation  E[X]   = Σ x · P(X = x)            (replace the sum with an integral for continuous X)
Variance     Var[X] = E[(X − E[X])²] = E[X²] − (E[X])²

Expectation 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.

Two 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, looks at what happens when that assumption breaks.

Conditional probability and Bayes' rule

The 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:

P(A|B) = P(B|A) · P(A) / P(B)
posterior = likelihood × prior / evidence

A 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.

P(positive) = 0.99 × 0.01 + 0.05 × 0.99 = 0.0594
P(disease | positive) = 0.99 × 0.01 / 0.0594 ≈ 0.1667

Even 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 classifier.

Maximum likelihood estimation

Given 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:

θ* = argmax Π P(xᵢ | θ) = argmin −Σ log P(xᵢ | θ)

Take 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.

Maximum likelihood is everywhere in machine learning. Under Gaussian noise, the maximum-likelihood solution of linear regression is least squares; 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 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.

Maximum 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.

Entropy, cross-entropy and KL divergence

In "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:

Entropy        H(P)     = −Σ P(x) · log P(x)
Cross-entropy  H(P, Q)  = −Σ P(x) · log Q(x)
KL divergence  KL(P‖Q)  =  Σ P(x) · log (P(x) / Q(x)) = H(P, Q) − H(P)

Intuitively, 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:

  1. 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.
  2. 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.
  3. 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).

This 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.

KL divergence also appears directly in large models:

Setting Role of KL Further reading
VAE The training objective (evidence lower bound) is a reconstruction term minus KL(approximate posterior‖prior), Kingma and Welling (2013) VAE card
Knowledge distillation The student fits the teacher's high-temperature soft-target distribution, Hinton et al. (2015) Knowledge distillation card
RLHF and preference optimisation A KL penalty to a reference model keeps the policy from drifting too far RLHF card, DPO card

Softmax, temperature and sampling

The last layer of a neural network outputs arbitrary real numbers called logits. Softmax turns them into a distribution:

softmax(z)ᵢ = exp(zᵢ / T) / Σⱼ exp(zⱼ / T)        (T is the temperature, T = 1 by default)

Implementations 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.

Temperature changes how peaked the distribution is:

Temperature Distribution Entropy (bits)
T = 0.5 (0.864, 0.117, 0.019) 0.655
T = 1.0 (0.659, 0.242, 0.099) 1.222
T = 2.0 (0.502, 0.304, 0.194) 1.481

Temperature shows up in three places:

  • 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.
  • 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.
  • 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.

Runnable examples

The code below was run on NumPy 2.5 and its output matches the numbers above.

import numpy as np
rng = np.random.default_rng(0)

# 1) Bayes' rule: 1% prevalence, 99% sensitivity, 5% false-positive rate
prior, sens, fpr = 0.01, 0.99, 0.05
p_pos = sens * prior + fpr * (1 - prior)
print(f"P(disease|positive) = {sens * prior / p_pos:.4f}")

# 2) Maximum likelihood: 1,000 coin flips with true p = 0.7
flips = rng.random(1000) < 0.7
grid = np.linspace(0.01, 0.99, 99)
nll = -(flips.sum() * np.log(grid) + (~flips).sum() * np.log(1 - grid))
print(f"sample frequency {flips.mean():.3f}, grid p with lowest NLL = {grid[nll.argmin()]:.2f}")

# 3) Entropy, cross-entropy, KL
def H(p): return -(p * np.log2(p)).sum()
def CE(p, q): return -(p * np.log2(q)).sum()
def KL(p, q): return (p * np.log2(p / q)).sum()
P = np.array([0.5, 0.25, 0.25]); Q = np.array([0.8, 0.1, 0.1])
print(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}")
print(f"CE - H = {CE(P,Q) - H(P):.4f} (equals KL(P||Q))")
ks = [KL(a, b) for a, b in (rng.dirichlet(np.ones(5), 2) for _ in range(10000))]
print(f"minimum KL over 10,000 random pairs = {min(ks):.6f} (>= 0)")

# 4) Cross-entropy loss = negative log-likelihood of the correct class
logits = np.array([2.0, 1.0, 0.1]); y = 0
p = np.exp(logits - logits.max()); p /= p.sum()
print(f"softmax={np.round(p, 4)}  -log p[y]={-np.log(p[y]):.4f} nats")

# 5) Temperature: larger T gives a flatter, higher-entropy distribution
for T in (0.5, 1.0, 2.0):
    q = np.exp(logits / T - (logits / T).max()); q /= q.sum()
    print(f"T={T}: p={np.round(q, 3)}  entropy={-(q * np.log2(q)).sum():.3f} bits")

Key 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.

A PyTorch cross-check (run on PyTorch 2.15 CPU):

import torch, torch.nn.functional as F
logits = torch.tensor([[2.0, 1.0, 0.1]]); y = torch.tensor([0])
print("F.cross_entropy =", round(F.cross_entropy(logits, y).item(), 4))      # 0.417
P = torch.tensor([[0.5, 0.25, 0.25]]); Q = torch.tensor([[0.8, 0.1, 0.1]])
kl = F.kl_div(Q.log(), P, reduction="batchmean")  # input is log Q, target is P, giving KL(P||Q)
print("KL(P||Q) nats =", round(kl.item(), 4))                               # 0.2231

0.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.

Hands-on practice

  1. 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).
  2. Work through the Basic Probability, Probability Distributions and Bayesian Inference chapters of Seeing Theory.
  3. Run the Gaussian mixture model notebook in the Mathematics for Machine Learning companion repository and match its E-step and M-step to the EM section above.
  4. Call PyTorch's CrossEntropyLoss once with logits and once with probabilities, compare the results and explain the difference using the official documentation.

Suggested order

Build intuition with Seeing Theory, then put the ideas into code with D2L section 2.6. For systematic study use Chapter 6 (Probability and Distributions) and Chapter 8 (When Models Meet Data) of Mathematics for Machine Learning. For information theory read the D2L information theory appendix, and go deeper with MacKay's Information Theory, Inference, and Learning Algorithms. Then move on to Overfitting, Generalisation and Data Splits.

FAQ

How much probability and statistics do I need for deep learning?

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.

How is cross-entropy loss related to maximum likelihood?

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.

Why is KL divergence asymmetric, and does the direction matter?

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.

Why does PyTorch's CrossEntropyLoss take logits rather than probabilities?

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'.

Why does a higher temperature make generation more random?

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.

Related AI news

Links go to the original publishers.

Sources & further reading

  1. Deisenroth, Faisal, Ong: Mathematics for Machine Learning (free official edition, Chapter 6 Probability and Distributions)
  2. Dive into Deep Learning: 2.6 Probability and Statistics
  3. Dive into Deep Learning: 22.11 Information Theory
  4. Dive into Deep Learning: 22.7 Maximum Likelihood
  5. Dive into Deep Learning: 4.1 Softmax Regression
  6. MacKay: Information Theory, Inference, and Learning Algorithms (free full text from the author)
  7. Brown University: Seeing Theory (interactive probability and statistics)
  8. PyTorch documentation: torch.nn.CrossEntropyLoss
  9. PyTorch documentation: torch.nn.KLDivLoss
  10. SciPy documentation: Statistical functions (scipy.stats)
  11. Shannon (1948), A Mathematical Theory of Communication, Bell System Technical Journal
  12. Kullback and Leibler (1951), On Information and Sufficiency, Annals of Mathematical Statistics
  13. Dempster, Laird and Rubin (1977), Maximum Likelihood from Incomplete Data via the EM Algorithm
  14. Kingma and Welling (2013), Auto-Encoding Variational Bayes
  15. Hinton, Vinyals and Dean (2015), Distilling the Knowledge in a Neural Network
  16. Guo et al. (2017), On Calibration of Modern Neural Networks
  17. Holtzman et al. (2019), The Curious Case of Neural Text Degeneration

Part of these paths

Data updated: Learn AI curriculum · Lesson news(UTC+8)