Module 03 — Probability, Statistics and Information Theory
⬅️ Module 02 · 🗺️ Curriculum · 🏠 Home · Module 04 ➡️
Level: Foundational · Prerequisites: Module 01, Module 02 · Time: about 8–10 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Overview and learning goals
Machine learning is reasoning under uncertainty. Probability describes uncertainty about data and parameters; statistics turns finite samples into estimates; information theory quantifies how much a distribution tells us and gives us the loss functions (cross-entropy, KL divergence) used throughout the rest of this wiki. In particular, minimising cross-entropy is maximum-likelihood estimation, and the VAE, GAN and diffusion objectives are all statements about divergences between distributions.
After this module you should be able to:
- apply conditional probability and Bayes' theorem;
- compute expectations, variances and covariances; recognise common distributions;
- derive maximum-likelihood estimators and connect them to loss functions;
- define entropy, cross-entropy, KL divergence and mutual information and prove $D_{KL}\ge0$;
- derive the gradient of the softmax cross-entropy loss.
Beginner: the big picture
A random variable assigns numbers to uncertain outcomes. Its distribution says how probable each value is. We usually cannot see the true distribution, only samples, so we pick a family of models $p_\theta$ and choose $\theta$ so the observed data look probable (likelihood). A classifier outputs a probability vector; the loss measures how much probability it assigned to the correct answer. If it gave the true class probability $0.9$ the penalty $-\ln0.9\approx0.105$ is small; if it gave $0.01$ the penalty $\approx4.6$ is large — confident mistakes are punished hardest.
flowchart LR
D["Data samples x1..xN"] --> L["Likelihood p_theta(data)"]
M["Model family p_theta"] --> L
L --> N["Negative log-likelihood = cross-entropy"]
N --> O["Minimise over theta (gradient descent)"]
O --> E["Trained model / MLE"]
Loading
Core concepts and derivations
Events, conditional probability and Bayes' theorem
$P(A\mid B)=P(A\cap B)/P(B)$. Rearranging the definition twice gives Bayes' theorem
$$P(A\mid B)=\frac{P(B\mid A)\,P(A)}{P(B)},\qquad P(B)=\sum_iP(B\mid A_i)P(A_i).$$
In Bayesian language: posterior $\propto$ likelihood $\times$ prior. This is also the template for VAEs (Module 18).
Random variables: PMF, PDF and CDF
Discrete variables have a PMF $p(x)=P(X=x)$ with $\sum_xp(x)=1$. Continuous variables have a PDF $f(x)\ge0$ with $\int f=1$ and $P(a\le X\le b)=\int_a^bf$; note $f(x)$ can exceed 1 (it is a density, not a probability). The CDF is $F(x)=P(X\le x)$.
Expectation, variance, covariance and independence
$\mathbb{E}[g(X)]=\sum_xg(x)p(x)$ or $\int g(x)f(x)dx$; expectation is linear. $\mathrm{Var}(X)=\mathbb{E}[(X-\mu)^2]=\mathbb{E}[X^2]-\mu^2$. $\mathrm{Cov}(X,Y)=\mathbb{E}[XY]-\mathbb{E}X\,\mathbb{E}Y$, and $\mathrm{Var}(X+Y)=\mathrm{Var}X+\mathrm{Var}Y+2\mathrm{Cov}(X,Y)$. Independence implies zero covariance; the converse is false ($X\sim\mathcal{N}(0,1)$, $Y=X^2$ are uncorrelated but dependent).
Joint, marginal and conditional distributions
$p(x,y)=p(y\mid x)p(x)$ (chain rule); marginals sum out: $p(x)=\sum_yp(x,y)$. For a vector with covariance matrix $\Sigma$ (always PSD, Module 01), $\Sigma_{ij}=\mathrm{Cov}(X_i,X_j)$. The multivariate Gaussian $\mathcal{N}(\mathbf{\mu},\Sigma)$ has density $\propto\exp\!\left(-\frac12(\mathbf{x}-\mathbf{\mu})^\top\Sigma^{-1}(\mathbf{x}-\mathbf{\mu})\right)$ and stays Gaussian under marginalisation and conditioning.
| Distribution |
Support |
Parameters |
Mean / variance |
Used for |
| Bernoulli |
$\{0,1\}$ |
$p$ |
$p$ / $p(1-p)$
|
binary labels |
| Categorical |
$\{1..K\}$ |
$\mathbf{p}$ |
– |
multiclass labels, tokens |
| Binomial |
$\{0..n\}$ |
$n,p$ |
$np$ / $np(1-p)$
|
counts of successes |
| Uniform |
$[a,b]$ |
$a,b$ |
$\frac{a+b}2$ / $\frac{(b-a)^2}{12}$
|
initialisation, noise |
| Gaussian |
$\mathbb{R}$ |
$\mu,\sigma^2$ |
$\mu$ / $\sigma^2$
|
noise, latents, weights |
Sampling, Monte Carlo estimation and maximum likelihood
Monte Carlo: $\mathbb{E}[f(X)]\approx\frac1N\sum_if(x_i)$ with standard error $O(1/\sqrt N)$ regardless of dimension — the reason SGD with mini-batches works.
Maximum likelihood (MLE). For i.i.d. data, $\hat\theta=\arg\max_\theta\sum_i\ln p_\theta(x_i)$. Example, Bernoulli with $k$ successes in $n$ trials: $\ell(p)=k\ln p+(n-k)\ln(1-p)$, $\ell'(p)=\frac kp-\frac{n-k}{1-p}=0\Rightarrow\hat p=k/n$. For a Gaussian: $\hat\mu=\frac1n\sum x_i$, $\hat\sigma^2=\frac1n\sum(x_i-\hat\mu)^2$ (biased; divide by $n-1$ for unbiased).
Loss functions are likelihoods. If $y=f_\theta(x)+\varepsilon$, $\varepsilon\sim\mathcal{N}(0,\sigma^2)$, then $-\ln p(y\mid x)=\frac{(y-f_\theta(x))^2}{2\sigma^2}+\text{const}$: MSE is Gaussian MLE. A categorical output gives cross-entropy.
Entropy, cross-entropy, KL divergence and mutual information
$$H(p)=-\sum_xp(x)\ln p(x),\qquad H(p,q)=-\sum_xp(x)\ln q(x),\qquad D_{KL}(p\Vert q)=\sum_xp(x)\ln\frac{p(x)}{q(x)}=H(p,q)-H(p).$$
Entropy is the average surprise; cross-entropy the average surprise when you believe $q$ but the truth is $p$. Because $H(p)$ does not depend on the model, minimising cross-entropy over $q$ equals minimising KL.

Figure 3.1 — For $p=\mathcal{N}(0,1)$ and $q=\mathcal{N}(1.5,2^2)$: $D_{KL}(p\Vert q)\approx0.599$ but $D_{KL}(q\Vert p)\approx1.932$. KL is not a distance. Original figure (figures/make_figs_1.py).
$D_{KL}\ge0$ (Gibbs' inequality). Since $-\ln$ is convex, Jensen's inequality gives $-D_{KL}(p\Vert q)=\mathbb{E}_p\!\left[\ln\frac qp\right]\le\ln\mathbb{E}_p\!\left[\frac qp\right]=\ln\sum_xq(x)=0$, with equality iff $p=q$.
Closed form for 1-D Gaussians: $D_{KL}\bigl(\mathcal{N}(\mu_1,\sigma_1^2)\Vert\mathcal{N}(\mu_2,\sigma_2^2)\bigr)=\ln\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12$ (used in the VAE, Module 18).
Conditional entropy and Jensen's inequality
$H(Y\mid X)=-\sum_{x,y}p(x,y)\ln p(y\mid x)=H(X,Y)-H(X)$. Mutual information $I(X;Y)=D_{KL}\bigl(p(x,y)\Vert p(x)p(y)\bigr)=H(Y)-H(Y\mid X)\ge0$ measures dependence; it is the quantity contrastive objectives lower-bound (InfoNCE, Module 17). Jensen: for convex $\varphi$, $\varphi(\mathbb{E}X)\le\mathbb{E}\varphi(X)$ — the engine behind the ELBO (Module 18).
Log-likelihood and probabilistic classification losses
For softmax outputs $p_k=e^{z_k}/\sum_je^{z_j}$ and one-hot label $\mathbf{y}$, $L=-\sum_ky_k\ln p_k$. Using $\partial p_k/\partial z_j=p_k(\delta_{kj}-p_j)$,
$$\frac{\partial L}{\partial z_j}=-\sum_ky_k\frac{1}{p_k}p_k(\delta_{kj}-p_j)=-y_j+p_j\sum_ky_k=p_j-y_j .$$
The gradient "prediction minus target" is remarkably simple and does not vanish when the model is confidently wrong — unlike MSE on probabilities. For a Bernoulli/sigmoid output the same form holds: $\partial L/\partial z=\sigma(z)-y$.
Bayes. A disease has prevalence 1%; a test has sensitivity 99% and false-positive rate 5%. $P(\text{pos})=0.99\cdot0.01+0.05\cdot0.99=0.0594$, so $P(\text{disease}\mid\text{pos})=0.0099/0.0594=1/6\approx16.7\%$. Most positives are false because the prior is low.
Softmax cross-entropy. Logits $\mathbf{z}=(2,1,0)$, true class 1. $\sum e^{z}=7.389+2.718+1=11.107$, so $\mathbf{p}=(0.665,0.245,0.090)$, $L=-\ln0.665=0.408$, gradient $\mathbf{p}-\mathbf{y}=(-0.335,0.245,0.090)$ (sums to 0).
import numpy as np
def softmax(z):
z = z - z.max(axis=-1, keepdims=True) # numerical stability
e = np.exp(z); return e / e.sum(axis=-1, keepdims=True)
def cross_entropy(logits, y_idx):
logp = np.log(softmax(logits)) # in practice: log-softmax directly
return -logp[np.arange(len(y_idx)), y_idx].mean()
def kl(p, q): return np.sum(p * (np.log(p) - np.log(q)))
z = np.array([[2., 1., 0.]]); print(cross_entropy(z, np.array([0]))) # 0.4076
p = softmax(z)[0]; print(p - np.eye(3)[0]) # gradient p - y
assert kl(p, p) == 0 and kl(p, np.ones(3) / 3) > 0
PyTorch: torch.nn.functional.cross_entropy(logits, target) takes raw logits and applies log-softmax internally; never feed it softmax outputs.
-
MLE, MAP and Bayesian inference. MAP adds a log-prior: a Gaussian prior gives $\ell_2$ regularisation, a Laplace prior $\ell_1$ (Module 10).
-
Fisher information and natural gradient use the local curvature of $D_{KL}$; Adam's second moment is a crude diagonal proxy.
-
Variational inference minimises $D_{KL}(q\Vert p(\cdot\mid x))$ over a tractable family (Module 18); $f$-divergences and Wasserstein distance underlie GAN variants (Module 19).
-
Estimators: bias–variance of estimators, the Cramér–Rao bound, and importance sampling.
-
Concentration inequalities (Hoeffding, Chebyshev) underpin generalisation bounds (Module 10).
-
Calibration measures whether predicted probabilities match frequencies (Module 24).
Pitfalls and best practices
- Feeding probabilities into a loss that expects logits (double softmax).
- Computing $\ln(\text{softmax})$ naively → overflow/underflow; use log-sum-exp.
- Treating KL as symmetric or as a metric; the direction determines mode-seeking vs mass-covering behaviour.
- Confusing a PDF value with a probability.
- Ignoring base rates (Bayes example above) when interpreting classifier outputs.
Conceptual questions and answers
Q1. Why is minimising cross-entropy equivalent to maximum likelihood?
Show answer
Cross-entropy between the empirical distribution and the model is $-\frac1N\sum_i\ln p_\theta(y_i\mid x_i)$, the negative average log-likelihood. Minimising it maximises the likelihood.
Q2. Why does MSE correspond to Gaussian noise?
Show answer
With $\varepsilon\sim\mathcal{N}(0,\sigma^2)$ the negative log-density of $y$ is $\frac{(y-f_\theta(x))^2}{2\sigma^2}+\text{const}$. Heavier-tailed (Laplace) noise gives MAE instead.
Q3. Prove that KL divergence is non-negative.
Show answer
Apply Jensen to the convex function $-\ln$: $D_{KL}(p\Vert q)=\mathbb{E}_p[-\ln(q/p)]\ge-\ln\mathbb{E}_p[q/p]=-\ln\sum q=0$.
Q4. Why is KL asymmetric, and what is the practical effect?
Show answer
The expectation is taken under the first argument. $D_{KL}(p\Vert q)$ heavily penalises $q$ being small where $p$ has mass (mass-covering); $D_{KL}(q\Vert p)$ penalises $q$ placing mass where $p$ has none (mode-seeking). Variational inference uses the latter; MLE the former.
Q5. What is the gradient of softmax cross-entropy with respect to the logits?
Show answer
$\mathbf{p}-\mathbf{y}$ — predicted probabilities minus the one-hot target.
Q6. Are uncorrelated variables independent?
Show answer
No. Independence implies zero covariance, but $X$ and $X^2$ for symmetric $X$ are uncorrelated yet dependent. (For jointly Gaussian variables the two are equivalent.)
Q7. Why does Monte Carlo estimation work in very high dimensions?
Show answer
The standard error $\sigma/\sqrt N$ depends on the variance of $f(X)$ and the sample count, not directly on dimension. This is why mini-batch gradients are useful estimates of the full gradient.
Q8. Why is the unbiased variance estimator divided by $n-1$?
Show answer
The sample mean is fitted to the same data, making deviations smaller than deviations from the true mean; dividing by $n$ underestimates $\sigma^2$ by a factor $(n-1)/n$.
Q9. What does mutual information measure and why is it $\ge 0$?
Show answer
How much knowing one variable reduces uncertainty about the other. It is a KL divergence between the joint and the product of marginals, hence non-negative and zero iff independent.
Q10. A model assigns probability 0.01 to the true class. Compare MSE and cross-entropy gradients.
Show answer
With sigmoid output, MSE's gradient contains the factor $\sigma'(z)=\sigma(1-\sigma)\approx0.0099$, so learning is slow when confidently wrong; cross-entropy's gradient $\sigma-y\approx-0.99$ is large exactly when the error is large.
Sources and further reading
- Cover, T. M., & Thomas, J. A. (2006). Elements of Information Theory (2nd ed.). Wiley.
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning, Ch. 1–2. Springer.
- Murphy, K. P. (2022). Probabilistic Machine Learning: An Introduction. MIT Press.
- Goodfellow, Bengio & Courville (2016). Deep Learning, Ch. 3.
- Blitzstein, J., & Hwang, J. (2019). Introduction to Probability (2nd ed.). CRC Press.
⬅️ Module 02 · 🗺️ Curriculum · 🏠 Home · Module 04 ➡️