Module contents
Lesson 5 of 24Core 115 min

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 πθ\pi_\theta that chooses an action aa and receives a reward R(a)R(a). You want to increase J(θ)=Ea∼πθ[R(a)]J(\theta) = \E_{a \sim \pi_\theta}[R(a)], which requires ∇θJ\grad_\theta J. The gradient is a derivative and expectation is an integral, so the question is whether they can be exchanged: does ∇θE[R]=E[∇θR]\grad_\theta \E[R] = \E[\grad_\theta R] hold? Two famous tricks say yes. One rewrites the sample as a differentiable function of θ\theta 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.

  1. It does not integrate some functions we want to integrate. The indicator of the rationals has no Riemann integral, yet P(X∈Q)\Pr(X \in \Q) is a perfectly reasonable probability.
  2. 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.
  3. It does not unify the cases. For a discrete variable expectation is a series ∑ixipi\sum_i x_i p_i; for a continuous one it is ∫xf(x)  ⁣dx\int x f(x)\,\dd x; for a mixed one (the output of a ReLU⁡\relu applied to a Gaussian has an atom at 00 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 P\Pr.
  • 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 ∇θE=E∇θ\grad_\theta \E = \E \grad_\theta, and the resulting pathwise and log-derivative identities.
  • Inequalities and LpL^p spaces. Jensen, Hölder, Cauchy–Schwarz and Minkowski, and which variables have moments.

Two ways to slice

To integrate a positive function ff over [0,1][0, 1] there are two ways to divide the area underneath. Riemann cuts vertical strips: divide the domain into nn pieces, choose a point in each and sum f(ti)⋅(anchura)f(t_i) \cdot (\text{anchura}). Lebesgue cuts horizontal layers: divide the range into heights 0<t1<t2<⋯0 < t_1 < t_2 < \cdots, measure how much of the domain lies above each height, λ({f≥tk})\lambda(\{f \ge t_k\}), and sum (grosor)⋅λ({f≥tk})(\text{grosor}) \cdot \lambda(\{f \ge t_k\}).

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

InteractiveVertical or horizontal slices
Riemann: the domain is sliced into nn vertical strips
t*
Lebesgue: the range is sliced into mm layers and each {f≥t}\{f \ge t\} is measured
λ = 0.60
  • Riemann strips (height ff at the tag)
  • Lebesgue layers (width λ(f≥t)\lambda(f \ge t))
  • graph of ff / measure of {f≥t}\{f \ge t\}
7
Tag in each strip
6
0.45
Riemann with n=7n = 7 tags0.4929
Darboux: lower · upper0.436 · 0.600
Lebesgue: ∫sm\int s_m with m=6m = 60.4000
∫f  ⁣dλ\int f \, \dd\lambda0.5150
λ(f≥t∗)\lambda(f \ge t^*)0.600
Left: the Riemann sum with nn vertical strips and one tag per strip. Right: the Lebesgue sum with mm layers, each with width equal to the measure of the level set {f≥t}\{f \ge t\} (the set marked in turquoise on the left xx axis by probe t∗t^*). Start with the four-value staircase: for which mm is the Lebesgue sum exact? What about the Riemann sum with nn strips? Switch to the oscillating function and compare how many strips and layers are needed to get within 0.010.01. Then choose the indicator of the rationals: the Riemann strips give any value between 00 and 11 depending on their tags (and what about Darboux sums?), while all Lebesgue layers have measure 00.

Two observations about the figure already contain much of the theory.

First, the sum of the layers is the integral of the function sm=⌊mf⌋/m≤fs_m = \lfloor m f \rfloor / m \le f, which takes finitely many values. Such functions and their integral ∑kak μ({s=ak})\sum_k a_k\,\mu(\{s = a_k\}) are the building blocks. Second, calculating the Lebesgue sum requires measuring sets of the form {f≥t}\{f \ge t\}. This is why the function must be measurable: without measurability of ff those sets are not in the σ-algebra and cannot be measured. In return, the measure μ\mu may be anything (probability, length, counting points), and the construction stays the same.

The indicator of Q\Q behaves as promised in the lesson on Lebesgue measure: every strip contains rationals and irrationals, so the upper Darboux sum equals 11 and the lower one 00 for every partition. But {f≥t}=Q∩[0,1]\{f \ge t\} = \Q \cap [0, 1] is countable, has measure 00, and all layers have area 00. Countable additivity does for the integral what countable covers did for measure.

Simple functions and construction of the integral

Let (Ω,F,μ)(\Omega, \mathcal{F}, \mu) be a measure space. Useful cases include a probability P\Pr (and the integral will be expectation), Lebesgue measure λ\lambda on R\R, or counting measure on N\N (and the integral will be a series). We work with values in [0,∞][0, \infty] using the rules 0⋅∞=00 \cdot \infty = 0 and a+∞=∞a + \infty = \infty.

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 AiA_i is the disjoint union of the BjB_j with bj=aib_j = a_i, and additivity of μ\mu gives aiμ(Ai)=∑j:bj=aibjμ(Bj)a_i \mu(A_i) = \sum_{j : b_j = a_i} b_j \mu(B_j). Sum over ii. (b) The intersections Ai∩BjA_i \cap B_j of the partitions of ss and tt form a common partition on which both are constant, with values aia_i and bjb_j; by (a), ∫(αs+βt)=∑i,j(αai+βbj)μ(Ai∩Bj)\int(\alpha s + \beta t) = \sum_{i,j} (\alpha a_i + \beta b_j)\mu(A_i \cap B_j), which splits into two sums. (c) On each nonempty cell Ai∩BjA_i \cap B_j we have ai≤bja_i \le b_j; sum using (a). (d) Each summand E↦aiμ(Ai∩E)E \mapsto a_i \mu(A_i \cap E) is a measure (a multiple of a restricted measure), and a finite sum of measures is a measure. ■\blacksquare

∎

Two things can already be checked. ∫1A  ⁣dμ=μ(A)\int \ind_A \,\dd\mu = \mu(A): the measure of a set is the integral of its indicator. And ∫a 1Ω  ⁣dμ=a μ(Ω)\int a\,\ind_\Omega\,\dd\mu = a\,\mu(\Omega), the expectation of a constant.

For any measurable function f≥0f \ge 0 we need simple functions that approximate it from below. This is the same dyadic staircase used to prove the Doob–Dynkin lemma.

Proof

sn=∑k=0n2n−1k2−n1{k2−n≤f<(k+1)2−n}+n 1{f≥n}s_n = \sum_{k=0}^{n 2^n - 1} k 2^{-n} \ind\{k 2^{-n} \le f < (k+1) 2^{-n}\} + n\,\ind\{f \ge n\} is a finite sum of indicators of measurable sets. Going from nn to n+1n+1 divides each dyadic interval in two and raises the cap from nn to n+1n + 1, so sn≤sn+1s_n \le s_{n+1}. If f(ω)<∞f(\omega) < \infty, for n>f(ω)n > f(\omega) we have 0≤f(ω)−sn(ω)<2−n0 \le f(\omega) - s_n(\omega) < 2^{-n}; if f(ω)=∞f(\omega) = \infty, sn(ω)=n→∞s_n(\omega) = n \to \infty. If f≤Mf \le M, the error is less than 2−n2^{-n} for every ω\omega from n>Mn > M onward. ■\blacksquare

∎

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: sup⁡\sup 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 s≤fs \le f satisfies s≤gs \le g. (b) If s≤fs \le f is simple, μ(Ai∩N)=0\mu(A_i \cap N) = 0 for each ii, hence ∫s=∑aiμ(Ai∩Nc)=∫s 1Nc\int s = \sum a_i \mu(A_i \cap N^c) = \int s\,\ind_{N^c} and s 1Nc≤f 1Ncs\,\ind_{N^c} \le f\,\ind_{N^c}; the converse is (a). (c) c 1{f≥c}c\,\ind_{\{f \ge c\}} is simple and lies below ff, so c μ(f≥c)≤∫fc\,\mu(f \ge c) \le \int f. (d) {f=∞}⊂{f≥c}\{f = \infty\} \subset \{f \ge c\} has measure at most ∫f/c\int f / c for every cc, which tends to 00. And {f>0}=⋃k{f≥1/k}\{f > 0\} = \bigcup_k \{f \ge 1/k\} is a countable union of sets of measure ≤k∫f=0\le k \int f = 0. ■\blacksquare

∎

Inequality (c) is Markov’s inequality, which returns with variance and concentration bounds. Part (d) gives a frequently used rule: a function equal to 00 except on a set of probability zero has expectation 00, and conversely a nonnegative function with expectation 00 is zero almost surely. That explains why the indicator of Q\Q has integral λ(Q∩[0,1])=0\lambda(\Q \cap [0, 1]) = 0.

Monotone convergence and Fatou’s lemma

The first major theorem supplies what Riemann integration did not: the ability to pass to limits.

Proof

f=sup⁡nfnf = \sup_n f_n is measurable as a countable supremum of measurable functions. In the almost-everywhere case, the set NN where convergence fails is measurable and null, and by part (b) of the first properties it suffices to replace fnf_n and ff with fn1Ncf_n \ind_{N^c} and f1Ncf \ind_{N^c}, which converge everywhere. (Without the assumption that ff is measurable, the limit might not be measurable unless the measure is complete.) By monotonicity ∫fn\int f_n increases and is at most ∫f\int f; let LL be its limit. It remains to show L≥∫fL \ge \int f.

Let ss be simple with 0≤s≤f0 \le s \le f and c∈(0,1)c \in (0, 1). The sets En={fn≥c s}E_n = \{f_n \ge c\,s\} are measurable and increase to Ω\Omega: where s(ω)=0s(\omega) = 0 they belong to every EnE_n, and where s(ω)>0s(\omega) > 0 we have c s(ω)<s(ω)≤f(ω)c\,s(\omega) < s(\omega) \le f(\omega), hence fn(ω)>c s(ω)f_n(\omega) > c\,s(\omega) from some nn onward. Therefore

∫fn  ≥  ∫fn1En  ≥  c∫s 1En=c ν(En)  ⟶  c ν(Ω)=c∫s,\int f_n \;\ge\; \int f_n \ind_{E_n} \;\ge\; c \int s\,\ind_{E_n} = c\,\nu(E_n) \;\longrightarrow\; c\,\nu(\Omega) = c \int s,

where ν\nu is the measure in part (d) of the simple-functions theorem and the limit uses continuity from below of the measure. Thus L≥c∫sL \ge c \int s for every c<1c < 1 and every simple s≤fs \le f, and taking c↑1c \uparrow 1 and the supremum over ss gives L≥∫fL \ge \int f. ■\blacksquare

∎

The proof is short and hides the key: ∫s 1En\int s\,\ind_{E_n} is the measure of an increasing set, which is why σ-additivity of μ\mu (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 fn=snf_n = s_n. (ii) With canonical sn↑fs_n \uparrow f and tn↑gt_n \uparrow g, αsn+βtn↑αf+βg\alpha s_n + \beta t_n \uparrow \alpha f + \beta g; apply linearity for simple functions and pass to the limit. For the signed case, (f+g)+−(f+g)−=f+−f−+g+−g−(f + g)^+ - (f + g)^- = f^+ - f^- + g^+ - g^- implies (f+g)++f−+g−=(f+g)−+f++g+(f + g)^+ + f^- + g^- = (f + g)^- + f^+ + g^+, and additivity for nonnegative functions with finite quantities gives equality of the integrals. The inequality follows from −∣f∣≤f≤∣f∣-\abs{f} \le f \le \abs{f}. (iii) The partial sums increase. ■\blacksquare

∎

Part (iii) justifies what might look like cheating with series: exchanging ∑\sum and ∫\int 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 gk=inf⁡n≥kfng_k = \inf_{n \ge k} f_n. It is measurable, gk↑lim inf⁡nfng_k \uparrow \liminf_n f_n and gk≤fng_k \le f_n for every n≥kn \ge k, so ∫gk≤inf⁡n≥k∫fn\int g_k \le \inf_{n \ge k} \int f_n. Taking k→∞k \to \infty, monotone convergence gives ∫lim inf⁡fn=lim⁡k∫gk≤lim inf⁡n∫fn\int \liminf f_n = \lim_k \int g_k \le \liminf_n \int f_n. ■\blacksquare

∎

The lemma says that mass can be lost in the limit but cannot appear. An extreme case is fn=n 1(0,1/n)f_n = n\,\ind_{(0, 1/n)} on ((0,1),λ)((0, 1), \lambda). Each fnf_n has integral 11 and fn→0f_n \to 0 at every point, so ∫lim inf⁡fn=0<1=lim inf⁡∫fn\int \liminf f_n = 0 < 1 = \liminf \int f_n. All the mass has concentrated at x=0x = 0, 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 (Ω,F,P)(\Omega, \mathcal{F}, \Pr) be a probability space.

With this one definition, probability is a special case of expectation: E[1A]=P(A)\E[\ind_A] = \Pr(A). A simple variable gives E[X]=∑iaiP(X=ai)\E[X] = \sum_i a_i \Pr(X = a_i), 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 E[g(X)]\E[g(X)] for a function of a variable whose law is known, not E[X]\E[X] with Ω\Omega 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 g=1Bg = \ind_B, E[1B(X)]=P(X∈B)=PX(B)=∫1B  ⁣dPX\E[\ind_B(X)] = \Pr(X \in B) = \Pr_X(B) = \int \ind_B \,\dd\Pr_X by definition of the law. Simple functions. Follow by linearity. Nonnegative functions. If g≥0g \ge 0 and sn↑gs_n \uparrow g are the canonical simple approximations, sn(X)↑g(X)s_n(X) \uparrow g(X) and monotone convergence applies on both sides: E[g(X)]=lim⁡E[sn(X)]=lim⁡∫sn  ⁣dPX=∫g  ⁣dPX\E[g(X)] = \lim \E[s_n(X)] = \lim \int s_n \,\dd\Pr_X = \int g \,\dd\Pr_X. Signed functions. Separate g=g+−g−g = g^+ - g^-. ■\blacksquare

∎

This result lets us forget Ω\Omega, as announced in the lesson on random variables. Three special cases cover all our calculations, and their proofs use the same machine.

  • Discrete law, PX=∑ipiδxi\Pr_X = \sum_i p_i \delta_{x_i}. For g≥0g \ge 0, g=∑ig(xi)1{xi}g = \sum_i g(x_i) \ind_{\{x_i\}} almost surely with respect to PX\Pr_X (there is no mass outside the atoms), and part (iii) of the consequences of monotone convergence gives E[g(X)]=∑ipi g(xi)\E[g(X)] = \sum_i p_i\, g(x_i); for signed functions apply it to g+g^+ and g−g^-. The discrete expectation series is a Lebesgue integral.
  • Law with a density, PX(B)=∫Bf  ⁣dλ\Pr_X(B) = \int_B f \,\dd\lambda. Then E[g(X)]=∫g(x)f(x)  ⁣dx\E[g(X)] = \int g(x) f(x)\,\dd x. For g=1Bg = \ind_B 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, PX=∑ipiδxi+μac\Pr_X = \sum_i p_i \delta_{x_i} + \mu_{\text{ac}} with μac(B)=∫Bf  ⁣dλ\mu_{\text{ac}}(B) = \int_B f\,\dd\lambda. The integral is linear in the measure (check using indicators and the machine), hence
E[g(X)]=∑ipi g(xi)+∫g(x)f(x)  ⁣dx.\E[g(X)] = \sum_i p_i\, g(x_i) + \int g(x) f(x)\,\dd x.

All three are one integral: there is no need to decide whether the variable is discrete or continuous before calculating. For example, if Z∼N(0,1)Z \sim \Normal(0, 1) and Y=ReLU⁡(Z)=max⁡(Z,0)Y = \relu(Z) = \max(Z, 0), the law of YY is PY(B)=121B(0)+∫B∩(0,∞)φ(y)  ⁣dy\Pr_Y(B) = \tfrac12 \ind_B(0) + \int_{B \cap (0, \infty)} \varphi(y)\,\dd y, with φ\varphi the standard normal density: an atom of mass 12\tfrac12 at 00 and a density (of total mass 12\tfrac12) on (0,∞)(0, \infty). Then

E[Y]=0⋅12+∫0∞y φ(y)  ⁣dy=φ(0)=12π≈0.3989,E[Y2]=12,\E[Y] = 0 \cdot \tfrac12 + \int_0^\infty y\,\varphi(y)\,\dd y = \varphi(0) = \frac{1}{\sqrt{2\pi}} \approx 0.3989, \qquad \E[Y^2] = \tfrac12 ,

with Var⁡(Y)=12−12π≈0.341\Var(Y) = \tfrac12 - \tfrac{1}{2\pi} \approx 0.341. 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 t↦μ(f>t)t \mapsto \mu(f > t).

Proof

Simple functions. If s=∑iai1Ais = \sum_i a_i \ind_{A_i} with ai>0a_i > 0 (the value 00 contributes nothing), μ(s>t)=∑iμ(Ai) 1{t<ai}\mu(s > t) = \sum_i \mu(A_i)\,\ind\{t < a_i\} is a step function of tt, and its integral on (0,∞)(0, \infty) is ∑iμ(Ai) ai=∫s\sum_i \mu(A_i)\,a_i = \int s. General case. With canonical sn↑fs_n \uparrow f, {sn>t}↑{f>t}\{s_n > t\} \uparrow \{f > t\} for every tt (if f(ω)>tf(\omega) > t, then sn(ω)>ts_n(\omega) > t from some nn onward), so μ(sn>t)↑μ(f>t)\mu(s_n > t) \uparrow \mu(f > t) by continuity from below of μ\mu. Monotone convergence in tt (with Lebesgue measure on (0,∞)(0, \infty)) gives ∫μ(sn>t)  ⁣dt↑∫μ(f>t)  ⁣dt\int \mu(s_n > t)\,\dd t \uparrow \int \mu(f > t)\,\dd t, and the left side is ∫sn↑∫f\int s_n \uparrow \int f. ■\blacksquare

∎

(The function t↦μ(f>t)t \mapsto \mu(f > t) 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 m03m03 when the latter exists.) Here we see that P(X>t)\Pr(X > t) and E[X]\E[X] contain the same information on the positive side. This tool calculates expectations without knowing the density: for an integer-valued variable X≥0X \ge 0 it is E[X]=∑k≥1P(X≥k)\E[X] = \sum_{k \ge 1} \Pr(X \ge k), and for an exponential variable with rate λ\lambda it is ∫0∞e−λt  ⁣dt=1/λ\int_0^\infty e^{-\lambda t}\,\dd t = 1/\lambda, 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 ff and sums rectangles with width the jump of tt and height μ(f>t)\mu(f > t). It uses no  ⁣dx\dd x: only measures of sets. We then compare it with the direct sum ∑f(xj)mj\sum f(x_j) m_j.

[ ]The Lebesgue integral by layers: discrete, continuous and mixedBrowser
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 (1.751.75) and one with density (E[Z2]=1\E[Z^2] = 1 and E[ReLU⁡(Z)]=0.3989\E[\relu(Z)] = 0.3989). 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 0.30330.3033 instead of 0.80330.8033). Last is the indicator of Q\Q: tags determine the Riemann sum and any value between 00 and 11 is possible, while the rationals in [0,1][0, 1] can be covered with intervals of arbitrarily small total length and their layers have area 00.

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 ∣f∣≤g\abs{f} \le g almost everywhere, ff is integrable. The sequence hn=2g−∣fn−f∣h_n = 2g - \abs{f_n - f} is nonnegative (because ∣fn−f∣≤∣fn∣+∣f∣≤2g\abs{f_n - f} \le \abs{f_n} + \abs{f} \le 2g) and hn→2gh_n \to 2g almost everywhere. By Fatou’s lemma,

∫2g  ≤  lim inf⁡n∫(2g−∣fn−f∣)  =  ∫2g−lim sup⁡n∫∣fn−f∣,\int 2g \;\le\; \liminf_n \int \big(2g - \abs{f_n - f}\big) \;=\; \int 2g - \limsup_n \int \abs{f_n - f},

and since ∫2g<∞\int 2g < \infty we may subtract: lim sup⁡n∫∣fn−f∣≤0\limsup_n \int \abs{f_n - f} \le 0. Finally ∣∫fn−∫f∣≤∫∣fn−f∣\abs{\int f_n - \int f} \le \int \abs{f_n - f}. ■\blacksquare

∎

In probability: if Xn→XX_n \to X almost surely and ∣Xn∣≤Y\abs{X_n} \le Y with E[Y]<∞\E[Y] < \infty, then E[Xn]→E[X]\E[X_n] \to \E[X]. The case of constant YY is called bounded convergence and is most frequently used in practice (probabilities, bounded loss functions). It recovers continuity of probability: 1An→1A\ind_{A_n} \to \ind_A if AnA_n increases to AA, with dominating function 11. On a probability space, uniform convergence of fnf_n to ff already suffices (because ∣∫fn−∫f∣≤sup⁡∣fn−f∣\abs{\int f_n - \int f} \le \sup \abs{f_n - f}); on an infinite measure space it does not, as shown by the third sequence in the next figure, which tends to 00 uniformly and has integral 11.

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 (n 1(0,1/n)n\,\ind_{(0,1/n)}), travels to infinity (1(n,n+1)\ind_{(n, n+1)}), or flattens until its supremum tends to 00 (1n1(0,n)\tfrac1n \ind_{(0, n)}). In all three cases ∫fn=1\int f_n = 1 for every nn and fn→0f_n \to 0 at every point: the integral of the limit is 00.

InteractiveEscaping mass
fn=n 1(0, 1/n)f_n = n\,\ind_{(0,\,1/n)} (blue), its pointwise limit (gray), envelope sup⁡k≤nfk\sup_{k \le n} f_k (purple) and your candidate gg (red)
g(x)=c x−αg(x) = c\,x^{-\alpha} on (0,1](0, 1]
Verdict. The smallest dominating function, sup⁡kfk≈1/x\sup_k f_k \approx 1/x, is not integrable. Integral of the envelope: Hn=1+12+⋯+1nH_n = 1 + \tfrac12 + \cdots + \tfrac1n.
  • fnf_n
  • pointwise limit
  • envelope sup⁡k≤nfk\sup_{k \le n} f_k
  • candidate gg
n = 1
1.00
0.50
∫fn  ⁣dx\int f_n \, \dd x with n=1n = 11.0000
∫lim⁡nfn  ⁣dx\int \lim_n f_n \, \dd x0.0000
max⁡fn\max f_n1.000
∫sup⁡k≤nfk  ⁣dx\int \sup_{k \le n} f_k \, \dd x1.000
Your gg: dominates all fnf_nno
Your gg: ∫g  ⁣dx\int g \, \dd x2.000
Dominated convergence assumptionsare not satisfied by this g
Advance nn with the player. In the first three sequences the pointwise limit is 00 (gray line) and the integral is always 11. The purple envelope is sup⁡k≤nfk\sup_{k \le n} f_k, the smallest function dominating the first nn: watch its integral grow. Then try to dominate them with g=c x−αg = c\,x^{-\alpha}: can you make g≥fng \ge f_n for every nn and also make gg integrable? In the concentrating case, with α<1\alpha < 1 the candidate is integrable near 00 but does not dominate, while for α≥1\alpha \ge 1 it dominates but is no longer integrable. For the traveling or flattening cases the reverse happens because the problem is at infinity. Compare with the two dominated sequences, where a valid gg exists.

We can say precisely why no gg works. The smallest possible dominating function is the envelope sup⁡n∣fn∣\sup_n \abs{f_n}: any gg dominating every fnf_n dominates the envelope, which is itself measurable and dominates. Therefore:

(One direction is monotonicity of the integral applied to sup⁡n∣fn∣≤g\sup_n \abs{f_n} \le g; the other takes g=sup⁡n∣fn∣g = \sup_n \abs{f_n}.) For fn=n 1(0,1/n)f_n = n\,\ind_{(0, 1/n)} the envelope equals nn on [1/(n+1),1/n)[1/(n+1), 1/n), and

∫sup⁡nfn  ⁣dλ=∑n≥1n(1n−1n+1)=∑n≥11n+1=∞,\int \sup_n f_n \,\dd\lambda = \sum_{n \ge 1} n \Big(\frac1n - \frac1{n+1}\Big) = \sum_{n \ge 1} \frac{1}{n+1} = \infty ,

the harmonic series: on (0,1)(0, 1) the envelope behaves like 1/x1/x, which is not integrable on 00. Through the first nn terms, the integral of the envelope is exactly Hn=1+12+⋯+1n≈ln⁡n+0.577H_n = 1 + \tfrac12 + \cdots + \tfrac1n \approx \ln n + 0.577: it grows slowly, making a dominating function seem plausible at a glance. None exists. With 1(n,n+1)\ind_{(n, n+1)} the envelope is 1(1,∞)\ind_{(1, \infty)}, and with 1n1(0,n)\tfrac1n \ind_{(0, n)} it is 1/⌈x⌉1/\lceil x \rceil, again harmonic.

The next cell programs the three sequences as step functions (rectangles with their heights, all exact), calculates ∫fn\int f_n and the integral of the envelope ∫sup⁡k≤nfk\int \sup_{k \le n} f_k, and compares the three theorems using the theoretical sequences: a monotone one (min⁡(x−1/2,n)↑x−1/2\min(x^{-1/2}, n) \uparrow x^{-1/2}, with ∫fn=2−1/n\int f_n = 2 - 1/n), a dominated one (from the figure, with ∫∣fn−f∣→0\int \abs{f_n - f} \to 0), and a Fatou case with strict inequality.

[ ]The three convergence theorems and their counterexamplesBrowser
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, ∫fn\int f_n equals 11 in every row and the limit integrates to 00, but the envelope has integral HnH_n (with n=200n = 200 already 5.8785.878, and growing without bound) in the concentrating and flattening cases, and nn in the traveling case. For the monotone sequence, integrals increase 1,1.9,1.99,1.9991, 1.9, 1.99, 1.999 toward 22, the integral of the limit (with a function that is unbounded and still integrable: monotone convergence does not require domination). For the dominated sequence, ∫∣fn−f∣\int \abs{f_n - f} decreases to 1,0.1,0.011, 0.1, 0.01 (it is exactly 1/n1/n), 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 PkP_k be nested partitions (each refines the preceding one) with U(f,Pk)−L(f,Pk)→0U(f, P_k) - L(f, P_k) \to 0, and let ℓk≤f≤uk\ell_k \le f \le u_k be the lower and upper step functions of PkP_k, with integrals L(f,Pk)L(f, P_k) and U(f,Pk)U(f, P_k). Then ℓk↑ℓ\ell_k \uparrow \ell and uk↓uu_k \downarrow u with ℓ≤f≤u\ell \le f \le u, measurable and bounded by a constant integrable on [a,b][a, b]. By dominated convergence ∫(u−ℓ)=lim⁡(U(f,Pk)−L(f,Pk))=0\int (u - \ell) = \lim (U(f, P_k) - L(f, P_k)) = 0, so u=ℓu = \ell almost everywhere and f=ℓf = \ell almost everywhere: ff is measurable for completed measure and ∫f=∫ℓ=lim⁡L(f,Pk)\int f = \int \ell = \lim L(f, P_k), the Riemann integral. ■\blacksquare

∎

The converse is false, as the indicator of Q\Q 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 m03m03), and is generalized only in the lesson on densities and derivatives of measures.

Differentiation under the integral sign

Return to the opening question. Let F(θ)=E[f(X,θ)]=∫f(x,θ) PX( ⁣dx)F(\theta) = \E[f(X, \theta)] = \int f(x, \theta)\,\Pr_X(\dd x). The derivative of FF is the limit of (F(θ+h)−F(θ))/h=E[Dh]\big(F(\theta + h) - F(\theta)\big)/h = \E[D_h] with difference quotient

Dh=f(X,θ+h)−f(X,θ)h.D_h = \frac{f(X, \theta + h) - f(X, \theta)}{h} .

Therefore F′(θ)=lim⁡h→0E[Dh]F'(\theta) = \lim_{h \to 0} \E[D_h], and asking whether the derivative can enter is exactly a dominated-convergence question: is lim⁡E[Dh]=E[lim⁡Dh]\lim \E[D_h] = \E[\lim D_h]? Dominating DhD_h amounts to a Lipschitz condition.

Proof

Let hk→0h_k \to 0 with hk≠0h_k \ne 0 and θ0+hk∈I\theta_0 + h_k \in I. The quotients Dk=(f(X,θ0+hk)−f(X,θ0))/hkD_k = \big(f(X, \theta_0 + h_k) - f(X, \theta_0)\big)/h_k satisfy Dk→∂θf(X,θ0)D_k \to \partial_\theta f(X, \theta_0) almost surely by (iii), and ∣Dk∣≤L(X)\abs{D_k} \le L(X) by (ii), with L(X)L(X) integrable. By dominated convergence E[Dk]→E[∂θf(X,θ0)]\E[D_k] \to \E[\partial_\theta f(X, \theta_0)]. By linearity E[Dk]=(F(θ0+hk)−F(θ0))/hk\E[D_k] = (F(\theta_0 + h_k) - F(\theta_0))/h_k. Since the sequence hkh_k is arbitrary, the derivative of FF at θ0\theta_0 exists and is the limit. ■\blacksquare

∎

Assumption (ii) is Lipschitz continuity in θ\theta with an integrable constant. The calculus-textbook version, ∣∂θf(x,θ)∣≤g(x)\abs{\partial_\theta f(x, \theta)} \le g(x) with gg integrable, implies it by the mean value theorem. The version above is more useful because (iii) requires differentiability only almost surely: a function like ReLU⁡\relu, which is not differentiable at 00 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 X∼N(0,1)X \sim \Normal(0, 1) and f(x,θ)=1{x<θ}f(x, \theta) = \ind\{x < \theta\}. Then F(θ)=E[f(X,θ)]=Φ(θ)F(\theta) = \E[f(X, \theta)] = \Phi(\theta), with derivative F′(θ)=φ(θ)>0F'(\theta) = \varphi(\theta) > 0. But for every x≠θx \ne \theta the function θ↦f(x,θ)\theta \mapsto f(x, \theta) is locally constant, so ∂θf(x,θ)=0\partial_\theta f(x, \theta) = 0 almost surely and E[∂θf(X,θ)]=0≠φ(θ)\E[\partial_\theta f(X, \theta)] = 0 \ne \varphi(\theta). The exchange fails, exactly where dominated convergence fails: the difference quotient is

Dh=1h 1{θ≤X<θ+h}(h>0),D_h = \frac{1}{h}\,\ind\{\theta \le X < \theta + h\} \qquad (h > 0),

which with h=1/nh = 1/n is the shifted sequence n 1(0,1/n)n\,\ind_{(0, 1/n)}: mass concentrates on a point of probability zero, the pointwise limit is 00 and the integrals equal E[Dh]≈φ(θ)\E[D_h] \approx \varphi(\theta). All the variation of ff with θ\theta occurs on a set of zero probability, and the almost-sure derivative cannot see it.

InteractiveDifferentiating inside expectation
The function f(x,θ)f(x, \theta) (red) and the density of X∼N(0,1)X \sim \Normal(0, 1) (blue)
θ
The function θ↦E[f(X,θ)]\theta \mapsto \E[f(X, \theta)] and three slopes at the current θ\theta
With the jump, ∂θ f is 0 for every x ≠ θ: the pathwise mean is 0 and the true slope is φ(θ). The derivative cannot move inside the expectation because all variation lies at a point of probability zero.
  • true slope
  • pathwise slope
  • log-derivative slope
  • density of XX and samples
0.60
0 (jump)
Truth:  ⁣d ⁣dθE[f(X,θ)]\frac{\dd}{\dd\theta}\E[f(X, \theta)]0.3332
Pathwise: mean of ∂θf\partial_\theta f (± error)0.0000 ± 0.0000
Log derivative (± error)0.3561 ± 0.0119
Variance per sample: pathwise0.000
Variance per sample: log derivative0.428
Prediction φ(θ)/(6s)\varphi(\theta)/(6s)∞
With X∼N(0,1)X \sim \Normal(0, 1) and f(x,θ)=1{x<θ}f(x, \theta) = \ind\{x < \theta\} (temperature s=0s = 0), move θ\theta and compare the slopes of θ↦E[f(X,θ)]\theta \mapsto \E[f(X, \theta)]: the true slope (thick gray, equal to φ(θ)\varphi(\theta)), the average of pathwise derivatives (red, flat), and the log-derivative slope (dashed turquoise). Then increase temperature ss: ff becomes a sigmoid σ((θ−x)/s)\sigma((\theta - x)/s) and the exchange becomes legal again. What happens to the variance of the pathwise estimator as ss decreases? And to that of the log derivative? For which ss does the winner change?

After smoothing, fs(x,θ)=σ((θ−x)/s)f_s(x, \theta) = \sigma\big((\theta - x)/s\big) is Lipschitz in θ\theta with constant 1/(4s)1/(4s), so the theorem applies: the pathwise estimator ∂θfs(X,θ)=σ′((θ−X)/s)/s\partial_\theta f_s(X, \theta) = \sigma'\big((\theta - X)/s\big)/s is unbiased for the derivative of θ↦E[fs(X,θ)]\theta \mapsto \E[f_s(X, \theta)], the density of X+sLX + sL with LL logistic. But that constant 1/(4s)1/(4s) explodes as s→0s \to 0, and so does the variance. A calculation with change of variable u=(θ−x)/su = (\theta - x)/s gives

Var⁡(∂θfs(X,θ))  ≈  φ(θ)s∫σ′(u)2  ⁣du  =  φ(θ)6s(s→0),\Var\big(\partial_\theta f_s(X, \theta)\big) \;\approx\; \frac{\varphi(\theta)}{s} \int \sigma'(u)^2 \,\dd u \;=\; \frac{\varphi(\theta)}{6s} \qquad (s \to 0),

as shown by the figure’s Prediction readout (the approximation is asymptotic: with s=0.1s = 0.1 and θ=0.6\theta = 0.6 it predicts 0.560.56 and the exact variance is 0.440.44). Near the jump we cannot have everything: for each s>0s > 0 the pathwise estimator is unbiased but its variance explodes like 1/s1/s; at the limit s=0s = 0 the variance is zero but the bias is total.

The figure’s log derivative needs another step, because here θ\theta appears in ff and not in the law of XX. Transfer it to the law using Y=θ−X∼N(θ,1)Y = \theta - X \sim \Normal(\theta, 1): then 1{X<θ}=1{Y>0}\ind\{X < \theta\} = \ind\{Y > 0\}, the parameter is the mean of YY, and the identity in the next section gives estimator 1{Y>0} (Y−θ)=−X 1{X<θ}\ind\{Y > 0\}\,(Y - \theta) = -X\,\ind\{X < \theta\}, unbiased for φ(θ)\varphi(\theta) with finite variance (0.410.41 with θ=0.6\theta = 0.6) that does not explode at the jump.

The two gradient identities

With the condition clear, the opening techniques follow as corollaries.

Reparameterization (pathwise). If X=T(Z,θ)X = T(Z, \theta) with ZZ of law independent of θ\theta (for example X=μ+σZX = \mu + \sigma Z with Z∼N(0,1)Z \sim \Normal(0, 1)), then E[f(X)]=E[f(T(Z,θ))]\E[f(X)] = \E[f(T(Z, \theta))] and, if ff is Lipschitz and differentiable at T(Z,θ)T(Z, \theta) almost surely, and TT is differentiable at θ\theta and Lipschitz in θ\theta with an integrable constant,

∂θ E[f(T(Z,θ))]=E[f′(T(Z,θ)) ∂θT(Z,θ)].\partial_\theta\, \E[f(T(Z, \theta))] = \E\big[f'(T(Z, \theta))\,\partial_\theta T(Z, \theta)\big].

For X=μ+σZX = \mu + \sigma Z this gives ∂μE[f(X)]=E[f′(X)]\partial_\mu \E[f(X)] = \E[f'(X)] and ∂σE[f(X)]=E[f′(X) Z]\partial_\sigma \E[f(X)] = \E[f'(X)\,Z]. This is the gradient backpropagation propagates through sampling in a variational autoencoder. It does not work if ff has jumps (an indicator, rounding, an arg max⁡\argmax) or, of course, with discrete variables, because TT is then not differentiable.

Log derivative (score function). If XX has density pθp_\theta with respect to a fixed measure ν\nu (Lebesgue or counting), Eθ[f(X)]=∫f(x) pθ(x) ν( ⁣dx)\E_\theta[f(X)] = \int f(x)\,p_\theta(x)\,\nu(\dd x). Applying the theorem to measure ν\nu with integrand f(x) pθ(x)f(x)\,p_\theta(x), provided ∂θpθ\partial_\theta p_\theta exists and ∣f ∂θpθ∣\abs{f\,\partial_\theta p_\theta} is dominated by a ν\nu-integrable function locally in θ\theta,

∂θ Eθ[f(X)]=∫f(x) ∂θpθ(x) ν( ⁣dx)=Eθ[f(X) ∂θlog⁡pθ(X)].\partial_\theta\, \E_\theta[f(X)] = \int f(x)\,\partial_\theta p_\theta(x)\,\nu(\dd x) = \E_\theta\big[f(X)\,\partial_\theta \log p_\theta(X)\big].

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

∂μ Eμ[f(X)]=∂μ∫f(x) φ(x−μ)  ⁣dx\partial_\mu\, \E_\mu[f(X)] = \partial_\mu \int f(x)\,\varphi(x - \mu)\,\dd x
Start from the expectation of X∼N(μ,1)X \sim \Normal(\mu, 1) as a Lebesgue integral with respect to Lebesgue measure, with φ\varphi the standard normal density. The parameter appears only in the density.
1/4

With f=1f = 1 the identity says Eθ[∂θlog⁡pθ(X)]=0\E_\theta[\partial_\theta \log p_\theta(X)] = 0: the score function has mean zero. This gives the REINFORCE baseline trick: subtracting a constant bb from ff does not change the estimator’s mean (because E[b ∂θlog⁡pθ]=0\E[b\,\partial_\theta \log p_\theta] = 0) and, when well chosen, greatly reduces variance.

Implementation from scratch: three gradient estimators

Estimate ∂μ EX∼N(μ,1)[f(X)]\partial_\mu\,\E_{X \sim \Normal(\mu, 1)}[f(X)] with X=μ+ZX = \mu + Z in three ways, and check what happens with a smooth function, one with a kink (the Lipschitz ReLU⁡\relu), and one with a jump. The ground truth is the exact derivative of each expectation.

[ ]Finite differences, pathwise and log derivativeBrowser
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 ReLU⁡\relu, pathwise still works, even though f′f' does not exist at 00 (the almost-sure differentiability case). With the jump, pathwise gives exactly 00 (the exchange fails; the mean is the derivative of a constant), whereas the log derivative is correct with variance 0.360.36. Finite differences are correct because they exchange nothing, but their variance grows as 1/h1/h: this is the earlier n 1(0,1/n)n\,\ind_{(0, 1/n)} with h=1/nh = 1/n.

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 m=E[X]m = \E[X]. Since XX takes values in II, mm lies between the endpoints of II. If mm equals an endpoint (say, the lower one), X−m≥0X - m \ge 0 has expectation 00 and therefore X=mX = m almost surely; in particular m∈Im \in I (because X∈IX \in I), and the inequality is equality. Otherwise mm is in the interior of II and there is a supporting line: c∈Rc \in \R with φ(x)≥φ(m)+c(x−m)\varphi(x) \ge \varphi(m) + c(x - m) for every x∈Ix \in I. (It exists because, by convexity, the slopes (φ(x)−φ(m))/(x−m)\big(\varphi(x) - \varphi(m)\big)/(x - m) increase with xx in I∖{m}I \setminus \{m\}, the three-chord lemma; take cc between the supremum of the slopes to the left of mm and their infimum to the right.) Then φ(X)≥φ(m)+c(X−m)\varphi(X) \ge \varphi(m) + c(X - m), the right side is integrable and therefore E[φ(X)]\E[\varphi(X)] exists. Taking expectations, by monotonicity and linearity,

E[φ(X)]  ≥  φ(m)+c(E[X]−m)=φ(m).\E[\varphi(X)] \;\ge\; \varphi(m) + c\big(\E[X] - m\big) = \varphi(m).

If φ\varphi is strictly convex, φ(x)>φ(m)+c(x−m)\varphi(x) > \varphi(m) + c(x - m) for x≠mx \ne m, and equality requires E[φ(X)−φ(m)−c(X−m)]=0\E\big[\varphi(X) - \varphi(m) - c(X - m)\big] = 0 with nonnegative integrand, hence zero almost surely; this happens only if X=mX = m almost surely. If φ\varphi is concave, apply the preceding result to −φ-\varphi. ■\blacksquare

∎

The picture is shown in the figure. Points (X,φ(X))(X, \varphi(X)) 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 E[φ(X)]\E[\varphi(X)], while the curve’s height at the average abscissa is φ(E[X])\varphi(\E[X]).

InteractiveJensen with draggable weights
Graph of φ\varphi (convex); points are values of XX, sized in proportion to their weights
Weights pi=P(X=xi)p_i = \Pr(X = x_i) (sum to 1: increasing one shares the remainder among the others)
0.350.200.45
  • graph of φ\varphi
  • (E[X],φ(E[X]))(\E[X], \varphi(\E[X]))
  • (E[X],E[φ(X)])(\E[X], \E[\varphi(X)])
  • convex hull of the points
Possible values of XX
E[X]\E[X]0.075
φ(E[X])\varphi(\E[X])1.078
E[φ(X)]\E[\varphi(X)]3.467
Gap E[φ(X)]−φ(E[X])\E[\varphi(X)] - \varphi(\E[X])2.3894
SignE φ(X) > φ(E X)
The colored points are values of XX on the graph of φ\varphi (drag them); the bars below show their probabilities (drag the handles). The magenta point is (E[X],E[φ(X)])(\E[X], \E[\varphi(X)]), the weighted average, always inside the convex hull. The small point, in the text color, is (E[X],φ(E[X]))(\E[X], \varphi(\E[X])) on the curve. With convex φ\varphi, is the magenta point above or below? When is the gap zero? For x2x^2, compare the gap with Var⁡(X)\Var(X). Switch to log⁡x\log x and x\sqrt x and observe the reversal. With the sigmoid, place all mass at x<0x < 0 and then at x>0x > 0: what happens to the sign?

Everyday consequences:

  • ∣E[X]∣≤E∣X∣\abs{\E[X]} \le \E\abs{X} and E[X]2≤E[X2]\E[X]^2 \le \E[X^2] (with φ=∣⋅∣\varphi = \abs{\cdot} and φ=x2\varphi = x^2): the second is Var⁡(X)≥0\Var(X) \ge 0.
  • E[etX]≥et E[X]\E[e^{tX}] \ge e^{t\,\E[X]} for every tt. For X∼N(0,1)X \sim \Normal(0, 1) and t=1t = 1 the gap is E[eX]−eE[X]=e1/2−1≈0.649\E[e^X] - e^{\E[X]} = e^{1/2} - 1 \approx 0.649 (calculated by completing the square in the exponent; this is an exercise).
  • E[log⁡X]≤log⁡E[X]\E[\log X] \le \log \E[X] for X>0X > 0 (concave logarithm): the geometric mean does not exceed the arithmetic mean.
  • ELBO. Let p(x,z)p(x, z) be a latent-variable model and q(z)q(z) any density over zz. Since p(x)=Eq[p(x,Z)/q(Z)]p(x) = \E_q\big[p(x, Z)/q(Z)\big], concavity of log⁡\log gives
log⁡p(x)  =  log⁡Eq[p(x,Z)q(Z)]  ≥  Eq[log⁡p(x,Z)q(Z)]=:ELBO(q),\log p(x) \;=\; \log \E_{q}\Big[\frac{p(x, Z)}{q(Z)}\Big] \;\ge\; \E_q\Big[\log \frac{p(x, Z)}{q(Z)}\Big] =: \mathrm{ELBO}(q),

and the gap is exactly KL⁡(q(z) ∥ p(z∣x))≥0\KL\big(q(z) \,\|\, p(z \given x)\big) \ge 0 (subtract the two sides and use p(x,z)=p(z∣x) p(x)p(x, z) = p(z \given x)\,p(x)). Raising the lower bound and bringing it closer to log⁡p(x)\log p(x) 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 ∥X∥p=(E∣X∣p)1/p\norm{X}_p = \big(\E\abs{X}^p\big)^{1/p} for p∈[1,∞)p \in [1, \infty), and call pp and qq conjugates if 1/p+1/q=11/p + 1/q = 1.

Proof

(a) If either norm is 00 or ∞\infty the result is trivial. Normalize to ∥X∥p=∥Y∥q=1\norm{X}_p = \norm{Y}_q = 1 (the statement is homogeneous). Young’s inequality says ab≤ap/p+bq/qab \le a^p/p + b^q/q for a,b≥0a, b \ge 0: by convexity of the exponential, ab=exp⁡(1pln⁡ap+1qln⁡bq)≤1pap+1qbqab = \exp\big(\tfrac1p \ln a^p + \tfrac1q \ln b^q\big) \le \tfrac1p a^p + \tfrac1q b^q. With a=∣X∣a = \abs{X} and b=∣Y∣b = \abs{Y} and taking expectations, E∣XY∣≤1p+1q=1\E\abs{XY} \le \tfrac1p + \tfrac1q = 1. (b) Apply (a) with p=q=2p = q = 2 to ∣XY∣≥±XY\abs{XY} \ge \pm XY. (c) For p=1p = 1 this is the triangle inequality. For p>1p > 1, ∣X+Y∣p≤2p−1(∣X∣p+∣Y∣p)\abs{X + Y}^p \le 2^{p-1}(\abs{X}^p + \abs{Y}^p) by convexity of tpt^p, hence E∣X+Y∣p<∞\E\abs{X + Y}^p < \infty if ∥X∥p,∥Y∥p<∞\norm{X}_p, \norm{Y}_p < \infty (otherwise there is nothing to prove). Writing ∣X+Y∣p≤∣X∣∣X+Y∣p−1+∣Y∣∣X+Y∣p−1\abs{X + Y}^p \le \abs{X}\abs{X + Y}^{p-1} + \abs{Y}\abs{X + Y}^{p-1} and applying Hölder with conjugate exponent q=p/(p−1)q = p/(p - 1) to each term,

E∣X+Y∣p≤(∥X∥p+∥Y∥p) (E∣X+Y∣(p−1)q)1/q=(∥X∥p+∥Y∥p) ∥X+Y∥pp−1,\E\abs{X + Y}^p \le \big(\norm{X}_p + \norm{Y}_p\big)\,\Big(\E\abs{X + Y}^{(p-1)q}\Big)^{1/q} = \big(\norm{X}_p + \norm{Y}_p\big)\,\norm{X + Y}_p^{p-1} ,

and divide by ∥X+Y∥pp−1\norm{X + Y}_p^{p-1} (the case ∥X+Y∥p=0\norm{X + Y}_p = 0 is trivial). ■\blacksquare

∎

Cauchy–Schwarz is the most frequently used inequality in the course. With X−E[X]X - \E[X] and Y−E[Y]Y - \E[Y] it gives ∣Cov⁡(X,Y)∣≤σXσY\abs{\Cov(X, Y)} \le \sigma_X \sigma_Y, meaning the correlation coefficient lies in [−1,1][-1, 1] (see the moments lesson). It is the inequality ∣⟨u,v⟩∣≤∥u∥∥v∥\abs{\inner{\vb{u}}{\vb{v}}} \le \norm{\vb{u}}\norm{\vb{v}} of Rn\R^n with inner product ⟨X,Y⟩=E[XY]\inner{X}{Y} = \E[XY]: random variables are vectors, and the correlation between two is the cosine of the angle between their centered versions.

LpL^p spaces and expectations that do not exist

The norm ∥X∥p\norm{X}_p is finite only if XX has a moment of order pp. Variables with that moment form a space.

This is a vector space by Minkowski (and by ∣X+Y∣p≤2p−1(∣X∣p+∣Y∣p)\abs{X + Y}^p \le 2^{p-1}(\abs{X}^p + \abs{Y}^p)), ∥⋅∥p\norm{\cdot}_p is a norm (if ∥X∥p=0\norm{X}_p = 0, then X=0X = 0 almost surely by the first properties, which is why almost surely equal variables are identified), and the product ⟨X,Y⟩=E[XY]\inner{X}{Y} = \E[XY] turns L2L^2 into an inner product space. Most important in probability is that these spaces are nested, and Jensen proves it in one line.

Proof

If ∥X∥q=∞\norm{X}_q = \infty there is nothing to prove; otherwise ∣X∣p≤1+∣X∣q\abs{X}^p \le 1 + \abs{X}^q is integrable. For q<∞q < \infty the function t↦tq/pt \mapsto t^{q/p} is convex on [0,∞)[0, \infty), and Jensen gives (E∣X∣p)q/p≤E[(∣X∣p)q/p]=E∣X∣q\big(\E\abs{X}^p\big)^{q/p} \le \E\big[(\abs{X}^p)^{q/p}\big] = \E\abs{X}^q. Raise to 1/q1/q. The case q=∞q = \infty is E∣X∣p≤∥X∥∞p\E\abs{X}^p \le \norm{X}_\infty^p. ■\blacksquare

∎

The inclusion is usually strict, and depends on finite measure. With P(X>x)=x−a\Pr(X > x) = x^{-a} for x≥1x \ge 1 (the Pareto law), the layer-cake formula gives E[Xp]=∫0∞P(Xp>t)  ⁣dt=1+∫1∞t−a/p  ⁣dt\E[X^p] = \int_0^\infty \Pr(X^p > t)\,\dd t = 1 + \int_1^\infty t^{-a/p}\,\dd t, which is finite if and only if p<ap < a: with a=3a = 3, X∈L2X \in L^2 but X∉L3X \notin L^3 (and E[X2]=3\E[X^2] = 3). On R\R with Lebesgue measure there is no inclusion: 1/(1+∣x∣)∈L2∖L11/(1 + \abs{x}) \in L^2 \setminus L^1 and ∣x∣−1/21(0,1)∈L1∖L2\abs{x}^{-1/2}\ind_{(0,1)} \in L^1 \setminus L^2, which is why in Lp(λ)L^p(\lambda) both ends need care (near zero and at infinity).

Proof

Choose n1<n2<⋯n_1 < n_2 < \cdots with ∥Xnk+1−Xnk∥p<2−k\norm{X_{n_{k+1}} - X_{n_k}}_p < 2^{-k} and define S=∑k∣Xnk+1−Xnk∣S = \sum_k \abs{X_{n_{k+1}} - X_{n_k}}. By monotone convergence and Minkowski, ∥S∥p≤∑k2−k<∞\norm{S}_p \le \sum_k 2^{-k} < \infty, so S<∞S < \infty almost surely, and then XnkX_{n_k} converges almost surely (the telescoping series converges absolutely) to a random variable XX. By Fatou’s lemma, for each kk, E∣X−Xnk∣p≤lim inf⁡jE∣Xnj−Xnk∣p≤(2−k+1)p\E\abs{X - X_{n_k}}^p \le \liminf_j \E\abs{X_{n_j} - X_{n_k}}^p \le \big(2^{-k+1}\big)^p. Thus Xnk→XX_{n_k} \to X in LpL^p and, because the sequence is Cauchy, the whole sequence converges to XX. ■\blacksquare

∎

Completeness lets us discuss limits of variables in LpL^p and, for p=2p = 2, projections: L2L^2 is a Hilbert space, and in the conditional expectation lesson E[Y∣X]\E[Y \mid X] will be the orthogonal projection of YY onto the subspace of functions of XX. Least-squares regression is that projection. Convergence in LpL^p 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 f(x)=1/(π(1+x2))f(x) = 1/\big(\pi(1 + x^2)\big), is the standard example:

E∣X∣=2π∫0∞x1+x2  ⁣dx=1πlim⁡M→∞ln⁡(1+M2)=∞.\E\abs{X} = \frac{2}{\pi}\int_0^\infty \frac{x}{1 + x^2}\,\dd x = \frac{1}{\pi}\lim_{M \to \infty} \ln(1 + M^2) = \infty .

Since E[X+]=E[X−]=∞\E[X^+] = \E[X^-] = \infty, the expectation does not exist, not even as +∞+\infty or −∞-\infty. Taking a “principal value” (integrating from −M-M to MM and taking M→∞M \to \infty) gives 00 by symmetry, but asymmetric truncation ∫−M2M\int_{-M}^{2M} 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, P(X=2k)=2−k\Pr(X = 2^k) = 2^{-k} with E[X]=∑k2k2−k=∞\E[X] = \sum_k 2^k 2^{-k} = \infty.

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 nn iid Cauchy variables has the same Cauchy law as each one and does not concentrate, however much nn increases.

[ ]Running means with and without expectationBrowser
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 00, and Pareto with a=1.5a = 1.5 converges to 33 (slowly, jumping at each extreme value because variance is infinite). The Cauchy mean keeps jumping at n=200 000n = 200\,000 (−5.987-5.987, far from any limit), and the St Petersburg mean does not converge: its typical level grows like log⁡2n\log_2 n (equal to 6.66.6, 10.010.0, 13.313.3 and 17.617.6 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 14.814.8 with n=100n = 100, far above log⁡2100\log_2 100; it then falls slowly until another jump raises it. The last line shows what happens inside the Cauchy sample: ten of 200 000200\,000 observations account for 55 %55\,\% 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.

[ ]expect, quad and sympyBrowser
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 E[f]\E[f] with respect to μ\mu, the expectation of f′f' (pathwise), and the expectation of f⋅(X−μ)f \cdot (X - \mu) (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

ProofDominated convergence from Fatou's lemma
Prove: Let fn→ff_n \to f almost everywhere, with ∣fn∣≤g\abs{f_n} \le g almost everywhere and gg integrable. Then ∫fn→∫f\int f_n \to \int f.
0
Prove lower and upper bounds for ∫f\int f separately with two applications of Fatou's lemma, without using the integral of ∣fn−f∣\abs{f_n - f}.

Step 1 of 4. What two sequences of nonnegative functions can be built from the assumptions?

ProofJensen with a supporting line
Prove: Let φ\varphi be convex on an interval II and XX integrable with values in II. Then φ(E[X])≤E[φ(X)]\varphi(\E[X]) \le \E[\varphi(X)].
0
Let m=E[X]m = \E[X] lie in the interior of II. Bound φ\varphi with a line touching the graph at mm, then take expectations.

Step 1 of 4. What line is used, and what property of φ\varphi guarantees its existence?

NumericThe exponential Jensen gap
Let X∼N(0,1)X \sim \Normal(0, 1). Calculate the Jensen gap E[eX]−eE[X]\E[e^X] - e^{\E[X]}.
NumericExpectation of a mixed variable
Let XX be a variable with P(X=0)=0.4\Pr(X = 0) = 0.4 and, with probability 0.60.6, an exponential of rate 22 (that is, PX=0.4 δ0+0.6 Exp(2)\Pr_X = 0.4\,\delta_0 + 0.6\,\mathrm{Exp}(2)). Calculate E[(X+1)2]\E\big[(X + 1)^2\big].
NumericA moment with the layer-cake formula
Let X≥1X \ge 1 with P(X>x)=x−3\Pr(X > x) = x^{-3} for x≥1x \ge 1 (Pareto law with index 33). Calculate E[X2]\E[X^2] using the layer-cake formula E[Y]=∫0∞P(Y>t)  ⁣dt\E[Y] = \int_0^\infty \Pr(Y > t)\,\dd t applied to Y=X2Y = X^2.
QuizWhich satisfy the assumptions of dominated convergence?
All these sequences are defined on [0,1][0, 1] or [0,∞)[0, \infty) with Lebesgue measure. Which have an integrable dominating function (a g∈L1g \in L^1 with ∣fn∣≤g\abs{f_n} \le g for every nn)?

More than one answer may be correct.

QuizWhich direction does each inequality take?
Let XX have the required moments (and X>0X > 0 when needed). Which of these inequalities are always true?

More than one answer may be correct.

CodePathwise and log derivative
Implement estimadores(f, df, mu, z), where z is an array of samples Zi∼N(0,1)Z_i \sim \Normal(0, 1) and Xi=μ+ZiX_i = \mu + Z_i. Return a tuple (pathwise, score) of two arrays of the same length as z, with per-sample estimates of ∂μE[f(X)]\partial_\mu \E[f(X)]: the pathwise f′(Xi)f'(X_i) (using the supplied derivative df) and log derivative f(Xi) (Xi−μ)f(X_i)\,(X_i - \mu). 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)
Shift+Enter to run

Summary

Key idea
The Lebesgue integral is built by slicing the range: simple functions, the supremum of those that fit below, and expectation is E[X]=∫X  ⁣dP\E[X] = \int X \,\dd\Pr, with one definition for discrete, continuous and mixed laws (LOTUS). Its value lies in the convergence theorems: monotone convergence, Fatou and dominated convergence, whose failure is escaping mass. Dominated convergence yields the exact condition for differentiation under the integral, and from there reparameterization and the log derivative. Jensen, Hölder and Minkowski lead to LpL^p spaces, nested in probability and complete.
  • The integral of f≥0f \ge 0 is sup⁡{∫s:s simple,s≤f}\sup\{\int s : s \text{ simple}, s \le f\}, and for a simple function ∫s=∑aiμ(Ai)\int s = \sum a_i \mu(A_i). A signed function is integrable if ∫∣f∣<∞\int \abs{f} < \infty. The layer-cake formula, ∫f=∫0∞μ(f>t)  ⁣dt\int f = \int_0^\infty \mu(f > t)\,\dd t, is the picture of horizontal slices.
  • Expectation is E[X]=∫X  ⁣dP\E[X] = \int X \,\dd\Pr, and LOTUS gives E[g(X)]=∫g  ⁣dPX=∑pig(xi)+∫gf  ⁣dx\E[g(X)] = \int g \,\dd\Pr_X = \sum p_i g(x_i) + \int g f\,\dd x for a mixed law. A nonnegative variable with expectation 00 is zero almost surely, and Markov bounds tails using expectation.
  • Monotone convergence: if 0≤fn↑f0 \le f_n \uparrow f, ∫fn↑∫f\int f_n \uparrow \int f (without further assumptions). Fatou: ∫lim inf⁡fn≤lim inf⁡∫fn\int \liminf f_n \le \liminf \int f_n; mass can disappear but cannot appear. Dominated convergence: fn→ff_n \to f and ∣fn∣≤g∈L1\abs{f_n} \le g \in L^1 give ∫∣fn−f∣→0\int \abs{f_n - f} \to 0.
  • An integrable dominating function exists if and only if ∫sup⁡n∣fn∣<∞\int \sup_n \abs{f_n} < \infty. 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 ff is Lipschitz in θ\theta with an integrable constant and differentiable almost surely. It fails with jumps (1{x<θ}\ind\{x < \theta\}): E[∂θf]=0≠φ(θ)\E[\partial_\theta f] = 0 \ne \varphi(\theta). Pathwise: E[f′(X) ∂θT]\E[f'(X)\,\partial_\theta T]. Log derivative: E[f(X) ∂θlog⁡pθ(X)]\E[f(X)\,\partial_\theta \log p_\theta(X)], without differentiating ff and with greater variance.
  • Jensen: φ(EX)≤Eφ(X)\varphi(\E X) \le \E\varphi(X) if φ\varphi is convex (reversed if concave); this gives E[log⁡X]≤log⁡E[X]\E[\log X] \le \log\E[X] and the ELBO. Hölder, Cauchy–Schwarz and Minkowski give the norm ∥X∥p\norm{X}_p.
  • LpL^p is complete, and in probability Lq⊂LpL^q \subset L^p if p≤qp \le q. L2L^2 is a Hilbert space, with ⟨X,Y⟩=E[XY]\inner{X}{Y} = \E[XY]. Some variables have no expectation (Cauchy), while others have infinite expectation but are finite almost surely (St Petersburg); their averages do not concentrate.