Lesson overview | Lesson overview | Next part
Expectation and Moments: Part 1: Intuition and Historical Context to 12. Why This Matters for AI 2026 Perspective
1. Intuition and Historical Context
1.1 The Moment Analogy
The word "moment" comes from classical mechanics. In physics, the first moment of a mass distribution is the center of mass; the second moment is the moment of inertia. Probability theory borrows this language directly: the -th moment of a random variable is , the expected value of raised to the -th power.
Imagine balancing a plank on which weights are placed at positions with weights (probabilities). The balance point is - the center of mass. The spread around that center is captured by , the second central moment. Higher moments capture the shape: whether the distribution leans left or right (skewness), whether it has heavy tails (kurtosis).
MOMENTS AS SHAPE DESCRIPTORS
========================================================================
First moment (mean \\mu): Location of center
Second central moment (\\sigma^2): Spread about center
Third central moment (\\gamma_1\\sigma^3): Asymmetry (skewness)
Fourth central moment (\\gamma_2\\sigma^4): Tail weight (kurtosis)
Standard normal N(0,1): \\mu=0, \\sigma^2=1, \\gamma_1=0, \\gamma_2=0 (baseline)
Right-skewed (\\gamma_1 > 0): Heavy right tail: income, LLM token probs
#
###
#####=====........
----+--------------------
Heavy-tailed (\\gamma_2 > 0): Leptokurtic: gradient norms, loss landscapes
#
#
###
#####.............
----+--------------------
========================================================================
Every major operation in statistics reduces to computing moments. The mean is the first moment. The variance is the second central moment. The sample statistics we compute to estimate distributions are moment estimates. The method of moments estimation technique literally sets sample moments equal to theoretical moments and solves for parameters.
For AI: Every loss function is an expectation over the data distribution:
We cannot compute this exactly (the true distribution is unknown), so we estimate it with the sample mean over a minibatch. The entire machinery of stochastic gradient descent rests on this approximation.
1.2 Why Moments Matter for AI
Moments appear in nearly every component of modern deep learning:
Loss functions. The mean squared error estimates , the expected squared loss. Cross-entropy loss estimates . Every loss is a first moment of some function of the predictions.
Optimisation. The Adam optimizer maintains running estimates of the first moment and second moment of the gradient . The adaptive learning rate normalises by the square root of the second moment. Without understanding moments, Adam is a black box; with it, Adam is moment matching with bias correction.
Batch Normalisation. BatchNorm computes the sample mean and variance of activations across a batch, then normalises. This is moment normalisation: forcing the first moment to zero and the second to one, stabilising training by controlling the distribution of layer activations.
KL Divergence. The KL divergence is an expectation under . Its non-negativity () follows directly from Jensen's inequality applied to the convex function . The ELBO in variational autoencoders is derived by applying Jensen's inequality to decompose .
Reparameterisation. The reparameterisation trick in VAEs () enables computing gradients of expectations. The gradient is intractable to compute directly, but after reparameterisation it becomes , estimable via sampling.
Score functions. The score function satisfies - its expectation is zero. This identity (proved by differentiating the normalisation condition ) underlies Fisher information, the REINFORCE policy gradient estimator, and Stein's identity used in score-based diffusion models.
1.3 Historical Timeline
HISTORY OF MOMENTS AND EXPECTATION
========================================================================
1654 Pascal-Fermat correspondence: first rigorous treatment of
expected value ("valeur" of a game) in probability
1657 Huygens: De Ratiociniis in Ludo Aleae - published the first
probability textbook with formal expectation calculations
1713 Bernoulli (Jakob): Ars Conjectandi - law of large numbers
(published posthumously); shows sample mean -> E[X]
1730 De Moivre: normal approximation to binomial via moments
1814 Laplace: Theorie Analytique des Probabilites - systematic
use of characteristic functions (Fourier transforms of densities)
1853 Chebyshev: first inequality bounding tails via variance;
rigorous proof of LLN; laid groundwork for moment inequalities
1867 Chebyshev: full variance-based inequality (P(|X-\\mu| \\geq k\\sigma) \\leq 1/k^2)
1894 Pearson: coined "moment" in statistics; introduced skewness
and kurtosis; method of moments estimation
1922 Fisher: likelihood, sufficient statistics, and moment
generating functions as tools of parametric inference
1945 Cramer: large deviation theory; MGF-based tail bounds
(foundations of Hoeffding and Chernoff later work)
1972 Williams: REINFORCE algorithm (score function gradient
estimator = gradient of log-expectation)
2014 Kingma & Ba: Adam optimizer - formal moment-tracking
adaptive gradient method
2014 Kingma & Welling: VAE - reparameterisation trick;
expectations with differentiable sampling
2020 Song et al.: score-based diffusion models - reverse SDE
guidance via score function = \\nabla log p(x)
========================================================================
2. Formal Definition of Expectation
2.1 Expectation for Discrete, Continuous, and Mixed Distributions
The expected value (or expectation or mean) of a random variable is defined as the probability-weighted average of all possible values.
Discrete random variable. If takes values in a countable set with PMF :
provided this sum converges absolutely: . If it does not converge absolutely, does not exist.
Example. For a fair die with :
Continuous random variable. If has PDF :
provided .
Example. For with PDF on :
Mixed distribution. If has a mixed distribution (point mass at plus a continuous density):
where is the point mass probability.
Notation. We write , , , or (physics notation) interchangeably. When the distribution is parameterised by : or .
For AI: The empirical mean is the canonical estimator of . Every forward pass computes a function of the inputs; averaging that function over a batch estimates its expectation. The loss function IS an expectation - we just estimate it from data.
2.2 Existence and Integrability
The expectation exists (is finite) when , i.e., when is integrable. This fails in important cases:
Cauchy distribution. has . The Cauchy distribution has no mean (or any finite moment). A ratio of two independent standard normals follows a Cauchy distribution.
Heavy-tailed distributions. The Pareto distribution for has:
- exists iff
- exists iff
- -th moment exists iff
This matters in practice: internet traffic volumes, earthquake magnitudes, word frequencies in language (Zipf's law), and wealth distributions all exhibit Pareto-like tails. Models that assume finite variance (e.g., CLT-based confidence intervals) can fail badly when applied to such data.
Convergence condition. is well-defined (possibly ) for non-negative (since the integral may diverge to but is unambiguous). For general , write where and . Then , finite only when both are finite.
For AI: In practice, neural network outputs and loss values are bounded (through clipping, normalisation, or the bounded nature of activation functions). But gradient values can have very heavy tails, especially in early training. Gradient clipping is a practical acknowledgment that the gradient may not have finite variance, making the Cauchy-Schwarz and CLT approximations break down.
2.3 Linearity of Expectation
The most powerful property of expectation is its linearity, which holds without any independence assumption:
Theorem (Linearity of Expectation). For any random variables and and constants :
Proof (continuous case). Using the joint density :
where we used (marginalisation from Section03). The discrete case is analogous.
Extension. By induction: for any constants and random variables (not necessarily independent):
Critical point: This holds even when and are dependent. It does NOT extend to products: only when .
Examples demonstrating power of linearity:
Sum of dice. where each is a fair die. Without worrying about dependence (there is none here, but the theorem doesn't require it): .
Binomial mean. . Write where (the indicator that trial succeeds). Then: . No need to compute the full PMF.
Expected number of fixed points. A random permutation of has expected number of fixed points () equal to 1, for any . Proof: .
For AI: Linearity of expectation is the reason we can decompose complex expected losses into sums of simpler expected losses. The expected cross-entropy over a vocabulary of size is - a sum of simpler expectations. The expected gradient of a sum is the sum of the expected gradients, justifying minibatch averaging as a gradient estimator.
2.4 LOTUS - Law of the Unconscious Statistician
A common need: compute for some function when we know the distribution of but not necessarily of directly. LOTUS provides the answer.
Theorem (LOTUS - Law of the Unconscious Statistician). Let be a random variable and a measurable function.
Discrete:
Continuous:
Key insight: We do NOT need the distribution of . We use the distribution of directly. This is why it's called the "unconscious" statistician - you can compute without consciously finding the PDF of .
Proof sketch (discrete case). Let . Grouping terms:
The last step rearranges the double sum.
Examples:
Variance via LOTUS. . Using LOTUS directly on :
Second moment of Exponential. For , using :
Jensen's inequality (preview). For convex , LOTUS combined with the supporting hyperplane property gives . (Full treatment in Section7.)
LOTUS for functions of multiple variables. For jointly distributed with joint density :
For AI: LOTUS is the theorem behind every expectation computation in variational inference. The ELBO contains - an expectation of under . LOTUS says: integrate weighted by , no need to find the distribution of directly.
3. Variance, Standard Deviation, and Higher Moments
3.1 Variance
The variance of measures the expected squared deviation from the mean:
Computational formula. Expanding the square:
This is the Konig-Huygens formula: .
Properties of variance:
- , with equality iff is almost surely constant.
- for any constants .
- (see Section4.4).
- If : .
Proof of property 2.
Note: the constant does not affect variance (shifts don't change spread).
Standard examples:
- : , , . Maximum at .
- : , .
- : , (by construction).
- : , , .
- : (special property).
For AI: Variance quantifies uncertainty. The variance of a model's predictions measures how much predictions vary with the training set - high variance = overfitting. The variance of gradient estimates in SGD determines how noisy the update steps are - high variance slows convergence. Reducing gradient variance is the goal of techniques like control variates, variance reduction in REINFORCE, and importance-weighted estimators.
3.2 Standard Deviation and Coefficient of Variation
The standard deviation has the same units as (variance has squared units). It is the more interpretable spread measure.
The coefficient of variation (CV) normalises the standard deviation by the mean:
CV is dimensionless and measures relative spread. A CV of 0.1 means the standard deviation is 10% of the mean. This is useful when comparing spread across distributions with different scales.
Standardisation. Subtracting the mean and dividing by the standard deviation gives the standardised variable:
which has and .
For AI: Batch Normalisation (Ioffe & Szegedy, 2015) standardises layer activations during training: for each feature, subtract the batch mean and divide by the batch standard deviation. This forces and , then rescales with learnable . Layer Norm and RMS Norm are variations that normalise over the feature dimension rather than the batch dimension - critical for transformers where batch sizes can be 1.
3.3 Raw vs Central Moments
Raw moments (moments about zero):
Central moments (moments about the mean ):
Relationship: The central moments can be expressed in terms of raw moments via the binomial theorem:
For the first four:
- (always - the mean is the center)
Standardised moments divide central moments by , making them dimensionless:
= skewness, = excess kurtosis (kurtosis of normal = 3; excess kurtosis subtracts 3).
3.4 Skewness
Skewness measures the asymmetry of a distribution about its mean:
- (right-skewed / positive skew): Long tail on the right; mean > median > mode. Examples: income distributions, insurance claims, LLM generation probabilities.
- (symmetric): Normal distribution, uniform, any distribution symmetric about its mean.
- (left-skewed / negative skew): Long tail on the left; mean < median < mode. Examples: age at death in developed countries.
SKEWNESS INTUITION
========================================================================
Right-skewed (\\gamma_1 > 0): Left-skewed (\\gamma_1 < 0):
## ##
#### ####
######... ...##########
--+--+--+------ ------+--+--+--+--
Mode < Median < Mean Mean < Median < Mode
Tail pulls mean right Tail pulls mean left
========================================================================
For AI: Gradient distributions in deep networks are often right-skewed - most gradients are small, but occasional large gradients occur. This is why gradient clipping is standard practice: the long right tail causes instability if unconstrained. Token probability distributions from language models are also right-skewed: most tokens have very low probability, while a handful of likely tokens dominate.
Skewness of common distributions:
- : (symmetric by construction)
- : (always right-skewed)
- : (approaches 0 as )
- :
3.5 Kurtosis and Excess Kurtosis
Kurtosis measures the weight of the tails relative to a normal distribution:
Excess kurtosis (the standard in statistics) subtracts the normal baseline of 3:
- (leptokurtic): Heavier tails than Gaussian; more probability in the tails and peak. Examples: Student- distribution, financial returns, gradient norms.
- (mesokurtic): Normal distribution (the baseline).
- (platykurtic): Lighter tails; more uniform. Uniform distribution has .
KURTOSIS AND TAIL WEIGHT
========================================================================
Leptokurtic (\\gamma_2>0): Mesokurtic (\\gamma_2=0): Platykurtic (\\gamma_2<0):
# # ###
### ### #####
##### ##### #######
......... ....... .......
Heavy tails - outliers Normal tails Thin tails
common. Student-t, loss Gaussian Uniform
gradients, finance
========================================================================
For AI: Gradient norm distributions during training are leptokurtic - occasional large-gradient events are far more common than a Gaussian would predict. This motivates both gradient clipping (cap the maximum norm) and heavy-tailed noise models for understanding why SGD generalises. The Student- distribution ( for ) is often used to model heavy-tailed distributions in robust statistics.
Kurtosis of common distributions:
- : (by definition - the reference)
- :
- :
- :
- : for ; infinite for
4. Covariance and Correlation
4.1 Covariance as an Operator
The covariance of two random variables and measures their linear co-movement:
Computational formula:
Proof: .
Properties (bilinearity):
- (symmetric)
- (bilinear, constants drop out)
- (linear in first argument)
- (Cauchy-Schwarz, proved in Section7.3)
Sign interpretation:
- : and tend to be above their means simultaneously.
- : when is above its mean, tends to be below its mean.
- : no linear relationship (but may still be nonlinearly dependent).
Recall from Section03: The full covariance matrix of a random vector collects all pairwise covariances: . The multivariate Gaussian is parameterised by . -> Full treatment: Joint Distributions Section03
4.2 Pearson Correlation Coefficient
The Pearson correlation normalises covariance to remove units:
Theorem: .
Proof via Cauchy-Schwarz. By the Cauchy-Schwarz inequality (proved in Section7.3):
Dividing both sides by : , so .
Boundary cases:
- : for some (perfect positive linear relationship).
- : for some (perfect negative linear relationship).
- : uncorrelated (no linear relationship - but not necessarily independent).
For AI: The correlation coefficient appears in weight matrix analysis. The effective rank of a weight matrix is related to the correlations between its columns. In attention, high correlation between key-query pairs produces high attention weights. In representational similarity analysis (RSA), neural network layers are compared by computing correlation matrices of their activations.
4.3 Independence and Zero Covariance
Theorem. If , then .
Proof. If , then (a characterisation of independence). Therefore .
The converse is FALSE. Zero covariance does not imply independence.
Classic counterexample. Let and . Then:
- (symmetric distribution)
- (odd function, symmetric distribution)
But is completely determined by - knowing tells you exactly. They are maximally dependent!
For jointly Gaussian variables only: Zero covariance DOES imply independence. This is a special property of the Gaussian distribution - it is the unique distribution for which uncorrelated implies independent (for the joint distribution; marginal Gaussians with zero covariance need not be jointly Gaussian).
For AI: Feature selection based on correlation can miss highly informative features that have nonlinear (but zero-covariance) relationships with the target. Mutual information is a better measure of dependence. In contrastive learning (e.g., SimCLR), redundancy reduction methods explicitly decorrelate representations - but decorrelation (zero covariance) and statistical independence are different objectives.
4.4 Variance of Sums
Theorem. For any random variables and :
Proof:
Corollary (independence): If : .
General sum: For :
If all are independent: .
Scaling. For iid with variance :
The variance of the sample mean decreases as - the statistical basis for why larger datasets reduce estimation uncertainty.
For AI: Weight initialisation strategies (Xavier/Glorot, He) are derived from variance propagation. If , then the variance of each output neuron is . To keep variance constant across layers (preventing vanishing/exploding activations): (Xavier) or (He for ReLU). This is the variance-of-sums formula applied to layer activations.
5. Conditional Expectation
5.1 Definition and Basic Properties
The conditional expectation is the expected value of given that takes the specific value . It is a function of , not a number.
Discrete case:
Continuous case:
As a random variable. When we write (without specifying the value of ), we mean the random variable obtained by composing the function with . This is a function of and is therefore itself a random variable.
Basic properties:
- (linearity)
- (taking out known factors)
- If : (conditioning on independent variable doesn't help)
- (tower property - see Section5.2)
Example. Let be jointly uniform on the triangle . From Section03 (Appendix V.1), the conditional density is on . Therefore:
The conditional mean of given is - exactly half of , which makes sense since is uniform on .
5.2 Tower Property (Iterated Expectation)
The tower property (also called the law of iterated expectations or Adam's law) is one of the most useful results in probability:
More generally, for any function :
Proof (continuous case):
Intuition. If you first average within groups defined by , then average those group means weighted by group size, you get the overall mean of .
Example: Expected test score. A class has 40% students from Group A (mean score 75) and 60% from Group B (mean score 85). Overall expected score: . This is exactly the tower property: where is group membership.
For AI: The tower property underlies the EM algorithm. The E-step computes - the expected complete-data log-likelihood, where the expectation is over the latent variable given the observed . The tower property guarantees that maximising increases , the marginal likelihood. In policy gradient methods, - decomposing trajectory returns by initial state.
5.3 Conditional Variance and Law of Total Variance
The conditional variance of given is:
Law of Total Variance (Eve's Law):
This decomposes total variance into:
- Within-group variance: - average variability within each value of .
- Between-group variance: - variability of the group means.
Proof:
Using the tower property twice and writing :
And . Therefore:
For AI: The law of total variance is the mathematical foundation of the bias-variance decomposition (Section8). For a model trained on dataset : total error = expected within-dataset error + between-dataset variance. It also explains why mixture models (GMMs) combine within-component variance and between-component variance.
5.4 AI Applications of Conditional Expectation
Optimal predictor. The function minimises the expected squared error:
Proof: For any ,
The cross term vanishes because , so by the tower property for any . The last term is non-negative. Therefore .
This is profound: the best possible predictor (in MSE sense) is the conditional expectation. Neural networks are universal approximators trained to approximate .
Rao-Blackwell theorem. In estimation theory: if is any unbiased estimator of and is a sufficient statistic, then is also unbiased and has variance . Conditioning on sufficient statistics never increases variance. This is the variance reduction analogue of why attention over relevant context helps.
Attention as conditional expectation. The output of self-attention at position is:
This is the conditional expectation of the value vectors under the attention distribution over key positions. High-entropy attention = averaging many values; low-entropy (sharp) attention = conditioning on one specific value.
6. Moment Generating Functions and Characteristic Functions
6.1 MGF Definition and Basic Properties
The moment generating function (MGF) of a random variable is:
defined for all in an open interval containing 0. If no such interval exists (the integral diverges), the MGF is said not to exist.
Moments from the MGF. Differentiating times and evaluating at gives the -th raw moment:
Proof: (when interchange is valid).
Differentiating times: .
Uniqueness theorem. If for in an open neighbourhood of 0, then and have the same distribution. The MGF uniquely determines the distribution (when it exists).
Existence. The MGF exists when for for some . Heavy-tailed distributions (Cauchy, Pareto with small , log-normal) do NOT have finite MGFs. The characteristic function (Section6.4) always exists and is the preferred tool for such distributions.
6.2 MGF of Common Distributions
Bernoulli():
Check: , . [ok]
Binomial(): (sum of iid Bernoulli)
First moment: . [ok]
Poisson():
Derivation: . , , so . [ok]
Normal():
Derivation: Complete the square in the exponent of . , , . [ok]
Exponential():
Derivation: (converges iff ). , , . [ok]
For AI: MGFs appear in the proof of the Chernoff bound (Section05), which gives exponentially sharp tail bounds. The exponential form is closely related to the log-partition function in the exponential family: . The moments of the sufficient statistic can be computed by differentiating - the MGF and the log-partition function are connected by a change of variables.
6.3 MGF of Sums and the Reproductive Property
Key theorem. If :
Proof: , using independence for the third equality.
This is the MGF version of the convolution theorem. It provides elegant proofs of reproductive properties:
Gaussian reproductive property. If and independently:
This is the MGF of . So .
Poisson reproductive property. If , independently:
So .
6.4 Characteristic Function
The characteristic function of is:
where .
Key advantage: exists for ALL distributions (since always), unlike the MGF which may not exist for heavy-tailed distributions.
Connection to MGF: when the MGF exists. But the characteristic function is defined even when the MGF is not.
Moments from . When moments exist:
Inversion formula. The distribution is uniquely determined by its characteristic function:
(when is continuous). This is the Fourier inversion formula - the characteristic function IS the Fourier transform of the PDF.
For AI: Characteristic functions appear in the analysis of convergence of distributions (Central Limit Theorem proofs use characteristic functions because they always exist). The score-based diffusion model framework uses the score function , which is related to the characteristic function via Fourier analysis. Random Fourier Features (Rahimi & Recht, 2007) approximate kernel functions via random sampling from the characteristic function of the kernel.
6.5 Cumulants and the Cumulant Generating Function
The cumulant generating function (CGF) is the log of the MGF:
Cumulants are the coefficients in the Taylor expansion of :
so .
First four cumulants:
- (mean)
- (variance)
- (third central moment = )
- (excess kurtosis )
Key property. For independent :
Cumulants of a sum of independent variables add - this is the additivity property that makes cumulants more natural than moments for sums.
Normal distribution: . All cumulants for . This characterises the normal distribution - it is the unique distribution with all cumulants beyond the second equal to zero.
7. Jensen's Inequality and Moment Inequalities
7.1 Jensen's Inequality
Definition. A function is convex if for all and :
Geometrically: the chord between any two points lies above the curve. Equivalently (for twice-differentiable ): everywhere.
Theorem (Jensen's Inequality). If is convex and :
Proof (via supporting hyperplane). Since is convex, for any there exists a supporting hyperplane at : a linear function such that for all (where is the subgradient at ). Setting :
Taking expectations of both sides:
Equality condition: iff is linear on the support of , or is almost surely constant.
For concave : (Jensen's inequality reverses).
Common applications:
| Function | Convex/Concave | Jensen gives |
|---|---|---|
| Convex | ||
| Convex | , i.e., | |
| Convex | (variance ) | |
| Concave | ||
| Concave |
7.2 Applications: KL Divergence and ELBO
KL divergence non-negativity. The Kullback-Leibler divergence is:
Theorem (Gibbs' inequality). , with equality iff almost everywhere.
Proof via Jensen:
where we applied Jensen's inequality with the concave function . Therefore .
ELBO derivation via Jensen. For a latent variable model :
where the inequality applies Jensen's to the concave . This lower bound is the ELBO:
The gap between and the ELBO is exactly . Maximising the ELBO tightens this bound.
Log-sum inequality. For non-negative :
This is the discrete version of KL non-negativity via Jensen.
7.3 Cauchy-Schwarz Inequality
Theorem (Cauchy-Schwarz for expectations). For any random variables and :
with equality iff almost surely for some constant .
Proof. For any :
This is a quadratic in that is always non-negative. A quadratic for all iff discriminant . Here , , :
Corollary (). Apply the Cauchy-Schwarz inequality to the centred variables and :
Dividing: .
For AI: Cauchy-Schwarz appears in attention - the dot product is bounded by , motivating the scaling in scaled dot-product attention (). Without this scaling, the dot products can become large in magnitude for high-dimensional keys/queries, causing the softmax to saturate and gradients to vanish.
7.4 Lyapunov Inequality
Theorem (Lyapunov's inequality). For :
In words: the norm of (as a random variable) is non-decreasing in .
Proof. Apply Jensen's inequality with the convex function (convex since ) to the random variable :
Taking powers of both sides: .
Consequence. If the -th moment is finite, all lower moments are finite. If , then as well.
For AI: Lyapunov's inequality underlies the Lyapunov CLT (a variant of the central limit theorem for non-identically distributed variables). In the theory of stochastic gradient descent, the existence of higher moments of the gradient controls the tightness of convergence bounds.
7.5 Preview: Tail Bounds from Moments
The most direct application of moments to probability is bounding how far a random variable can stray from its mean. These are covered fully in Section05, but we preview the key results here.
Preview: Markov's Inequality
For any non-negative random variable and :
Proof: . The mean bounds the probability of large values.
-> Full treatment and applications: Section05 Concentration Inequalities
Preview: Chebyshev's Inequality
For any random variable with mean and variance :
Proof: Apply Markov's inequality to : . The variance bounds how often deviates from its mean by standard deviations.
-> Full treatment and sharper bounds: Section05 Concentration Inequalities
8. Bias-Variance Decomposition
8.1 Statistical Risk and Optimal Predictor
Consider predicting from using a function . The statistical risk (expected squared loss) is:
Theorem. The minimiser of over all measurable functions is the conditional expectation:
and the minimum risk equals the irreducible noise:
Proof: From Section5.4, for any :
And by definition.
The Bayes risk (irreducible error) cannot be reduced by any model, no matter how complex. It is the noise inherent in the prediction problem.
For regression: With where is independent noise with variance , the Bayes risk is .
For AI: The irreducible error is why perfect test accuracy is impossible on noisy datasets. In language modelling, even a perfect model (which exactly learns the true distribution) will have non-zero cross-entropy loss equal to the entropy of the true distribution . GPT-4's perplexity on human text is bounded below by the entropy of human language.
8.2 Bias-Variance-Noise Decomposition
In practice, we learn a model from a finite dataset of samples. The model is a random function - it depends on the random training data. We can decompose the expected prediction error at a new test point :
Proof. Let (expected prediction) and (noisy observation):
The cross term is (since and ). Then:
And . Combining: Bias^2 + Variance + Noise.
BIAS-VARIANCE TRADEOFF
========================================================================
Error Total Error
^ /
| Variance /
| _______________/
| /
| / Bias^2
| / _______________
|_____/__/________________
| Noise
+-------------------------------- Model Complexity ->
Classical view: sweet spot minimises total error
========================================================================
Interpretations:
- High bias: The model is too simple to capture (underfitting). Consistent but wrong. Example: linear model for a quadratic .
- High variance: The model is too complex - it fits training noise (overfitting). Right on average but variable. Example: high-degree polynomial on limited data.
- Noise: Irreducible. The best we can do.
8.3 Double Descent and Modern Deep Learning
The classical bias-variance picture predicts a unique optimal complexity. Modern deep learning violates this: neural networks trained to zero training loss (interpolating the training data, which classical theory predicts should overfit catastrophically) often generalise well. This is the double descent phenomenon.
DOUBLE DESCENT
========================================================================
Test Error
^
| Classical regime Modern regime
| | |
| +----+ | |
| ++ ++ | |
| ++ ++ | +----+
| ++ +--+-----------------+
| | Interpolation threshold
+---------------------------------------- Model Size ->
^ ^
Underfitting Overparameterised
regime regime (good!)
========================================================================
Why does this happen? In overparameterised models:
- Many solutions interpolate the training data.
- Gradient descent (especially with weight decay or implicit regularisation from SGD noise) selects the minimum-norm solution among all interpolating solutions.
- The minimum-norm interpolant has low variance among interpolants - it is the "flattest" fit.
The bias-variance decomposition still holds in double descent, but the variance first rises (at the interpolation threshold, the model just barely interpolates - highly sensitive to training data) and then falls again (overparameterised models have many interpolating solutions, most with low variance).
For AI (2026 context): Large language models like GPT-4, Claude, and Gemini are massively overparameterised. They interpolate (or nearly interpolate) their training data and yet generalise remarkably well - this is the double descent regime. Understanding why overparameterisation helps generalisation remains one of the central open questions in deep learning theory.
8.4 Regularisation as Bias Injection
L2 regularisation (Ridge regression). The regularised estimator minimises:
For linear regression with design matrix (overloading notation): .
Bias-variance analysis of Ridge:
- Bias: is a biased estimator of . Specifically, . Ridge shrinks estimates toward 0, introducing bias.
- Variance: for any . The regularised estimator has smaller variance - it is more stable with respect to perturbations in the training data.
- Trade-off: As increases, bias increases and variance decreases. The optimal minimises total risk.
For AI: Weight decay in neural network training (the most common form of regularisation) adds to the loss, equivalent to L2 regularisation. AdamW implements weight decay correctly by decoupling it from the adaptive learning rate. Understanding the bias-variance trade-off tells us why weight decay helps: it reduces model variance (overfitting) at the cost of some bias.
9. Expectation in ML: Core Applications
9.1 Cross-Entropy Loss as an Expectation
For a -class classification problem, the cross-entropy loss for a single example with true label and model probabilities is:
The expected cross-entropy over the data distribution :
This equals the cross-entropy between the true label distribution and the model's predicted distribution, averaged over inputs .
Connection to KL divergence. For each input :
where is the entropy of the true conditional. Since doesn't depend on , minimising cross-entropy is equivalent to minimising KL divergence - i.e., making the model distribution as close as possible to the true distribution, in the KL sense.
For language models. The cross-entropy loss on a token sequence is:
This is the expected negative log-probability per token - an expectation under the empirical distribution of the training corpus. Minimising this drives the model distribution toward the empirical distribution of human text. The perplexity is : a model with perplexity 50 is "equally surprised" by text as a uniform distribution over 50 tokens.
9.2 ELBO as an Expected Value
The Variational Autoencoder (VAE) introduces an approximate posterior (the encoder) to approximate the intractable true posterior . The Evidence Lower BOund (ELBO) is:
Reconstruction term: - the expected log-likelihood of the observed data given a latent code, averaged over the approximate posterior. This rewards the decoder for reconstructing well from samples of .
KL regularisation term: - penalises the approximate posterior for straying from the prior . For Gaussian encoder :
Gradient computation. The reconstruction term cannot be differentiated through the sampling operation directly. The reparameterisation trick (Section03) writes with , enabling:
This gradient is computable by backpropagation through the deterministic function .
9.3 Policy Gradient (REINFORCE)
In reinforcement learning, an agent with policy (parameterised by ) seeks to maximise the expected return:
where is a trajectory. The REINFORCE gradient is:
Derivation via log-derivative trick (score function):
Since (dynamics don't depend on ), we get the REINFORCE formula.
The score function appears because we differentiated the log of the probability. The key identity underlying this:
(differentiate the normalisation condition to get , then note ).
For RLHF. Reinforcement learning from human feedback uses policy gradients to fine-tune language models. The policy is the LLM: where is the context and is the generated token. The reward comes from a reward model trained on human preferences. REINFORCE and its variants (PPO, GRPO) compute gradients of with respect to the LLM parameters.
9.4 Adam Optimizer as Moment Tracking
The Adam optimizer (Kingma & Ba, 2014) maintains exponential moving averages of the first and second moments of the gradient:
where is the gradient at step .
Bias correction. Since , the early estimates are biased toward zero. The debiased estimates are:
Why does this work? (when gradient is stationary), so dividing by recovers an unbiased estimate of .
Parameter update:
The update is the first moment (direction of average gradient) scaled by - normalising by the root mean square of the gradient. This is adaptive learning rate: parameters with large gradient variance get smaller updates (conservative), parameters with small variance get larger updates (aggressive).
Connection to Fisher Information. The diagonal of the Fisher information matrix is (when gradients are zero-mean). Adam's approximates the diagonal Fisher, making Adam an approximate natural gradient method.
AdamW. Standard Adam conflates weight decay and L2 regularisation (they are equivalent for SGD but not for adaptive methods). AdamW decouples them:
The last term is direct weight decay - not affected by the adaptive scaling. This is the current default for training large language models.
10. Common Mistakes
| # | Mistake | Why It's Wrong | Fix |
|---|---|---|---|
| 1 | (always) | Only true when is linear. For convex : (Jensen). For : . | Apply LOTUS directly to compute . |
| 2 | Assuming without checking independence | True only for independent (or uncorrelated for linear functions). Dependent variables violate this. | Check (uncorrelated) before using this; for full product rule you need . |
| 3 | Confusing variance and standard deviation units | Variance has squared units; std dev has same units as . Mixing them gives nonsense. | Always track units: (squared), (same as ). |
| 4 | (wrong) | The constant shifts location, not spread. Variance is invariant to translation. | - the vanishes. |
| 5 | without independence | This only holds when . For positively correlated : variance is larger. | . |
| 6 | Zero covariance implies independence | False in general. The unit disk example: has but is determined by . | Use mutual information to test full independence. Covariance only measures linear dependence. |
| 7 | Confusing (a number) with (a random variable) | is fixed once is fixed. is random because is random. | Be explicit: ; then is the random variable. |
| 8 | Applying Jensen in the wrong direction for concave | Jensen: convex . For (concave): . | Check second derivative: = convex (Jensen \leq); = concave (Jensen \geq). |
| 9 | Assuming MGF exists for all distributions | Cauchy, Pareto (small ), log-normal: MGFs are infinite. Using MGF-based results for these fails. | Use characteristic function (always exists). Check integrability: for $ |
| 10 | Confusing raw moments and central moments | and differ unless . Kurtosis is , not . | Explicitly write which you mean. For Gaussian: but . |
11. Exercises
Exercise 1 * - LOTUS: Expected Value of a Transformation
Let with PDF for .
(a) Compute directly from the definition.
(b) Using LOTUS, compute .
(c) Compute .
(d) Let . Compute using LOTUS. (Hint: .) What is the domain of for which is finite?
Exercise 2 * - Linearity Without Independence
Let and .
(a) Compute , , and and verify linearity.
(b) Compute . What does this tell you about the linear relationship?
(c) Are and independent? Justify rigorously.
(d) Compute using the formula , and verify numerically.
Exercise 3 * - Moments of the Gaussian
For (standard normal):
(a) Show for all (odd moments vanish).
(b) Using the MGF , find , , and by differentiating.
(c) Verify the general formula .
(d) For , compute the skewness and excess kurtosis .
Exercise 4 ** - Tower Property in Action
A fair coin is flipped. If heads (prob 1/2), . If tails (prob 1/2), .
(a) Using the tower property, compute (let be the coin flip).
(b) Using the law of total variance, compute .
(c) Write down the marginal PMF of (it is a mixture of two Poissons). Verify directly.
(d) AI connection: Mixture-of-experts (MoE) models route tokens to different experts. Each expert has its own output distribution. The total output distribution is a mixture; the tower property computes its moments.
Exercise 5 ** - MGF and Moment Extraction
Let with PDF for .
(a) Derive the MGF: show for .
(b) Use to compute and by differentiating.
(c) Show that the sum of independent variables (same rate ) follows using the MGF multiplicative property.
(d) The chi-squared distribution . What is and ?
Exercise 6 ** - Jensen and KL Divergence
(a) Prove that for any probability distribution over :
with equality iff is uniform. (Hint: Apply Jensen to or use the KL divergence to uniform.)
(b) Show that using Jensen's inequality applied to .
(c) Compute analytically. Verify it equals zero when , .
(d) For the ELBO: show that with gap .
Exercise 7 *** - Bias-Variance Decomposition
Consider estimating from iid samples .
(a) Show that the sample mean is unbiased with variance .
(b) Consider a regularised estimator . Compute its bias and variance as functions of .
(c) The MSE of is Bias^2 + Variance. Find the that minimises MSE. (Hint: it depends on .)
(d) Simulate this: draw 10000 datasets of samples, compute for , plot bias^2, variance, and MSE vs .
Exercise 8 *** - Adam as Moment Estimation
(a) Show that the Adam first-moment estimate satisfies when gradients are iid with mean (stationary gradient assumption). Therefore is unbiased.
(b) Implement a minimal Adam optimizer in NumPy (no PyTorch) and apply it to minimise . Track the first and second moment estimates. Plot , , and over 200 steps.
(c) Show that for a quadratic loss , Adam converges to and the second moment squared gradient. In this case, : Adam reduces to steepest descent with unit step size.
(d) Connect to Fisher information: the Fisher information matrix for has diagonal equal to 1 (the variance of the score). Natural gradient descent uses . How does Adam approximate this for diagonal Fisher?
12. Why This Matters for AI (2026 Perspective)
| Concept | AI/LLM Application | 2026 Context |
|---|---|---|
| - expected loss | Every training objective; cross-entropy, MSE, RLHF reward | All SOTA LLMs (GPT-4, Claude, Gemini) optimise expected log-likelihood; RLHF maximises expected reward from human preference model |
| Linearity of expectation | Gradient of a sum = sum of gradients; minibatch averaging | Distributed training computes gradients on data shards and averages them - justified by linearity |
| Tower property | EM algorithm E-step; policy gradient decomposition | Mixture-of-experts routing in GPT-4, Mixtral uses tower property to compute expected output over router distribution |
| - variance | Uncertainty quantification, BatchNorm/LayerNorm, gradient clipping | LayerNorm is standard in every transformer (BERT, GPT, LLaMA); normalises by mean and variance per token |
| Bias-variance decomposition | Model selection, regularisation, double descent | Understanding why GPT-4-scale models (massively overparameterised) still generalise - double descent regime |
| Jensen's inequality | KL divergence ; ELBO derivation; softmax bounds | VAE encoder (DALL-E 2, Stable Diffusion) optimises ELBO; Jensen is the mathematical foundation |
| MGF / Cumulants | Proof of CLT, Chernoff bounds, tail analysis | Hoeffding/Chernoff bounds used to prove PAC-learning generalisation bounds for language models |
| Adam / moment tracking | Default optimiser for all large-scale training | AdamW trains GPT-4, LLaMA, Claude, Gemini; Adam moment tracking is a direct application of and |
| Score function = | REINFORCE, RLHF policy gradient, diffusion model score | Score-based diffusion (Stable Diffusion, DALL-E 3) is defined by ; trained by denoising score matching |
| Cauchy-Schwarz | Attention scaling , Fisher information bounds | Scaled dot-product attention in every transformer uses scaling derived from variance of dot products |
| Conditional expectation | Attention output = conditional mean; optimal predictor = | Transformers approximate via attention; mechanistic interpretability studies what conditional distributions each head computes |
| Reparameterisation | VAE encoder, diffusion posterior sampling | Stable Diffusion's latent diffusion uses Gaussian reparameterisation for differentiable sampling through the encoder |