The Lebesgue integral and expectation
Expectation is the Lebesgue integral of X with respect to P. Build it from simple functions, prove monotone convergence, Fatou's lemma and dominated convergence, and use them to justify exchanges of limits, derivatives and expectations underlying ML gradient estimators. Study Jensen, Hölder, Cauchy–Schwarz and Minkowski inequalities and Lᵖ spaces.
After this lesson you can
- Build the Lebesgue integral from simple functions and calculate expectations of discrete, continuous and mixed variables using one definition.
- Apply monotone convergence, Fatou's lemma and dominated convergence, and recognize counterexamples when their assumptions fail.
- Justify when ∇θ 𝔼[f(X, θ)] = 𝔼[∇θ f(X, θ)] and derive the pathwise and log-derivative identities.
- Use Jensen, Hölder, Cauchy–Schwarz and Minkowski inequalities and place variables in Lᵖ spaces.
- Calculate expectations using the law of the unconscious statistician.
Before you start
Motivation: averaging without breaking anything
You train a policy that chooses an action and receives a reward . You want to increase , which requires . The gradient is a derivative and expectation is an integral, so the question is whether they can be exchanged: does hold? Two famous tricks say yes. One rewrites the sample as a differentiable function of and fixed noise (the reparameterization of variational autoencoders, or pathwise estimator). The other multiplies by the derivative of the logarithm of the density (the log derivative of REINFORCE and policy gradients, also called the score function estimator). Both exchange derivative and expectation, and both fail if their assumptions do not hold. This lesson identifies those assumptions.
First we need a definition of expectation that does not break down. The familiar Riemann integral has three problems that matter here.
- It does not integrate some functions we want to integrate. The indicator of the rationals has no Riemann integral, yet is a perfectly reasonable probability.
- It does not handle limits well. An increasing, bounded sequence of integrable functions can have a limit that is no longer integrable. Without convergence theorems there is no law of large numbers, no central limit theorem and nothing to justify a Monte Carlo estimator.
- It does not unify the cases. For a discrete variable expectation is a series ; for a continuous one it is ; for a mixed one (the output of a applied to a Gaussian has an atom at and a density elsewhere) neither formula suffices.
The Lebesgue integral fixes all three with one idea: slice the range, not the domain. The lesson has four parts.
- The construction. From simple functions to nonnegative measurable functions and integrable functions, then expectation as an integral with respect to .
- Convergence theorems. Monotone convergence, Fatou’s lemma and dominated convergence, with counterexamples: mass that concentrates, travels or flattens out.
- Differentiation under the integral sign. The exact condition for , and the resulting pathwise and log-derivative identities.
- Inequalities and spaces. Jensen, Hölder, Cauchy–Schwarz and Minkowski, and which variables have moments.
Two ways to slice
To integrate a positive function over there are two ways to divide the area underneath. Riemann cuts vertical strips: divide the domain into pieces, choose a point in each and sum . Lebesgue cuts horizontal layers: divide the range into heights , measure how much of the domain lies above each height, , and sum .
An analogy is counting coins in a drawer. Riemann counts them in their drawer order, one by one, and does well if the drawer is orderly (if varies little between nearby points). Lebesgue first sorts them by value and adds “value times how many”: it does not matter whether they are mixed up.
Two observations about the figure already contain much of the theory.
First, the sum of the layers is the integral of the function , which takes finitely many values. Such functions and their integral are the building blocks. Second, calculating the Lebesgue sum requires measuring sets of the form . This is why the function must be measurable: without measurability of those sets are not in the σ-algebra and cannot be measured. In return, the measure may be anything (probability, length, counting points), and the construction stays the same.
The indicator of behaves as promised in the lesson on Lebesgue measure: every strip contains rationals and irrationals, so the upper Darboux sum equals and the lower one for every partition. But is countable, has measure , and all layers have area . Countable additivity does for the integral what countable covers did for measure.
Simple functions and construction of the integral
Let be a measure space. Useful cases include a probability (and the integral will be expectation), Lebesgue measure on , or counting measure on (and the integral will be a series). We work with values in using the rules and .
This is the sum of the layers in the figure. Before using it we must check that it behaves well; this is the technical part of the construction.
Proof
(a) Each is the disjoint union of the with , and additivity of gives . Sum over . (b) The intersections of the partitions of and form a common partition on which both are constant, with values and ; by (a), , which splits into two sums. (c) On each nonempty cell we have ; sum using (a). (d) Each summand is a measure (a multiple of a restricted measure), and a finite sum of measures is a measure.
∎Two things can already be checked. : the measure of a set is the integral of its indicator. And , the expectation of a constant.
For any measurable function we need simple functions that approximate it from below. This is the same dyadic staircase used to prove the Doob–Dynkin lemma.
Proof
is a finite sum of indicators of measurable sets. Going from to divides each dyadic interval in two and raises the cap from to , so . If , for we have ; if , . If , the error is less than for every from onward.
∎Now define the integral with one idea: the largest sum that fits below.
For a simple function this agrees with the earlier sum by monotonicity (c). The definition requires only measurability and no partition of the domain: ranges over all of it. On the other hand, linearity of the integral is not evident from this definition (a supremum need not be linear); the theorem in the next section will fix that. The properties using monotonicity and simple functions do follow directly.
Proof
(a) Every simple satisfies . (b) If is simple, for each , hence and ; the converse is (a). (c) is simple and lies below , so . (d) has measure at most for every , which tends to . And is a countable union of sets of measure .
∎Inequality (c) is Markov’s inequality, which returns with variance and concentration bounds. Part (d) gives a frequently used rule: a function equal to except on a set of probability zero has expectation , and conversely a nonnegative function with expectation is zero almost surely. That explains why the indicator of has integral .
Monotone convergence and Fatou’s lemma
The first major theorem supplies what Riemann integration did not: the ability to pass to limits.
Proof
is measurable as a countable supremum of measurable functions. In the almost-everywhere case, the set where convergence fails is measurable and null, and by part (b) of the first properties it suffices to replace and with and , which converge everywhere. (Without the assumption that is measurable, the limit might not be measurable unless the measure is complete.) By monotonicity increases and is at most ; let be its limit. It remains to show .
Let be simple with and . The sets are measurable and increase to : where they belong to every , and where we have , hence from some onward. Therefore
where is the measure in part (d) of the simple-functions theorem and the limit uses continuity from below of the measure. Thus for every and every simple , and taking and the supremum over gives .
∎The proof is short and hides the key: is the measure of an increasing set, which is why σ-additivity of (not merely finite additivity) passes to the integral. This is the difference from Riemann integration. The consequences, all immediate, make up half of what we use from the theory.
Proof
(i) This is monotone convergence with . (ii) With canonical and , ; apply linearity for simple functions and pass to the limit. For the signed case, implies , and additivity for nonnegative functions with finite quantities gives equality of the integrals. The inequality follows from . (iii) The partial sums increase.
∎Part (iii) justifies what might look like cheating with series: exchanging and with positive terms is always allowed, without further conditions. With counting measure this is Tonelli’s theorem for double series.
Fatou’s lemma
Sometimes the sequence is not monotone. We can still obtain a bound.
Proof
Let . It is measurable, and for every , so . Taking , monotone convergence gives .
∎The lemma says that mass can be lost in the limit but cannot appear. An extreme case is on . Each has integral and at every point, so . All the mass has concentrated at , a point of measure zero, and the pointwise limit cannot see it.
Expectation as an integral
With the integral constructed, expectation is a one-line definition. Let be a probability space.
With this one definition, probability is a special case of expectation: . A simple variable gives , the familiar expectation of a finite discrete variable. Linearity, monotonicity and the almost-sure rules follow from the previous section without further work. But what we nearly always calculate is for a function of a variable whose law is known, not with in front. This leads to the result used most often throughout the course.
Proof
This is the standard measure-theoretic procedure, also used for Doob–Dynkin: prove the result for each class of functions and move to the next. Indicators. If , by definition of the law. Simple functions. Follow by linearity. Nonnegative functions. If and are the canonical simple approximations, and monotone convergence applies on both sides: . Signed functions. Separate .
∎This result lets us forget , as announced in the lesson on random variables. Three special cases cover all our calculations, and their proofs use the same machine.
- Discrete law, . For , almost surely with respect to (there is no mass outside the atoms), and part (iii) of the consequences of monotone convergence gives ; for signed functions apply it to and . The discrete expectation series is a Lebesgue integral.
- Law with a density, . Then . For this is the definition of density, and the rest follows from the standard machine again (the density as a Radon–Nikodym derivative is studied later).
- Mixed law, with . The integral is linear in the measure (check using indicators and the machine), hence
All three are one integral: there is no need to decide whether the variable is discrete or continuous before calculating. For example, if and , the law of is , with the standard normal density: an atom of mass at and a density (of total mass ) on . Then
with . The final code section checks this with a manually constructed mixed measure.
The layer-cake formula
We now prove the opening figure. The integral of a nonnegative function is the area under its tail .
Proof
Simple functions. If with (the value contributes nothing), is a step function of , and its integral on is . General case. With canonical , for every (if , then from some onward), so by continuity from below of . Monotone convergence in (with Lebesgue measure on ) gives , and the left side is .
∎(The function is decreasing, hence measurable and, where finite, Riemann integrable on every compact interval; the integral in the formula is the Lebesgue integral and agrees with the improper Riemann integral of when the latter exists.) Here we see that and contain the same information on the positive side. This tool calculates expectations without knowing the density: for an integer-valued variable it is , and for an exponential variable with rate it is , without differentiation.
Implementation from scratch: the integral by layers
We implement the Lebesgue integral from the definition, using the layer-cake formula, for a measure represented by points with mass: a discrete measure, one with a density (many fine points) or a mixed one (atoms plus density). The function sorts the values of and sums rectangles with width the jump of and height . It uses no : only measures of sets. We then compare it with the direct sum .
import numpy as np
from fractions import Fraction as Fr
from math import sqrt, pi, exp
def capas(valores, masas):
"""∫ f dμ para f >= 0 como área bajo t -> μ(f > t): se ordenan los valores de f y se suman
rectángulos de ancho (salto de t) y alto μ(f >= siguiente valor)."""
orden = np.argsort(valores)
v = np.asarray(valores, dtype=float)[orden]
m = np.asarray(masas, dtype=float)[orden]
cola = m[::-1].cumsum()[::-1] # cola[j] = μ(f >= v[j])
anchos = np.diff(np.concatenate([[0.0], v])) # v[j] - v[j-1], con v[-1] = 0
return float((anchos * cola).sum())
def directa(valores, masas): # la definición «de siempre»: Σ f(x_j) m_j
return float(np.dot(valores, masas))
# 1) medida discreta: f(x) = x con átomos 0, 1, 2, 4
x = np.array([0.0, 1.0, 2.0, 4.0]); p = np.array([0.15, 0.35, 0.30, 0.20])
print("discreta :", capas(x, p), directa(x, p))
# 2) medida con densidad: N(0, 1) en una rejilla de puntos medios, f = x² (E = 1) y f = max(x, 0)
n = 40000; dx = 18 / n
g = -9 + (np.arange(n) + 0.5) * dx
w = np.exp(-g**2 / 2) / sqrt(2 * pi) * dx
for nombre, f in {"x^2": g**2, "relu": np.maximum(g, 0)}.items():
print(f"continua {nombre:5s}:", round(capas(f, w), 6), round(directa(f, w), 6))
# 3) medida mixta: la ley de Y = relu(Z) es (1/2) δ_0 + densidad φ sobre (0, ∞)
y = g[g > 0]; wy = np.exp(-y**2 / 2) / sqrt(2 * pi) * dx
puntos = np.concatenate([[0.0], y]); masas = np.concatenate([[0.5], wy])
f = np.cos(puntos) + 1 # E[cos Y] + 1, con f >= 0
print("mixta E[cos Y] =", round(capas(f, masas) - 1, 5), " exacto 1/2 + e^(-1/2)/2 =", round(0.5 + 0.5 * exp(-0.5), 5))
print("solo la densidad (olvidar el átomo):", round(float((np.cos(y) * wy).sum()), 5), " <- falta el 1/2 del átomo")
# 4) la indicadora de ℚ: la suma de Riemann depende de las etiquetas; la de Lebesgue no
def riemann_Q(n, frac_racional):
racional = np.arange(n) < round(frac_racional * n) # etiquetas racionales en las primeras franjas
return racional.sum() / n # Σ 1_ℚ(t_i) · (1/n)
for fr in (0.0, 0.25, 0.5, 1.0):
print(f" etiquetas racionales {fr:4.2f}: suma de Riemann (n = 1000) =", riemann_Q(1000, fr))
racionales = sorted({Fr(a, b) for b in range(1, 40) for a in range(0, b + 1)})
eps = 1e-3
longitud = sum(Fr(1, 1000) / 2 ** (k + 1) for k in range(len(racionales))) # exacta, con fracciones
N_q = len(racionales)
print(f" {N_q} racionales de [0, 1] cubiertos por intervalos de longitud ε/2^(k+1): total ε·(1 - 2^(-{N_q})),",
"estrictamente menor que ε:", longitud < Fr(1, 1000))The first three lines show that the layer-cake formula and direct sum agree for a discrete measure () and one with density ( and ). The mixed measure is the case Riemann integration lacks: with a mixed measure the method works without changing a line, and calculating using only the density loses exactly the half in the atom (the sum gives instead of ). Last is the indicator of : tags determine the Riemann sum and any value between and is possible, while the rationals in can be covered with intervals of arbitrarily small total length and their layers have area .
Dominated convergence
Monotonicity is a strong assumption. A different assumption actually holds in models: every function in the sequence lies below the same integrable function.
Proof
Since almost everywhere, is integrable. The sequence is nonnegative (because ) and almost everywhere. By Fatou’s lemma,
and since we may subtract: . Finally .
∎In probability: if almost surely and with , then . The case of constant is called bounded convergence and is most frequently used in practice (probabilities, bounded loss functions). It recovers continuity of probability: if increases to , with dominating function . On a probability space, uniform convergence of to already suffices (because ); on an infinite measure space it does not, as shown by the third sequence in the next figure, which tends to uniformly and has integral .
When domination fails
The assumption is not a formality, and the best way to understand it is to see it break. The pointwise limit of a sequence does not say where the mass is, and mass can escape in three ways. It concentrates at a point of measure zero (), travels to infinity (), or flattens until its supremum tends to (). In all three cases for every and at every point: the integral of the limit is .
We can say precisely why no works. The smallest possible dominating function is the envelope : any dominating every dominates the envelope, which is itself measurable and dominates. Therefore:
(One direction is monotonicity of the integral applied to ; the other takes .) For the envelope equals on , and
the harmonic series: on the envelope behaves like , which is not integrable on . Through the first terms, the integral of the envelope is exactly : it grows slowly, making a dominating function seem plausible at a glance. None exists. With the envelope is , and with it is , again harmonic.
The next cell programs the three sequences as step functions (rectangles with their heights, all exact), calculates and the integral of the envelope , and compares the three theorems using the theoretical sequences: a monotone one (, with ), a dominated one (from the figure, with ), and a Fatou case with strict inequality.
from scipy import integrate
# Sucesiones escalonadas: lista de rectángulos (a, b, altura). Todo es exacto.
def conc(n): return [(0.0, 1.0 / n, float(n))] # n·1_(0,1/n)
def viaja(n): return [(float(n), n + 1.0, 1.0)] # 1_(n,n+1)
def aplana(n): return [(0.0, float(n), 1.0 / n)] # (1/n)·1_(0,n)
def integral(f): return sum((b - a) * h for a, b, h in f)
def integral_envolvente(familia, n):
"""∫ sup_{k<=n} f_k, exacta: se parte la recta en los tramos que delimitan todos los extremos."""
fs = [familia(k) for k in range(1, n + 1)]
pts = sorted({p for f in fs for a, b, _ in f for p in (a, b)})
total = 0.0
for a, b in zip(pts[:-1], pts[1:]):
m = (a + b) / 2
total += (b - a) * max((h for f in fs for x0, x1, h in f if x0 < m < x1), default=0.0)
return total
print(f"{'familia':10s}{'n':>5s}{'∫ f_n':>9s}{'∫ lim':>7s}{'∫ sup_(k<=n) f_k':>18s}")
for nombre, fam in {"concentra": conc, "viaja": viaja, "aplana": aplana}.items():
for n in (1, 10, 100, 200):
print(f"{nombre:10s}{n:5d}{integral(fam(n)):9.3f}{0:7d}{integral_envolvente(fam, n):18.3f}")
print("H_200 =", round(sum(1 / k for k in range(1, 201)), 3), " (la envolvente de 'concentra' y de 'aplana' es H_n)")
# Convergencia monótona: f_n = min(x^(-1/2), n) crece a x^(-1/2) en (0, 1); ∫ f_n = 2 - 1/n -> 2 = ∫ f
for n in (1, 10, 100, 1000):
q = integrate.quad(lambda x: min(x ** -0.5, n), 0, 1, points=[1 / n**2], limit=200)[0]
print(f"MCT n = {n:5d}: ∫ min(x^(-1/2), n) = {q:.5f} (2 - 1/n = {2 - 1/n:.5f})")
# Convergencia dominada: f_n = (1 + x/(n+1))^(-(n+1)) -> e^(-x), dominada por (1 + x/2)^(-2)
for n in (1, 10, 100):
f = lambda x: (1 + x / (n + 1)) ** -(n + 1)
I = integrate.quad(f, 0, np.inf)[0]
L1 = integrate.quad(lambda x: abs(f(x) - np.exp(-x)), 0, np.inf, limit=200)[0]
print(f"DCT n = {n:4d}: ∫ f_n = {I:.5f} (exacto (n+1)/n = {(n+1)/n:.5f}) ∫|f_n - f| = {L1:.5f}")
print("dominante (1 + x/2)^(-2): integral =", integrate.quad(lambda x: (1 + x / 2) ** -2, 0, np.inf)[0])
# Fatou: con n·1_(0,1/n) la desigualdad es estricta
print("Fatou: ∫ liminf f_n = 0 < liminf ∫ f_n =", round(min(integral(conc(n)) for n in range(1, 200)), 6))For all three families, equals in every row and the limit integrates to , but the envelope has integral (with already , and growing without bound) in the concentrating and flattening cases, and in the traveling case. For the monotone sequence, integrals increase toward , the integral of the limit (with a function that is unbounded and still integrable: monotone convergence does not require domination). For the dominated sequence, decreases to (it is exactly ), much stronger than convergence of integrals, as guaranteed by the theorem.
The Riemann integral is a special case
Dominated convergence lets us settle why Lebesgue integration contains Riemann integration in the sense relevant to calculus.
Proof
Let be nested partitions (each refines the preceding one) with , and let be the lower and upper step functions of , with integrals and . Then and with , measurable and bounded by a constant integrable on . By dominated convergence , so almost everywhere and almost everywhere: is measurable for completed measure and , the Riemann integral.
∎The converse is false, as the indicator of showed: Lebesgue integrates more functions, preserving the value where Riemann already worked. The fundamental theorem of calculus remains true in its Riemann form (the one for ), and is generalized only in the lesson on densities and derivatives of measures.
Differentiation under the integral sign
Return to the opening question. Let . The derivative of is the limit of with difference quotient
Therefore , and asking whether the derivative can enter is exactly a dominated-convergence question: is ? Dominating amounts to a Lipschitz condition.
Proof
Let with and . The quotients satisfy almost surely by (iii), and by (ii), with integrable. By dominated convergence . By linearity . Since the sequence is arbitrary, the derivative of at exists and is the limit.
∎Assumption (ii) is Lipschitz continuity in with an integrable constant. The calculus-textbook version, with integrable, implies it by the mean value theorem. The version above is more useful because (iii) requires differentiability only almost surely: a function like , which is not differentiable at but is Lipschitz, qualifies as long as the bad point has probability zero, as for a continuous variable. A function with a jump does not qualify, as the next figure shows.
The counterexample: a jump
Let and . Then , with derivative . But for every the function is locally constant, so almost surely and . The exchange fails, exactly where dominated convergence fails: the difference quotient is
which with is the shifted sequence : mass concentrates on a point of probability zero, the pointwise limit is and the integrals equal . All the variation of with occurs on a set of zero probability, and the almost-sure derivative cannot see it.
After smoothing, is Lipschitz in with constant , so the theorem applies: the pathwise estimator is unbiased for the derivative of , the density of with logistic. But that constant explodes as , and so does the variance. A calculation with change of variable gives
as shown by the figure’s Prediction readout (the approximation is asymptotic: with and it predicts and the exact variance is ). Near the jump we cannot have everything: for each the pathwise estimator is unbiased but its variance explodes like ; at the limit the variance is zero but the bias is total.
The figure’s log derivative needs another step, because here appears in and not in the law of . Transfer it to the law using : then , the parameter is the mean of , and the identity in the next section gives estimator , unbiased for with finite variance ( with ) that does not explode at the jump.
The two gradient identities
With the condition clear, the opening techniques follow as corollaries.
Reparameterization (pathwise). If with of law independent of (for example with ), then and, if is Lipschitz and differentiable at almost surely, and is differentiable at and Lipschitz in with an integrable constant,
For this gives and . This is the gradient backpropagation propagates through sampling in a variational autoencoder. It does not work if has jumps (an indicator, rounding, an ) or, of course, with discrete variables, because is then not differentiable.
Log derivative (score function). If has density with respect to a fixed measure (Lebesgue or counting), . Applying the theorem to measure with integrand , provided exists and is dominated by a -integrable function locally in ,
need not be differentiable, continuous or even known: only evaluable. This is why the method works with nondifferentiable rewards and discrete variables. The price is variance.
With the identity says : the score function has mean zero. This gives the REINFORCE baseline trick: subtracting a constant from does not change the estimator’s mean (because ) and, when well chosen, greatly reduces variance.
Implementation from scratch: three gradient estimators
Estimate with in three ways, and check what happens with a smooth function, one with a kink (the Lipschitz ), and one with a jump. The ground truth is the exact derivative of each expectation.
import numpy as np
from scipy import stats
rng = np.random.default_rng(0)
mu, N = 0.7, 200_000
Z = rng.standard_normal(N) # X = mu + Z con Z ~ N(0, 1)
def fd_crn(f, mu, z, h): # diferencias finitas con números aleatorios comunes: la MISMA z en los dos extremos
return (f(mu + h + z) - f(mu - h + z)) / (2 * h)
def pathwise(df, mu, z): # reparametrización: d/dmu f(mu + z) = f'(mu + z)
return df(mu + z)
def score(f, mu, z): # log-derivada: f(X) · d/dmu log N(X; mu, 1) = f(X) · (X - mu) = f(mu + z) · z
return f(mu + z) * z
def resumen(nombre, g, verdad):
print(f" {nombre:22s} media = {g.mean():8.4f} ± {g.std(ddof=1)/np.sqrt(len(g)):.4f} varianza = {g.var(ddof=1):9.3f} (verdad {verdad:.4f})")
casos = {
"suave: f = sin x + x^2": (lambda x: np.sin(x) + x**2, lambda x: np.cos(x) + 2 * x, np.exp(-0.5) * np.cos(mu) + 2 * mu),
"pliegue: f = max(x, 0)": (lambda x: np.maximum(x, 0), lambda x: (x > 0) * 1.0, stats.norm.cdf(mu)),
"salto: f = 1[x < 1]": (lambda x: (x < 1) * 1.0, lambda x: np.zeros_like(x), -stats.norm.pdf(1 - mu)),
}
for nombre, (f, df, verdad) in casos.items():
print(nombre)
resumen("diferencias (h = 0.01)", fd_crn(f, mu, Z, 0.01), verdad)
resumen("pathwise", pathwise(df, mu, Z), verdad)
resumen("log-derivada", score(f, mu, Z), verdad)
print("\nsalto: las diferencias con números comunes aciertan, pero su varianza explota al bajar h")
f = casos["salto: f = 1[x < 1]"][0]
for h in (0.1, 0.01, 0.001):
g = fd_crn(f, mu, Z, h)
print(f" h = {h:5.3f}: media = {g.mean():8.4f} varianza = {g.var():8.1f} (≈ φ/(2h) = {stats.norm.pdf(1 - mu)/(2 * h):.1f})")The result summarizes the section. With the smooth function, common-random-number differences and pathwise give nearly the same sample (the central difference approximates the same derivative well), while the log derivative is unbiased but has eight times the variance: reparameterization is almost always preferable when applicable. With the kink in , pathwise still works, even though does not exist at (the almost-sure differentiability case). With the jump, pathwise gives exactly (the exchange fails; the mean is the derivative of a constant), whereas the log derivative is correct with variance . Finite differences are correct because they exchange nothing, but their variance grows as : this is the earlier with .
Inequalities: Jensen, Hölder, Cauchy–Schwarz and Minkowski
The Lebesgue integral is linear and monotone, and together these prove nearly all the important inequalities. The first describes how a nonlinear function passes through an expectation.
Proof
Let . Since takes values in , lies between the endpoints of . If equals an endpoint (say, the lower one), has expectation and therefore almost surely; in particular (because ), and the inequality is equality. Otherwise is in the interior of and there is a supporting line: with for every . (It exists because, by convexity, the slopes increase with in , the three-chord lemma; take between the supremum of the slopes to the left of and their infimum to the right.) Then , the right side is integrable and therefore exists. Taking expectations, by monotonicity and linearity,
If is strictly convex, for , and equality requires with nonnegative integrand, hence zero almost surely; this happens only if almost surely. If is concave, apply the preceding result to .
∎The picture is shown in the figure. Points on a convex function’s graph are averaged with weights, and the average of points on a convex curve lies above the curve, inside their convex hull. The height of that average is , while the curve’s height at the average abscissa is .
Everyday consequences:
- and (with and ): the second is .
- for every . For and the gap is (calculated by completing the square in the exponent; this is an exercise).
- for (concave logarithm): the geometric mean does not exceed the arithmetic mean.
- ELBO. Let be a latent-variable model and any density over . Since , concavity of gives
and the gap is exactly (subtract the two sides and use ). Raising the lower bound and bringing it closer to are the same thing; this is the principle of variational autoencoders.
Hölder, Cauchy–Schwarz and Minkowski
For two variables, the expectation of their product is bounded by norms of the factors. Write for , and call and conjugates if .
Proof
(a) If either norm is or the result is trivial. Normalize to (the statement is homogeneous). Young’s inequality says for : by convexity of the exponential, . With and and taking expectations, . (b) Apply (a) with to . (c) For this is the triangle inequality. For , by convexity of , hence if (otherwise there is nothing to prove). Writing and applying Hölder with conjugate exponent to each term,
and divide by (the case is trivial).
∎Cauchy–Schwarz is the most frequently used inequality in the course. With and it gives , meaning the correlation coefficient lies in (see the moments lesson). It is the inequality of with inner product : random variables are vectors, and the correlation between two is the cosine of the angle between their centered versions.
spaces and expectations that do not exist
The norm is finite only if has a moment of order . Variables with that moment form a space.
This is a vector space by Minkowski (and by ), is a norm (if , then almost surely by the first properties, which is why almost surely equal variables are identified), and the product turns into an inner product space. Most important in probability is that these spaces are nested, and Jensen proves it in one line.
Proof
If there is nothing to prove; otherwise is integrable. For the function is convex on , and Jensen gives . Raise to . The case is .
∎The inclusion is usually strict, and depends on finite measure. With for (the Pareto law), the layer-cake formula gives , which is finite if and only if : with , but (and ). On with Lebesgue measure there is no inclusion: and , which is why in both ends need care (near zero and at infinity).
Proof
Choose with and define . By monotone convergence and Minkowski, , so almost surely, and then converges almost surely (the telescoping series converges absolutely) to a random variable . By Fatou’s lemma, for each , . Thus in and, because the sequence is Cauchy, the whole sequence converges to .
∎Completeness lets us discuss limits of variables in and, for , projections: is a Hilbert space, and in the conditional expectation lesson will be the orthogonal projection of onto the subspace of functions of . Least-squares regression is that projection. Convergence in also has its place among the modes of convergence.
Expectations that do not exist
All of this assumes the integral exists, which is not always true. The Cauchy law, with density , is the standard example:
Since , the expectation does not exist, not even as or . Taking a “principal value” (integrating from to and taking ) gives by symmetry, but asymmetric truncation gives another number: it is a property of the procedure, not the variable. The Lebesgue definition settles the issue at its root: the expectation does not exist. There is an equally important intermediate case: a variable may be finite almost surely with infinite expectation, like that of the St Petersburg paradox, with .
In machine learning this is no curiosity. A stochastic gradient with heavy-tailed noise, or a reward with extreme values, can fail the previous theorems’ assumptions and its averages cease to behave: the mean of iid Cauchy variables has the same Cauchy law as each one and does not concentrate, however much increases.
rng = np.random.default_rng(1)
n = 200_000
T = np.arange(1, n + 1)
def curva(x): # media móvil en cuatro instantes
m = np.cumsum(x) / T
return [round(float(m[k - 1]), 3) for k in (100, 1000, 10_000, 200_000)]
normal = rng.standard_normal(n)
cauchy = rng.standard_cauchy(n)
pareto = rng.pareto(1.5, n) + 1 # P(X > x) = x^(-1.5): esperanza finita (= 3), varianza infinita
k = np.floor(np.log2(1 / rng.random(n))) + 1 # San Petersburgo: P(X = 2^k) = 2^(-k)
peter = 2.0 ** k
print(" n = 100 1000 10000 200000")
for nombre, x in {"normal (E = 0)": normal, "Cauchy (no existe)": cauchy, "Pareto 1.5 (E = 3)": pareto, "San Petersburgo (E = ∞)": peter}.items():
print(f"{nombre:24s}", curva(x))
print("\nmáximo de |X| en la muestra de Cauchy:", round(float(np.abs(cauchy).max()), 1), " suma de los 10 mayores de |X| frente a la suma total:",
round(float(np.sort(np.abs(cauchy))[-10:].sum() / np.abs(cauchy).sum()), 3))The normal running means converge to , and Pareto with converges to (slowly, jumping at each extreme value because variance is infinite). The Cauchy mean keeps jumping at (, far from any limit), and the St Petersburg mean does not converge: its typical level grows like (equal to , , and at those four times), with huge jumps whenever a large value appears. In this sample one such jump arrives early and leaves the mean at with , far above ; it then falls slowly until another jump raises it. The last line shows what happens inside the Cauchy sample: ten of observations account for of total absolute value, with extremes in control.
Using libraries
In Python, scipy.integrate.quad integrates a function of one variable, and scipy.stats implements the expectation of a function of a variable with expect, which is LOTUS in practice. For atoms, the mixture is written by hand: a sum over atoms plus an integral over the density component. And sympy performs the Gaussian integral symbolically, allowing an exchange of derivative and expectation to be checked by hand.
import numpy as np
import sympy as sp
from scipy import stats, integrate
N01 = stats.norm()
Eexp = N01.expect(np.exp, lb=-12, ub=12) # acotar el rango: con ±inf, exp(x)·φ(x) da inf·0
print("E[e^X], X ~ N(0,1):", Eexp, " exacto e^(1/2) =", np.exp(0.5))
print("brecha de Jensen :", Eexp - np.exp(N01.mean()), " exacto e^(1/2) - 1 =", np.exp(0.5) - 1)
# esperanza mixta con una sola definición: átomos + densidad. Y = relu(Z): 1/2 δ_0 + φ sobre (0, ∞)
def esperanza_mixta(g, atomos, densidad, intervalo):
return sum(p * g(x) for x, p in atomos) + integrate.quad(lambda y: g(y) * densidad(y), *intervalo)[0]
print("E[(Y+1)^2], Y = relu(Z):", esperanza_mixta(lambda y: (y + 1) ** 2, [(0.0, 0.5)], N01.pdf, (0, np.inf)), " exacto 3/2 + 2/sqrt(2π) =", 1.5 + 2 / np.sqrt(2 * np.pi))
# fórmula de las capas: E[Y] = ∫ P(Y > t) dt, con Y = X^2 y X ~ Pareto(3), y con X ~ exponencial(2)
print("capas, Pareto(3) E[X^2] =", 1.0 + integrate.quad(lambda t: t ** -1.5, 1, np.inf)[0], " (exacto 3)")
print("capas, Exp(2) E[X] =", integrate.quad(lambda t: np.exp(-2 * t), 0, np.inf)[0], " (exacto 1/2)")
# derivar bajo la integral con sympy: d/dμ E[f(X)] frente a E[f'(X)], X ~ N(μ, 1)
mu, x = sp.symbols("mu x", real=True)
dens = sp.exp(-(x - mu) ** 2 / 2) / sp.sqrt(2 * sp.pi)
for f in (x ** 2, x ** 3 - x):
F = sp.simplify(sp.integrate(f * dens, (x, -sp.oo, sp.oo)))
G = sp.simplify(sp.integrate(sp.diff(f, x) * dens, (x, -sp.oo, sp.oo)))
score_ = sp.simplify(sp.integrate(f * (x - mu) * dens, (x, -sp.oo, sp.oo)))
print(f"f = {f}: E[f] = {F}, d/dμ E[f] = {sp.simplify(sp.diff(F, mu))}, E[f'] = {G}, E[f·(X-μ)] = {score_}")For a differentiable function of polynomial growth, the derivative of with respect to , the expectation of (pathwise), and the expectation of (log derivative) are all the same expression: this shows differentiation under the integral and Stein’s lemma from the inside. Outside Python, deep-learning frameworks implement the same thing with different interfaces: in PyTorch, Normal.rsample() performs reparameterization (the gradient passes through the sample), while Normal.sample() together with log_prob performs the log derivative (the gradient passes through the density). Choosing between them means choosing an identity from this lesson.
Common mistakes
Exercises
Step 1 of 4. What two sequences of nonnegative functions can be built from the assumptions?
Step 1 of 4. What line is used, and what property of guarantees its existence?
More than one answer may be correct.
More than one answer may be correct.
estimadores(f, df, mu, z), where z is an array of samples and . Return a tuple (pathwise, score) of two arrays of the same length as z, with per-sample estimates of : the pathwise (using the supplied derivative df) and log derivative . Tests check that both are unbiased for a smooth function and one with a kink, that only the log derivative succeeds with a jump, and that pathwise has lower variance for smooth functions.import numpy as np
def estimadores(f, df, mu, z):
"""Devuelve (pathwise, score): estimaciones por muestra de d/dmu E[f(mu + Z)], Z ~ N(0, 1)."""
# tu código
return np.zeros_like(z), np.zeros_like(z)Summary
- The integral of is , and for a simple function . A signed function is integrable if . The layer-cake formula, , is the picture of horizontal slices.
- Expectation is , and LOTUS gives for a mixed law. A nonnegative variable with expectation is zero almost surely, and Markov bounds tails using expectation.
- Monotone convergence: if , (without further assumptions). Fatou: ; mass can disappear but cannot appear. Dominated convergence: and give .
- An integrable dominating function exists if and only if . Without one, mass can concentrate, travel, or flatten, and the limit of integrals is not the integral of the limit; the theorem is sufficient, not necessary.
- Differentiation under the integral holds if is Lipschitz in with an integrable constant and differentiable almost surely. It fails with jumps (): . Pathwise: . Log derivative: , without differentiating and with greater variance.
- Jensen: if is convex (reversed if concave); this gives and the ELBO. Hölder, Cauchy–Schwarz and Minkowski give the norm .
- is complete, and in probability if . is a Hilbert space, with . Some variables have no expectation (Cauchy), while others have infinite expectation but are finite almost surely (St Petersburg); their averages do not concentrate.