Module contents
Lesson 7 of 24Core 85 min

Random vectors, product measures and independence

A random vector has a joint law on ℝⁿ whose marginals are pushforward measures under projections. Product measures and the Fubini–Tonelli theorems formalize independence as factorization of the joint law and allow integrals to be exchanged. Kolmogorov's extension theorem guarantees the existence of the iid sequences used throughout.

After this lesson you can

  • Calculate marginals of discrete and continuous joint laws by summing or integrating out variables.
  • Construct product measures and apply Fubini–Tonelli, including the tail formula 𝔼[X] = ∫₀^∞ P(X > t) dt.
  • Characterize independence by factorization of the joint law, distribution function or density.
  • State Kolmogorov's extension theorem and explain why it guarantees iid sequences.
  • Generate independent, reproducible random streams for parallel simulations.

Before you start

Motivation: what does iid mean in a minibatch?

You train a network with minibatches of B=32B = 32 examples and write without thinking, “let X1,…,X32X_1, \dots, X_{32} be an iid sample from the data distribution.” That sentence has precise content, and everything said afterward about the stochastic gradient depends on it: the minibatch is one random object, a vector X=(X1,…,X32)\vb{X} = (X_1, \dots, X_{32}) taking values in R32×d\R^{32 \times d}, and iid is a statement about its joint law. Given what you know, that law is a measure on R32×d\R^{32 \times d}; the question is which one. This lesson answers four interdependent questions.

  1. Random vectors and joint laws. A random vector has a law on Rn\R^n, and each component has its own marginal law, the pushforward under a projection. The joint law determines the marginals, not conversely: infinitely many joint laws share the same marginals, distinguished by their dependence.
  2. Product measures and the Fubini–Tonelli theorem. There is a unique way to construct a measure on a product from two measures so that the two sides do not affect each other. It lets us calculate double integrals as iterated integrals, provided no assumption fails. When one fails, order matters and the result can change.
  3. Independence. Variables X1,…,XnX_1, \dots, X_n are independent exactly when their joint law is the product of the marginals. All the criteria you use follow (factorization of the distribution function, density, E[XY]=E[X]E[Y]\E[XY] = \E[X]\E[Y]), along with the tail formula for expectation.
  4. Infinite sequences. Endless training, stochastic processes and laws of large numbers all speak of infinite sequences of independent variables. Kolmogorov’s extension theorem guarantees that they exist. The last section takes this to code: generating independent, reproducible random streams for parallel simulations.

Random vectors and joint laws

A random vector is a list of random variables defined on the same probability space. The requirement is that the list be measurable as a whole; fortunately, this is equivalent to requiring measurability component by component.

Proof

(⇒\Rightarrow) Xi=πi∘XX_i = \pi_i \circ \vb{X} and πi\pi_i is continuous, hence Borel measurable. (⇐\Leftarrow) Boxes (a1,b1]×⋯×(an,bn](a_1, b_1] \times \cdots \times (a_n, b_n] generate B(Rn)\mathcal{B}(\R^n), and X−1\vb{X}^{-1} of a box is ⋂i{Xi∈(ai,bi]}∈F\bigcap_i \{X_i \in (a_i, b_i]\} \in \mathcal{F}. The generator criterion from the random variables lesson concludes the proof. ■\blacksquare

∎

This is why one can say “(X,Y)(X, Y) is a random variable” from “XX and YY are random variables”, and why X+YX + Y, XYXY or max⁡(X,Y)\max(X, Y) are measurable: they are compositions of a measurable vector with a continuous function. Also, the joint distribution function determines the joint law. Quadrants (−∞,x1]×⋯×(−∞,xn](-\infty, x_1] \times \cdots \times (-\infty, x_n] form a π-system generating B(Rn)\mathcal{B}(\R^n) (the intersection of two quadrants is another quadrant), and the π-λ theorem gives uniqueness, just as in one dimension.

Marginalizing means summing or integrating

When a vector takes finitely many values, its joint law is a tensor p(x1,…,xn)=P(X1=x1,…,Xn=xn)p(x_1, \dots, x_n) = \Pr(X_1 = x_1, \dots, X_n = x_n) with nonnegative entries summing to 11; the marginal of XiX_i is obtained by summing over every other axis:

pi(xi)=∑x1,…,xi^,…,xnp(x1,…,xn).p_i(x_i) = \sum_{x_1, \dots, \widehat{x_i}, \dots, x_n} p(x_1, \dots, x_n).

This is the total probability formula from the conditioning lesson applied to event {Xi=xi}\{X_i = x_i\} and the partition by the other variables’ values; in NumPy it is P.sum(axis=...). With a joint Lebesgue density ff, the marginal is obtained by integrating ff over the other variables. This requires Tonelli’s theorem and is proved below. What matters now is the opposite direction.

The figure shows this at scale and reveals what the difference measures. Each cell is a square of area proportional to P(x,y)\Pr(x, y); the dotted square is the area that would result if XX and YY were independent, pX(x) pY(y)p_X(x)\,p_Y(y).

InteractiveMany joint laws, same marginals
marginal of Xmarginal of Yvalue of X (column)
  • P(x,y)\Pr(x, y) (area)
  • pX(x) pY(y)p_X(x)\,p_Y(y)
  • marginal of XX
  • marginal of YY
Starting joint law
Brush
Mutual information I(X;Y)I(X; Y)1.433 bits
Distance to product (total variation)0.613
Correlation of positions0.700
X⊥ ⁣ ⁣ ⁣⊥YX \indep Y?no
The joint law has I(X;Y)=1.433I(X; Y) = 1.433 bits. Lock the marginals and paint: the joint law and dependence can change without moving the bars.
The 8×88 \times 8 grid is the joint law of (X,Y)(X, Y), with both marginals (pushforwards under projections) as bars at the edges. Start with the diagonal joint law: what are its marginals? Press ‘Lock current marginals’ and paint mass in other cells: the joint law changes but the bars stay fixed (iterative proportional fitting corrects it). Press ‘Another joint with the same marginals’ several times: what stays the same? Measure dependence using mutual information. How many of these joint laws have it equal to zero? Finally replace the joint law by the product of its marginals and check that all 64 squares match the dotted squares. The erase brush can make it impossible to fix the marginals: why?

What you see provides an operational definition of dependence: the joint law carries information that the marginals lack, and independence is the choice of joint law with no extra information. To make this precise, construct that special joint law from the marginals: the product measure.

Product measure

If (X,A,μ)(X, \mathcal{A}, \mu) and (Y,B,ν)(Y, \mathcal{B}, \nu) are measure spaces, the product X×YX \times Y has a natural σ-algebra: the one making the rectangles A×BA \times B measurable for A∈AA \in \mathcal{A} and B∈BB \in \mathcal{B}. It is the σ-algebra generated by the two projections, the smallest one making them measurable.

For the line, B(R)⊗B(R)=B(R2)\mathcal{B}(\R) \otimes \mathcal{B}(\R) = \mathcal{B}(\R^2): open rectangles generate the open sets of R2\R^2, and open sets generate the Borel sets. The same holds in every finite dimension, so B(Rn)=B(R)⊗n\mathcal{B}(\R^n) = \mathcal{B}(\R)^{\otimes n}. The next theorem states that a measure with that property exists and is unique, and contains half of Fubini–Tonelli.

Proof

Measurable sections. For E⊂X×YE \subset X \times Y and x∈Xx \in X let Ex={y:(x,y)∈E}E_x = \{y : (x, y) \in E\} be its section. Let D\mathcal{D} be the class of E∈A⊗BE \in \mathcal{A} \otimes \mathcal{B} such that Ex∈BE_x \in \mathcal{B} for every xx and x↦ν(Ex)x \mapsto \nu(E_x) is A\mathcal{A}-measurable. It contains rectangles because (A×B)x(A \times B)_x is BB if x∈Ax \in A and ∅\emptyset otherwise, so ν((A×B)x)=1A(x)ν(B)\nu((A \times B)_x) = \ind_A(x)\nu(B). Rectangles are a π-system (the intersection of two rectangles is a rectangle). And D\mathcal{D} is a Dynkin system: it contains X×YX \times Y; if E⊂FE \subset F are in D\mathcal{D} then (F∖E)x=Fx∖Ex(F \setminus E)_x = F_x \setminus E_x and ν((F∖E)x)=ν(Fx)−ν(Ex)\nu((F \setminus E)_x) = \nu(F_x) - \nu(E_x) (here finiteness of ν\nu is used); and if Ek↑EE_k \uparrow E with Ek∈DE_k \in \mathcal{D}, sections increase, Ex=⋃k(Ek)xE_x = \bigcup_k (E_k)_x and ν(Ex)=lim⁡kν((Ek)x)\nu(E_x) = \lim_k \nu((E_k)_x) is a limit of measurable functions. By the π-λ theorem, D=A⊗B\mathcal{D} = \mathcal{A} \otimes \mathcal{B}. The same holds with the roles of xx and yy exchanged.

Existence. Let π1(E)=∫Xν(Ex) μ( ⁣dx)\pi_1(E) = \int_X \nu(E_x)\,\mu(\dd x). This is a measure: π1(∅)=0\pi_1(\emptyset) = 0, and if E(1),E(2),…E^{(1)}, E^{(2)}, \dots are disjoint, sections Ex(k)E^{(k)}_x are disjoint and ν\nu is σ-additive, so ν((⨆kE(k))x)=∑kν(Ex(k))\nu\big((\bigsqcup_k E^{(k)})_x\big) = \sum_k \nu(E^{(k)}_x), and the monotone convergence theorem (for series of nonnegative functions) permits exchanging sum and integral. On rectangles, π1(A×B)=∫1A(x)ν(B) μ( ⁣dx)=μ(A)ν(B)\pi_1(A \times B) = \int \ind_A(x)\nu(B)\,\mu(\dd x) = \mu(A)\nu(B). Similarly, π2(E)=∫Yμ(Ey) ν( ⁣dy)\pi_2(E) = \int_Y \mu(E^y)\,\nu(\dd y) is another measure with the same values on rectangles.

Uniqueness and equality. π1\pi_1 and π2\pi_2 agree on the π-system of rectangles, which generates A⊗B\mathcal{A} \otimes \mathcal{B}, and have the same total mass μ(X)ν(Y)<∞\mu(X)\nu(Y) < \infty. By π-λ, π1=π2\pi_1 = \pi_2, and any other measure with the product property agrees with them by the same argument. Call it μ⊗ν\mu \otimes \nu. This is (a), and (b) for f=1Ef = \ind_E: (μ⊗ν)(E)=∫ν(Ex) μ( ⁣dx)=∫μ(Ey) ν( ⁣dy)(\mu \otimes \nu)(E) = \int \nu(E_x)\,\mu(\dd x) = \int \mu(E^y)\,\nu(\dd y).

Functions. By linearity, (b) holds for nonnegative simple functions. If f≥0f \ge 0 is measurable, let fk↑ff_k \uparrow f be simple. By monotone convergence, ∫fk(x,y) ν( ⁣dy)↑∫f(x,y) ν( ⁣dy)\int f_k(x, y)\,\nu(\dd y) \uparrow \int f(x, y)\,\nu(\dd y) for every xx, so the limit is measurable, and applying it again to the outer integrals gives equality for ff. Both iterated integrals agree with ∫f  ⁣d(μ⊗ν)\int f\,\dd(\mu \otimes \nu) for the same reason.

σ-finite case. If X=⋃kXkX = \bigcup_k X_k and Y=⋃kYkY = \bigcup_k Y_k have finite, increasing measures, apply the preceding result to restrictions to Xk×YkX_k \times Y_k and take k→∞k \to \infty using monotone convergence. Uniqueness holds because rectangles Xk×YkX_k \times Y_k have finite measure and cover the product. ■\blacksquare

∎

This explains why in probability nearly everything works without additional assumptions: probability measures μ\mu and ν\nu are finite. The σ-finite cases used here are Lebesgue and counting measures. With Lebesgue measure, λn=λ⊗⋯⊗λ\lambda^n = \lambda \otimes \cdots \otimes \lambda on B(Rn)\mathcal{B}(\R^n): the two measures agree on boxes, a π-system. This is the volume measure of the multiple integral from calculus.

An example using the theorem for a concrete purpose. The diagonal D={(x,x)}D = \{(x, x)\} of R2\R^2 is closed, hence Borel, and by Tonelli λ2(D)=∫λ({x})  ⁣dx=∫0  ⁣dx=0\lambda^2(D) = \int \lambda(\{x\})\,\dd x = \int 0\,\dd x = 0. Therefore the vector (X,X)(X, X), with XX uniform on [0,1][0, 1], has no density on R2\R^2 even though each component does: its law is concentrated on a null set. This is the simplest version of the previous lesson’s warning about distributions concentrated on low-dimensional manifolds.

Fubini: when the function changes sign

Tonelli and the next theorem are the Fubini–Tonelli theorems. For functions taking both signs we may apply Tonelli to positive and negative parts separately, provided neither integral is infinite.

Proof

By Tonelli applied to ∣f∣\abs{f}, ∫X(∫Y∣f(x,y)∣ ν( ⁣dy))μ( ⁣dx)=∫∣f∣  ⁣d(μ⊗ν)<∞\int_X \big(\int_Y \abs{f(x, y)}\,\nu(\dd y)\big)\mu(\dd x) = \int \abs{f}\,\dd(\mu \otimes \nu) < \infty. A nonnegative function with finite integral is finite almost everywhere, so ∫Y∣f(x,y)∣ ν( ⁣dy)<∞\int_Y \abs{f(x, y)}\,\nu(\dd y) < \infty for μ\mu-almost every xx. Write f=f+−f−f = f^+ - f^-. Tonelli gives equality of the iterated integrals for f+f^+ and f−f^-, both finite, so they can be subtracted. ■\blacksquare

∎

The theorem in the calculus lesson is the same result with Lebesgue measure. Assumption f∈L1(μ⊗ν)f \in L^1(\mu \otimes \nu) is not a technical detail: without it the result can fail, and there may not even be a unique answer.

The second interactive sums the matrix in every order and shows when the results agree.

InteractiveWhen summation order matters
The matrix aija_{ij} (first 10 rows and columns of infinitely many)
columnas j = 1, 2, 3 …+−+−+−+−+−+−+−+−+−+= 0= 0= 0= 0= 0= 0= 0= 0= 0= 01000000000suma filasum of the whole column (the series continues to infinity)
Partial total of aija_{ij} when summing the first NN rows or columns
0.00.51.012345678910N0.0
  • whole rows first
  • whole columns first
  • N×NN \times N blocks
Summation order
What is summed
4
1.00
Sum of all row sums0.000
Sum of all column sums1.000
∑i,j∣aij∣\sum_{i,j} \abs{a_{ij}}∞
Partial total with N=4N = 4 (whole rows first)0.000
Summing by rows gives 00 (each row sums to 00), by columns 11 (only the first column contributes), and by N×NN \times N blocks 11. The double sum is not well-defined: order cannot be exchanged.
The first ten rows and columns of the infinite matrix (blue: +1+1, red: −1-1), with each row sum on the right and each column sum below. Choose a summation order and observe the partial total as NN increases: what is the row sum? The column sum? The sum over N×NN \times N blocks? Enable ∣aij∣\abs{a_{ij}}: what happens in each order? Now lower decay ρ\rho from 11 to 0.990.99: matrix ρi+jaij\rho^{i+j}a_{ij} is absolutely summable and both orders agree, but on what value? Why is it neither 00 nor 11?

With decay ρi+j\rho^{i+j} the matrix is integrable: ∑i,j∣aij∣=ρ2/(1−ρ)\sum_{i, j} \abs{a_{ij}} = \rho^2/(1 - \rho), and both iterated sums equal ρ2/(1+ρ)\rho^2/(1 + \rho), tending to 1/21/2 as ρ→1\rho \to 1. A decay-based summation method (Abel summation of the double series with the same factor ρ\rho on rows and columns) assigns the original matrix value 1/21/2, neither ordered sum. This is another way to see that 00 and 11 are arbitrary assignments: without integrability, the matrix’s sum is undefined. The next cell checks the discrete example and the classical continuous example with integrand f(x,y)=(x2−y2)/(x2+y2)2f(x, y) = (x^2 - y^2)/(x^2 + y^2)^2 on (0,1)2(0, 1)^2, whose iterated integrals equal +π/4+\pi/4 and −π/4-\pi/4.

[ ]The double sum and double integral without an orderBrowser
import numpy as np
import sympy as sp
from scipy import integrate

def a(i, j):
    return 1 if i == j else (-1 if j == i + 1 else 0)

fila = lambda i: sum(a(i, j) for j in (i, i + 1))                    # serie exacta: solo j = i, i + 1 aportan
columna = lambda j: sum(a(i, j) for i in (j - 1, j) if i >= 1)       # solo i = j - 1, j aportan
N = 12
print("sumas de filas   :", [fila(i) for i in range(1, N + 1)], " total", sum(fila(i) for i in range(1, N + 1)))
print("sumas de columnas:", [columna(j) for j in range(1, N + 1)], " total", sum(columna(j) for j in range(1, N + 1)))
for n in (5, 50, 500):
    blq = sum(a(i, j) for i in range(1, n + 1) for j in range(1, n + 1))
    absb = sum(abs(a(i, j)) for i in range(1, n + 1) for j in range(1, n + 1))
    print(f"bloque {n}x{n}: suma = {blq},  suma de |a| = {absb} = 2n - 1")

for rho in (0.5, 0.9, 0.99):                                          # con decaimiento rho^(i+j): integrable
    M = 4000
    por_filas = sum(rho ** (2 * i) * (1 - rho) for i in range(1, M))
    por_cols = rho ** 2 + sum(-(rho ** (2 * j - 1)) * (1 - rho) for j in range(2, M))
    print(f"rho = {rho}: filas {por_filas:.6f}  columnas {por_cols:.6f}  rho^2/(1+rho) = {rho**2/(1+rho):.6f}  suma|a| = {rho**2/(1-rho):.2f}")

x, y = sp.symbols("x y", positive=True)
f = (x**2 - y**2) / (x**2 + y**2) ** 2
print("\nd/dy [y/(x^2+y^2)] = f:", sp.simplify(sp.diff(y / (x**2 + y**2), y) - f) == 0, " (así que la integral en y desde 0 hasta 1 es 1/(1+x^2))")
fn = sp.lambdify((x, y), f, "math")
y_dentro = integrate.quad(lambda u: integrate.quad(lambda v: fn(u, v), 0, 1)[0], 0, 1)[0]
x_dentro = integrate.quad(lambda v: integrate.quad(lambda u: fn(u, v), 0, 1)[0], 0, 1)[0]
print(f"integrando primero en y: {y_dentro:.6f}   primero en x: {x_dentro:.6f}   pi/4 = {np.pi/4:.6f}")

Rows individually sum to zero, columns give 11 in total, and square blocks give 11 at any size, while ∑∣aij∣\sum \abs{a_{ij}} in the block grows like 2n−12n - 1. In the continuous example the integrand is not integrable on (0,1)2(0, 1)^2 (near the origin it behaves as 1/r21/r^2 in polar coordinates with measure r  ⁣drr\,\dd r, and ∫ ⁣dr/r=∞\int \dd r/r = \infty), and the two iterated integrals are opposite. Practical rule: for nonnegative functions use Tonelli; for others first verify ∫∣f∣<∞\int \abs{f} < \infty by calculating it using Tonelli. Everything follows from that check.

Two immediate consequences

Tonelli gives the marginal formula for a joint density. Let (X,Y)(X, Y) have density ff relative to Lebesgue measure on R2\R^2, and A∈B(R)A \in \mathcal{B}(\R). Then

P(X∈A)=P((X,Y)∈A×R)=∫R21A(x)f(x,y)  ⁣d(x,y)=∫A(∫Rf(x,y)  ⁣dy) ⁣dx,\Pr(X \in A) = \Pr\big((X, Y) \in A \times \R\big) = \int_{\R^2} \ind_A(x) f(x, y)\,\dd(x, y) = \int_A \Big(\int_{\R} f(x, y)\,\dd y\Big)\dd x,

so XX has density fX(x)=∫f(x,y)  ⁣dyf_X(x) = \int f(x, y)\,\dd y (defined almost everywhere), and similarly for YY. Marginalizing a density means integrating out the other variables. With f=1Ef = \ind_E this gives familiar computation of volume by sections. The converse is false: two marginals with densities do not imply a joint density, as just seen with (X,X)(X, X).

Independence of random variables

In the conditioning lesson, independence was a property of events. For random variables it is required simultaneously for all events they determine: those in their generated σ-algebras. A family of σ-algebras G1,…,Gn\mathcal{G}_1, \dots, \mathcal{G}_n is independent if P(A1∩⋯∩An)=∏iP(Ai)\Pr(A_1 \cap \cdots \cap A_n) = \prod_i \Pr(A_i) for any choice of Ai∈GiA_i \in \mathcal{G}_i (since every Gi\mathcal{G}_i contains Ω\Omega, this includes all subfamilies).

Taking Bj=RB_j = \R at some indices gives factorization for every subfamily, so the definition already includes mutual independence. Viewed through the joint law, this equality is the lesson’s central result.

Proof

Let PX\Pr_{\vb{X}} be the joint law and μ=PX1⊗⋯⊗PXn\mu = \Pr_{X_1} \otimes \cdots \otimes \Pr_{X_n} the product measure of the marginals (which exists uniquely by the previous theorem, applied iteratively). On a rectangle, PX(B1×⋯×Bn)=P(X1∈B1,…,Xn∈Bn)\Pr_{\vb{X}}(B_1 \times \cdots \times B_n) = \Pr(X_1 \in B_1, \dots, X_n \in B_n), and μ(B1×⋯×Bn)=∏iP(Xi∈Bi)\mu(B_1 \times \cdots \times B_n) = \prod_i \Pr(X_i \in B_i). The definition of independence thus says exactly that the two probabilities agree on rectangles. Since rectangles are a π-system generating B(Rn)\mathcal{B}(\R^n) and both measures are probabilities, π-λ makes them equal on all B(Rn)\mathcal{B}(\R^n). Conversely, if PX=μ\Pr_{\vb{X}} = \mu, evaluating on a rectangle gives factorization. ■\blacksquare

∎

This is the claim at the start: a minibatch (X1,…,XB)(X_1, \dots, X_B) with Xi∼iidPX_i \iid P is a random vector whose law is P⊗BP^{\otimes B}. Nothing more is needed: neither independent randomness as a separate concept nor an intrinsic property of variables. It is a property of the joint measure, called the product measure. All criteria follow from this.

Proof

(a) (⇒\Rightarrow) evaluates the definition at Bi=(−∞,xi]B_i = (-\infty, x_i]. (⇐\Leftarrow) Measures PX\Pr_{\vb{X}} and ⨂iPXi\bigotimes_i \Pr_{X_i} agree on quadrants (−∞,x1]×⋯×(−∞,xn](-\infty, x_1] \times \cdots \times (-\infty, x_n] (the first by definition, the second by the product property), a generating π-system of B(Rn)\mathcal{B}(\R^n), and have total mass 11. By π-λ they agree, and the previous theorem applies. The first exercise guides this proof step by step.

(b) If f=∏igif = \prod_i g_i almost everywhere, with measurable gi≥0g_i \ge 0, Tonelli gives ∫⋯∫∏i1Bi(xi)gi(xi)  ⁣dx=∏i∫Bigi\int \cdots \int \prod_i \ind_{B_i}(x_i) g_i(x_i)\,\dd \vb{x} = \prod_i \int_{B_i} g_i for every rectangle. Taking Bi=RB_i = \R shows ∏i∫gi=1\prod_i \int g_i = 1, so each ∫gi=:ci\int g_i =: c_i is finite and positive with ∏ici=1\prod_i c_i = 1, and P(Xi∈Bi)=∫Bigi/ci\Pr(X_i \in B_i) = \int_{B_i} g_i / c_i, so fXi=gi/cif_{X_i} = g_i / c_i, and rectangle probability is ∏i∫Bigi=∏iP(Xi∈Bi)\prod_i \int_{B_i} g_i = \prod_i \Pr(X_i \in B_i). Conversely, under independence, product measure ⨂iPXi\bigotimes_i \Pr_{X_i} has density ∏ifXi\prod_i f_{X_i} (by the same Tonelli calculation, on rectangles then by π-λ), and equals PX\Pr_{\vb{X}}, which has density ff. Two densities of the same measure agree almost everywhere (density uniqueness). (c) (⇒\Rightarrow) is the definition with Bi={xi}B_i = \{x_i\}. (⇐\Leftarrow) Measures PX\Pr_{\vb{X}} and ⨂iPXi\bigotimes_i \Pr_{X_i} are concentrated on the countable product of the value sets and agree at every point, each a rectangle {x1}×⋯×{xn}\{x_1\} \times \cdots \times \{x_n\}. By σ-additivity they agree on all Borel sets, and the product-law theorem applies. ■\blacksquare

∎

In tables: independence is rank one

For two discrete variables with joint table P=(pij)\mat{P} = (p_{ij}), factorization (c) says pij=piqjp_{ij} = p_i q_j, that is P=pq⊤\mat{P} = \vb{p}\vb{q}\T: an outer product, a rank-one matrix. Conversely, a rank-one matrix with nonnegative entries summing to 11 is P=uv⊤\mat{P} = \vb{u}\vb{v}\T, and its marginals are u (1⊤v)\vb{u}\,(\vb{1}\T\vb{v}) and v (1⊤u)\vb{v}\,(\vb{1}\T\vb{u}), so P\mat{P} is the product of its marginals (because (1⊤u)(1⊤v)=1(\vb{1}\T\vb{u})(\vb{1}\T\vb{v}) = 1). Thus independence is equivalent to rank one, detectable using linear algebra: the second singular value of the SVD is σ2=0\sigma_2 = 0, or more elementarily every minor 2×22 \times 2 pijpkl−pilpkjp_{ij}p_{kl} - p_{il}p_{kj} vanishes (the odds ratio pijpkl/(pilpkj)p_{ij}p_{kl}/(p_{il}p_{kj}) is 11: no interaction between xx and yy).

InteractiveIndependence as rank one
Joint P\mat{P} (rows == values of YY)
0.0760.1820.0230.1630.0740.0240.0960.0970.0150.0580.0820.0110.0060.0610.0120.0210.440.290.170.100.170.330.210.29
Product of marginals pXpY⊤\vb{p}_X\vb{p}_Y\T
0.0760.1440.0940.1290.0500.0940.0620.0850.0280.0540.0350.0480.0170.0330.0210.0290.440.290.170.100.170.330.210.29
Singular values of P\mat{P}
0.000.150.300.297σ₁0.111σ₂0.069σ₃0.000σ₄
  • red cells: P(x,y)≠pX(x)pY(y)\Pr(x, y) \ne p_X(x)p_Y(y)
  • σ1\sigma_1
  • σ2,σ3,σ4\sigma_2, \sigma_3, \sigma_4: zero if and only if independent
  • marginal of YY (right)
  • marginal of XX (bottom)
Starting table
0.00
Rank of P\mat{P}3
σ2/σ1\sigma_2 / \sigma_10.3750
Largest 2×22 \times 2 minor0.01694
I(X;Y)I(X; Y)0.2364 bits
∥P−pXpY⊤∥F\norm{\mat{P} - \vb{p}_X\vb{p}_Y\T}_F0.1389
Best rank one (Eckart–Young), error0.1308
Rank 3: there is dependence because σ2/σ1=0.375\sigma_2 / \sigma_1 = 0.375 is nonzero and the largest 2×22 \times 2 minor equals 0.01690.0169 instead of 00. Mixing with the product does not reduce rank until exactly λ=1\lambda = 1.
Edit the joint table of two discrete variables by dragging each cell up or down (or using arrow keys). At right are the product of its marginals and the table's singular values. Select the product preset: how many singular values are nonzero? Start with almost product: is the rank one? What are σ2/σ1\sigma_2/\sigma_1 and the remaining mutual information? Adjust the mixture λ\lambda with the product: distance to the product falls linearly, but at exactly which point does rank become one? Compare the error of the best rank-one approximation (Eckart–Young) with distance to the product of marginals: are they equal?

The figure reveals a detail. The product of marginals pXpY⊤\vb{p}_X\vb{p}_Y\T is the product law closest to P\mat{P} in Kullback–Leibler divergence (it minimizes KL⁡(P ∥ ab⊤)\KL(\mat{P} \,\|\, \vb{a}\vb{b}\T) among products, with minimum mutual information). But it is not the closest rank-one matrix in Frobenius norm: that is the truncated singular value decomposition σ1u1v1⊤\sigma_1 \vb{u}_1\vb{v}_1\T (Eckart–Young theorem). The first is a probability law with the same marginals, while the second generally has neither its marginals nor sum 11. Each solves a different problem, so the error of the best rank-one approximation never exceeds the distance to the product of marginals.

Functions of independent variables

Independence is a property of σ-algebras, and transforming variables only makes them smaller. This proves a consequence often used without mention.

Proof

(a) σ(gi(Xi))⊂σ(Xi)\sigma(g_i(X_i)) \subset \sigma(X_i), and a subfamily of smaller independent σ-algebras remains independent. (b) By the product-law theorem, PX=⨂iPXi\Pr_{\vb{X}} = \bigotimes_i \Pr_{X_i}. Grouping by blocks is associativity of the product: each block vector’s law is ⨂i∈IkPXi\bigotimes_{i \in I_k} \Pr_{X_i} (obtained by marginalizing), and the product of block laws agrees with ⨂iPXi\bigotimes_i \Pr_{X_i} on rectangles, hence everywhere (by π-λ). The block vectors are therefore independent, and by (a), so are any Borel functions of each. ■\blacksquare

∎

Pairwise independence is not mutual independence

The product law ⨂iPXi\bigotimes_i \Pr_{X_i} factorizes all subfamilies simultaneously. Pairwise factorization can make it look true, but is insufficient. Let X,YX, Y be independent fair coins and Z=X⊕YZ = X \oplus Y (exclusive or): each pair is independent (the table of (X,Z)(X, Z) has four cells of 1/41/4), but the triple is not, because (X,Y,Z)(X, Y, Z) takes only four of eight possible values, each with probability 1/41/4, whereas the product law of marginals assigns 1/81/8 to each of eight. This is the XOR interactive from the conditioning lesson, in the language of laws: P(X,Y,Z)≠PX⊗PY⊗PZ\Pr_{(X, Y, Z)} \ne \Pr_X \otimes \Pr_Y \otimes \Pr_Z even though all pairwise marginals are products. In machine learning, the mistake is checking feature independence only in pairs (with tests or two-way tables) and then treating the full set as independent: a label that is the XOR of two features is invisible to pairwise analysis.

Sums of independent variables

A typical use of Tonelli with the product law: if X⊥ ⁣ ⁣ ⁣⊥YX \indep Y, the distribution function of X+YX + Y is

P(X+Y≤s)=∫R21[x+y≤s] (PX⊗PY)( ⁣dx, ⁣dy)=∫RFX(s−y) PY( ⁣dy).\Pr(X + Y \le s) = \int_{\R^2} \ind[x + y \le s]\,(\Pr_X \otimes \Pr_Y)(\dd x, \dd y) = \int_{\R} F_X(s - y)\,\Pr_Y(\dd y).

Integrate first over xx (for fixed yy it is the measure of the half-line (−∞,s−y](-\infty, s - y], namely FX(s−y)F_X(s - y)), then over yy. If XX and YY have densities fXf_X and fYf_Y, differentiation gives convolution fX+Y(s)=∫fX(s−y)fY(y)  ⁣dyf_{X + Y}(s) = \int f_X(s - y) f_Y(y)\,\dd y, studied in the random-variable transformations lesson. With X,Y∼iidUnif⁡(0,1)X, Y \iid \Unif(0, 1) and s=1.5s = 1.5, FX(1.5−y)=1F_X(1.5 - y) = 1 if y≤0.5y \le 0.5 and 1.5−y1.5 - y if 0.5<y≤10.5 < y \le 1, so P(X+Y≤1.5)=0.5+∫0.51(1.5−y)  ⁣dy=0.875\Pr(X + Y \le 1.5) = 0.5 + \int_{0.5}^1 (1.5 - y)\,\dd y = 0.875. This is the area of a square minus the corner of a triangle with legs 0.50.5: 1−12⋅0.251 - \tfrac12 \cdot 0.25.

Expectation of a product and the tail formula

For two independent variables and functions of each, expectation (the Lebesgue integral with respect to P\Pr) factorizes. This is the most frequent use of Fubini in the course.

Proof

By change of variables for pushforward measures, E[ϕ(X,Y)]=∫ϕ  ⁣dP(X,Y)\E[\phi(X, Y)] = \int \phi\,\dd \Pr_{(X, Y)}, and by independence P(X,Y)=PX⊗PY\Pr_{(X, Y)} = \Pr_X \otimes \Pr_Y. For g,h≥0g, h \ge 0, Tonelli gives E[g(X)h(Y)]=∫ ⁣ ⁣∫g(x)h(y) PX( ⁣dx)PY( ⁣dy)=(∫g  ⁣dPX)(∫h  ⁣dPY)\E[g(X)h(Y)] = \int\!\!\int g(x)h(y)\,\Pr_X(\dd x)\Pr_Y(\dd y) = \big(\int g\,\dd\Pr_X\big)\big(\int h\,\dd \Pr_Y\big). Applied to ∣x∣\abs{x} and ∣y∣\abs{y}, it gives E[∣XY∣]=E∣X∣ E∣Y∣<∞\E[\abs{XY}] = \E\abs{X}\,\E\abs{Y} < \infty, so XY∈L1(PX⊗PY)XY \in L^1(\Pr_X \otimes \Pr_Y) and Fubini permits the same signed calculation. ■\blacksquare

∎

The converse is false, sufficiently so to deserve the following rule. If Z∼N(0,1)Z \sim \Normal(0, 1), E[Z⋅Z2]=E[Z3]=0=E[Z]E[Z2]\E[Z \cdot Z^2] = \E[Z^3] = 0 = \E[Z]\E[Z^2], yet ZZ and Z2Z^2 are far from independent: E[Z2⋅Z2]=3≠1=E[Z2]2\E[Z^2 \cdot Z^2] = 3 \ne 1 = \E[Z^2]^2. Independence is E[g(X)h(Y)]=E[g(X)]E[h(Y)]\E[g(X)h(Y)] = \E[g(X)]\E[h(Y)] for all bounded functions gg and hh (indicators suffice, by definition), while g(x)=xg(x) = x, h(y)=yh(y) = y is only one case.

The tail formula

The second use of Tonelli calculates expectation by changing the geometry of the problem: instead of integrating xx against the law, integrate the probability of exceeding a threshold.

Proof

For each ω\omega, X(ω)=∫0∞1[t<X(ω)]  ⁣dtX(\omega) = \int_0^\infty \ind[t < X(\omega)]\,\dd t (the length of interval [0,X(ω))[0, X(\omega))). Function (ω,t)↦1[t<X(ω)](\omega, t) \mapsto \ind[t < X(\omega)] is measurable with respect to F⊗B([0,∞))\mathcal{F} \otimes \mathcal{B}([0, \infty)) because {(ω,t):X(ω)−t>0}\{(\omega, t) : X(\omega) - t > 0\} is the positivity set of (ω,t)↦X(ω)−t(\omega, t) \mapsto X(\omega) - t, a difference of measurable functions on the product. Since it is nonnegative and P\Pr and λ\lambda are σ-finite, Tonelli allows integration in ω\omega first:

E[X]=∫Ω∫0∞1[t<X(ω)]  ⁣dt P( ⁣dω)=∫0∞P(X>t)  ⁣dt.■\E[X] = \int_\Omega \int_0^\infty \ind[t < X(\omega)]\,\dd t\,\Pr(\dd \omega) = \int_0^\infty \Pr(X > t)\,\dd t. \qquad \blacksquare∎

Picture a region in plane (ω,t)(\omega, t) below the graph of XX. Expectation is its area cut into columns (for each ω\omega, average height X(ω)X(\omega)) or into layers (for each level tt, the fraction of ω\omega exceeding it). Tonelli says both agree. The interactive constructs this region from samples.

InteractiveExpectation as area under the tail
Columns: the first 50 samples XiX_i (height =Xi= X_i)
024t* = 1.65: 10 of 50 columns exceed itsample index
Layers: p tp−1P(X>t)p\,t^{p-1}\Pr(X > t) (area =E[Xp]= \E[X^p]), with p=1.00p = 1.00
00.50024t
  • columns below t∗t^*
  • columns above t∗t^*
  • p tp−1S^n(t)p\,t^{p-1}\hat S_n(t) (empirical)
  • p tp−1S(t)p\,t^{p-1}S(t) (exact)
Law of X≥0X \ge 0
1.00
1.5
1.65
Samples nn
E[Xp]\E[X^p] exact1.0000
Mean of XipX_i^p, n=50n = 50 (columns)1.0112
Total area under p tp−1S^np\,t^{p-1}\hat S_n (layers)1.0112
Exact area under p tp−1Sp\,t^{p-1}S up to tmax⁡t_{\max}0.9909
P(X>t∗)\Pr(X > t^*) exact and empirical0.193 and 0.200
The two calculations agree: the mean of XipX_i^p (columns) and the area under p tp−1S^n(t)p\,t^{p-1}\hat S_n(t) (layers) are the same number because this exchanges integration order in the region {(ω,t):t<X(ω)}\{(\omega, t) : t < X(\omega)\}.
Left: samples of a variable X≥0X \ge 0 as columns of height XiX_i; move level t∗t^* and see the fraction of columns exceeding it. Enable decreasing order: the silhouette is the survival function turned on its side. Right: the curve p tp−1P(X>t)p\,t^{p-1}\Pr(X > t) whose area is E[Xp]\E[X^p], exact and empirical. Compare the mean of XipX_i^p with the area under the empirical curve: why do they always agree for any sample? Choose Pareto and lower α\alpha to 0.80.8, or raise pp above α\alpha: what happens to area and sample mean as nn increases?

Four useful applications. For a variable with values in {0,1,2,… }\{0, 1, 2, \dots\}, E[N]=∑k≥1P(N≥k)\E[N] = \sum_{k \ge 1}\Pr(N \ge k) (the tail formula with counting measure). For an exponential with rate λ\lambda, P(X>t)=e−λt\Pr(X > t) = e^{-\lambda t} and E[X]=∫0∞e−λt  ⁣dt=1/λ\E[X] = \int_0^\infty e^{-\lambda t}\,\dd t = 1/\lambda. For truncation min⁡(X,c)\min(X, c), E[min⁡(X,c)]=∫0cP(X>t)  ⁣dt\E[\min(X, c)] = \int_0^c \Pr(X > t)\,\dd t (used in finance and reward clipping). And for integrability: X≥0X \ge 0 is integrable if and only if ∑n≥1P(X≥n)<∞\sum_{n \ge 1} \Pr(X \ge n) < \infty, because E⌊X⌋≤E[X]≤E⌊X⌋+1\E\lfloor X \rfloor \le \E[X] \le \E\lfloor X \rfloor + 1 and E⌊X⌋=∑n≥1P(X≥n)\E\lfloor X \rfloor = \sum_{n \ge 1}\Pr(X \ge n). With tail P(X>t)=t−α\Pr(X > t) = t^{-\alpha} for t≥1t \ge 1 (Pareto), expectation equals α/(α−1)\alpha/(\alpha - 1) if α>1\alpha > 1 and is infinite if α≤1\alpha \le 1. This appears in the figure and in heavy-tailed rewards.

Infinite sequences and Kolmogorov’s theorem

So far everything was a vector of finite length nn, and product P⊗nP^{\otimes n} exists by Tonelli. But nearly every asymptotic result speaks of an infinite sequence X1,X2,…X_1, X_2, \dots of variables independent on the same space: the law of large numbers, the central limit theorem, learning from unlimited data. Does such a probability space exist? A two-factor product measure does not settle this, and infinitely many factors cannot be constructed by iteration.

The natural space is Ω=RN\Omega = \R^{\N}, the space of real sequences ω=(ω1,ω2,… )\omega = (\omega_1, \omega_2, \dots), with product σ-algebra B(R)⊗N\mathcal{B}(\R)^{\otimes \N} generated by cylinders

Cn(A)={ω:(ω1,…,ωn)∈A},A∈B(Rn), n≥1.C_n(A) = \{\omega : (\omega_1, \dots, \omega_n) \in A\}, \qquad A \in \mathcal{B}(\R^n),\ n \ge 1.

Variables Xk(ω)=ωkX_k(\omega) = \omega_k are the coordinates. To define a probability on this space, specify every cylinder’s value; these values cannot be arbitrary: the probability of {(ω1,…,ωn)∈A}\{(\omega_1, \dots, \omega_n) \in A\} cannot depend on whether it is viewed as a cylinder of nn or n+1n + 1 coordinates, because Cn(A)=Cn+1(A×R)C_n(A) = C_{n+1}(A \times \R).

Kolmogorov’s extension theorem is an existence theorem based on Carathéodory extension: defining P\Pr on the algebra of cylinders is easy; σ-additivity is hard.

Proof

Uniqueness. Cylinders form a π-system generating B(R)⊗N\mathcal{B}(\R)^{\otimes \N} (the intersection of cylinders is a cylinder: write them with the same nn and intersect the sets). Probabilities agreeing there are equal (π-λ).

Definition on the algebra. Let C\mathcal{C} be the algebra of cylinders. Define P0(Cn(A))=Pn(A)\Pr_0(C_n(A)) = \Pr_n(A). It is well defined: if Cn(A)=Cm(B)C_n(A) = C_m(B) with n<mn < m, then B=A×Rm−nB = A \times \R^{m-n} and applying consistency m−nm - n times gives Pm(B)=Pn(A)\Pr_m(B) = \Pr_n(A). It is finitely additive (write two disjoint cylinders with the same nn and use additivity of Pn\Pr_n) and P0(Ω)=1\Pr_0(\Omega) = 1.

σ-additivity. By Carathéodory’s theorem, it suffices to show P0\Pr_0 is continuous at the empty set: if Ck∈CC_k \in \mathcal{C} decrease to ∅\emptyset, then P0(Ck)→0\Pr_0(C_k) \to 0. Suppose otherwise: P0(Ck)≥ε>0\Pr_0(C_k) \ge \varepsilon > 0 for every kk. Write Ck=Cnk(Ak)C_k = C_{n_k}(A_k) with n1<n2<⋯n_1 < n_2 < \cdots (coordinates may be added using factors R\R). Every probability on Rn\R^n is regular: for Borel AA and δ>0\delta > 0 there is a compact K⊂AK \subset A with Pn(A∖K)<δ\Pr_n(A \setminus K) < \delta (approximate from inside by closed sets and intersect with a large box that carries almost all mass by continuity of probability). Choose compacts Kk⊂AkK_k \subset A_k with Pnk(Ak∖Kk)<ε 2−k−1\Pr_{n_k}(A_k \setminus K_k) < \varepsilon\,2^{-k-1} and set Dk=Cnk(Kk)⊂CkD_k = C_{n_k}(K_k) \subset C_k and Ek=D1∩⋯∩DkE_k = D_1 \cap \cdots \cap D_k. Since Ck⊂CjC_k \subset C_j if j≤kj \le k, Ck∖Ek⊂⋃j≤k(Cj∖Dj)C_k \setminus E_k \subset \bigcup_{j \le k}(C_j \setminus D_j), so P0(Ck∖Ek)<ε/2\Pr_0(C_k \setminus E_k) < \varepsilon/2 and P0(Ek)≥ε/2>0\Pr_0(E_k) \ge \varepsilon/2 > 0: every EkE_k is nonempty.

Choose ω(k)∈Ek\omega^{(k)} \in E_k. For each j≤kj \le k, (ω1(k),…,ωnj(k))∈Kj(\omega^{(k)}_1, \dots, \omega^{(k)}_{n_j}) \in K_j, which is compact. A diagonal argument extracts a coordinatewise convergent subsequence of (ω(k))(\omega^{(k)}): first a subsequence whose first n1n_1 coordinates converge (compactness of K1K_1), then one of that subsequence for n2n_2 coordinates, and so on; the diagonal makes all converge. Its limit ω∗\omega^* satisfies (ω1∗,…,ωnj∗)∈Kj(\omega^*_1, \dots, \omega^*_{n_j}) \in K_j for every jj (the KjK_j are closed), that is, ω∗∈Dj⊂Cj\omega^* \in D_j \subset C_j for every jj. But ⋂jCj=∅\bigcap_j C_j = \emptyset, a contradiction. ■\blacksquare

∎

Consequence: iid sequences exist. If μ\mu is a probability on R\R, the family Pn=μ⊗n\Pr_n = \mu^{\otimes n} is consistent because μ⊗(n+1)(A×R)=μ⊗n(A)μ(R)=μ⊗n(A)\mu^{\otimes (n+1)}(A \times \R) = \mu^{\otimes n}(A)\mu(\R) = \mu^{\otimes n}(A). The theorem gives a probability μ⊗N\mu^{\otimes \N} on RN\R^{\N}, and on (RN,B⊗N,μ⊗N)(\R^{\N}, \mathcal{B}^{\otimes \N}, \mu^{\otimes \N}) coordinates Xk(ω)=ωkX_k(\omega) = \omega_k are independent, each with law μ\mu: their finite-dimensional laws are μ⊗n\mu^{\otimes n}. From now on, “let X1,X2,…X_1, X_2, \dots be an iid sequence” is a legitimate statement.

Two observations about the theorem’s scope:

  • Consistency is essential. The family P1=Bern⁡(0.3)\Pr_1 = \Bern(0.3), P2=Bern⁡(1/2)⊗2\Pr_2 = \Bern(1/2)^{\otimes 2} is not consistent (the first marginal of P2\Pr_2 is Bern⁡(1/2)\Bern(1/2)) and is no process’s law. The families used later (iid, Markov chains, Gaussians with a given covariance) are consistent by construction; the cell below checks this with tensors. For Markov chains and decision trajectories (RL), when laws are specified by transition kernels rather than joint-law families, the Ionescu–Tulcea theorem plays the same role.
  • With uncountable indices, it sees only what depends on countably many coordinates. For sequences there is no problem: B(R)⊗N\mathcal{B}(\R)^{\otimes \N} contains events such as “Xk→0X_k \to 0” or “sup⁡kXk>1\sup_k X_k > 1”. The theorem has a version for arbitrary indices such as t∈[0,1]t \in [0, 1], on R[0,1]\R^{[0, 1]} with its product σ-algebra, but each measurable event there is determined by countably many coordinates. An event such as “the path is continuous” depends on all coordinates and is not measurable. Brownian motion thus needs Kolmogorov plus a continuity argument, covered in the processes module. Existence itself is the same.

For those preferring not to use the theorem for iid sequences: a single uniform variable U∼Unif⁡(0,1)U \sim \Unif(0, 1) contains an iid bit sequence: its binary digits b1(U),b2(U),…b_1(U), b_2(U), \dots (used to construct the Cantor law in the random variables lesson) are independent with law Bern⁡(1/2)\Bern(1/2), and splitting digits into infinitely many disjoint index sets yields infinitely many independent uniform variables. This is another existence proof using only Lebesgue measure on [0,1][0, 1].

Implementation from scratch

A discrete joint law of nn variables is a tensor with nn axes. Marginalizing sums over axes, the product law is an outer product, and mutual independence is their equality. The code is as short as the theory, and should be explicit because np.einsum or scipy.stats conceal exactly these operations.

[ ]Joint laws as tensors: marginals, product, independence and consistencyBrowser
import numpy as np
from itertools import product, combinations

def marginal(P, keep):
    """Ley de las variables en los ejes `keep`: se suma sobre todos los demás."""
    drop = tuple(a for a in range(P.ndim) if a not in keep)
    return P.sum(axis=drop)

def product_law(margs):
    """Medida producto discreta: producto exterior de las marginales."""
    out = np.array(1.0)
    for m in margs:
        out = np.multiply.outer(out, m)
    return out

def mutual_independence(P, tol=1e-12):
    """¿Es P la ley producto de sus marginales unidimensionales? (independencia mutua)."""
    return bool(np.abs(P - product_law([marginal(P, [a]) for a in range(P.ndim)])).max() < tol)

def pairwise_independence(P, tol=1e-12):
    return {(a, b): bool(np.abs(marginal(P, [a, b]) - np.multiply.outer(marginal(P, [a]), marginal(P, [b]))).max() < tol)
            for a, b in combinations(range(P.ndim), 2)}

xor = np.zeros((2, 2, 2))
for x, y in product((0, 1), repeat=2):
    xor[x, y, x ^ y] = 0.25                                   # X, Y monedas justas, Z = X xor Y
iid = product_law([np.array([0.5, 0.5])] * 3)
copia = np.zeros((2, 2, 2)); copia[0, 0, 0] = copia[1, 1, 1] = 0.5   # X = Y = Z

for nombre, P in {"iid": iid, "xor": xor, "copia": copia}.items():
    print(f"{nombre:6s} suma = {P.sum():.2f}  mutua: {mutual_independence(P)!s:5}  pares:", pairwise_independence(P))
print("marginal de (X, Z) en la ley xor:\n", marginal(xor, [0, 2]))
print("puntos con masa: ley xor =", int((xor > 0).sum()), "  producto de sus marginales =", int((product_law([marginal(xor, [a]) for a in range(3)]) > 0).sum()))

# Consistencia de Kolmogórov: la marginal de P_{n+1} sobre las n primeras coordenadas debe ser P_n
def consistente(familia, tol=1e-12):
    return all(np.abs(familia[n].sum(axis=-1) - familia[n - 1]).max() < tol for n in range(1, len(familia)))

bern = lambda p: np.array([1 - p, p])
T = np.array([[0.9, 0.1], [0.4, 0.6]])                          # matriz de transición de una cadena de Markov

def markov(n, inicial=np.array([0.5, 0.5])):
    P = inicial.copy()
    for _ in range(n - 1):
        P = P[..., :, None] * T                                 # añade X_{k+1} con el núcleo T(x_k, x_{k+1})
    return P

f_iid = [product_law([bern(0.3)] * n) for n in range(1, 5)]
f_mk = [markov(n) for n in range(1, 5)]
f_mal = [bern(0.3), product_law([bern(0.5)] * 2), product_law([bern(0.5)] * 3)]
print("\niid:", consistente(f_iid), "  Markov:", consistente(f_mk), "  P_1 = Bern(0.3) con P_2 = Bern(1/2)^2:", consistente(f_mal))

Law xor passes independence tests on all three pairs and fails as a triple: it has four points with mass, while the product of marginals has eight. The iid family and Markov chain are consistent; the third is not, motivating the assumption in Kolmogorov’s theorem. The next cell checks the tail formula and product expectation by simulation, and the identity is exact, not statistical: the empirical survival function is a step function, so its integral weighted by p tp−1p\,t^{p-1} is computed without error and must agree with the average of XipX_i^p for every sample.

[ ]Tail formula, product expectation, and why Z and Z² are not independentBrowser
from scipy import special

rng = np.random.default_rng(5)
n = 100_000
X = rng.exponential(1.0, n)

def tail_integral(X, p):
    """∫ p t^(p-1) S_n(t) dt con S_n la supervivencia empírica. S_n es escalonada: la integral es exacta."""
    xs = np.sort(X)
    nn = len(xs)
    bordes = np.concatenate(([0.0], xs))
    S = 1 - np.arange(nn + 1) / nn                  # S_n vale (nn - k)/nn entre x_(k) y x_(k+1)
    return float(np.sum(S[:-1] * (bordes[1:] ** p - bordes[:-1] ** p)))

for p in (1, 2, 2.5):
    print(f"p = {p}: media de X^p = {np.mean(X**p):.5f}   integral de colas = {tail_integral(X, p):.5f}   Gamma(p + 1) = {special.gamma(p + 1):.5f}")

Xi, Yi = rng.exponential(1.0, n), rng.uniform(0, 2, n)
print("\nindependientes: E[XY] =", round(float(np.mean(Xi * Yi)), 4), "  E[X] E[Y] =", round(float(Xi.mean() * Yi.mean()), 4), " (exacto: 1)")
Z = rng.standard_normal(n)
print("Z y Z^2 incorrelacionadas: E[Z Z^2] =", round(float(np.mean(Z**3)), 4), "  E[Z] E[Z^2] =", round(float(Z.mean() * np.mean(Z**2)), 4))
print("pero no independientes: E[Z^2 Z^2] =", round(float(np.mean(Z**4)), 3), " frente a E[Z^2]^2 =", round(float(np.mean(Z**2) ** 2), 3), " (exacto: 3 y 1)")

The first two columns agree in every decimal place: this is Tonelli, not a statistical approximation. What is statistical is how both approach Γ(p+1)\Gamma(p + 1), the exact expectation of XpX^p for the exponential. The preceding block’s last line gives the warning numerically.

Independent streams in parallel simulations

A parallel simulation needs many random streams independent of one another and reproducible: results should depend on seed and task index, not on which process finishes first. This follows directly from the lesson: task numbers should be an independent family, meaning their joint law is the product of their laws. A pseudorandom generator is a deterministic function of its state, so independence is not automatic and depends on initial states.

A small generator shows the mechanism. mulberry32 has a 32-bit state advancing by addition of a constant STEP and mixing the result with bit operations. Seeds ss and s+2 STEPs + 2\,\text{STEP} produce the same stream shifted by two positions. The next two cells measure this with cross-correlation (whose peak reveals the overlap) and an experiment using the streams: two processes estimating π\pi with 100100 points, whose average should have half the variance of each.

[ ]A 32-bit generator from scratch: identical, overlapping and derived seedsBrowser
MASK = 0xFFFFFFFF
STEP = 0x6D2B79F5

def mulberry32(seed):
    """Generador de 32 bits de estado: flujo infinito de uniformes en [0, 1)."""
    a = seed & MASK
    while True:
        a = (a + STEP) & MASK
        t = a
        t = ((t ^ (t >> 15)) * (t | 1)) & MASK
        t ^= (t + ((t ^ (t >> 7)) * (t | 61) & MASK)) & MASK
        yield ((t ^ (t >> 14)) & MASK) / 4294967296

def flujo(seed, n):
    g = mulberry32(seed)
    return np.array([next(g) for _ in range(n)])

def hash32(a, b):
    """Mezcla de 32 bits de (semilla, índice): una semilla hija por tarea (idea de SeedSequence.spawn)."""
    h = (a ^ (((b + 0x9E3779B9) & MASK) * 0x85EBCA6B & MASK)) & MASK
    h = ((h ^ (h >> 16)) * 0x85EBCA6B) & MASK
    h = ((h ^ (h >> 13)) * 0xC2B2AE35) & MASK
    return (h ^ (h >> 16)) & MASK

def corr_cruzada(A, B, lags=3):
    n = len(A) - 2 * lags
    return {l: round(float(np.corrcoef(A[lags:lags + n], B[lags + l:lags + l + n])[0, 1]), 2) for l in range(-lags, lags + 1)}

s = hash32(2024, 0)
A = flujo(s, 406)
casos = {"misma semilla": s, "s + 1": (s + 1) & MASK, "s + 2 pasos": (s + 2 * STEP) & MASK, "hash(2024, 1)": hash32(2024, 1)}
for nombre, sb in casos.items():
    print(f"{nombre:14s}", corr_cruzada(A, flujo(sb, 406)))

def pi_hat(u, m):
    return 4 * np.mean(u[0:2 * m:2] ** 2 + u[1:2 * m:2] ** 2 < 1)

def experimento(esquema, R=300, m=100):
    ea, eb = [], []
    for r in range(R):
        a = hash32(77, r)
        b = {"misma": a, "solape": (a + 2 * STEP) & MASK, "hash": hash32(78, r)}[esquema]
        ea.append(pi_hat(flujo(a, 2 * m), m))
        eb.append(pi_hat(flujo(b, 2 * m), m))
    ea, eb = np.array(ea), np.array(eb)
    return np.corrcoef(ea, eb)[0, 1], np.var((ea + eb) / 2) / np.var(ea)

print()
for esq in ("misma", "solape", "hash"):
    c, r = experimento(esq)
    print(f"{esq:7s} corr(estimaciones) = {c:6.3f}   Var(promedio) / Var(uno) = {r:.2f}")

With the same seed, correlation at lag 00 is exactly 11. With ss and s+2 STEPs + 2\,\text{STEP} the peak is at lag −2-2 and equals 11: the cloud of pairs (Ak,Bk)(A_k, B_k) at lag 00 looks perfectly random, and the defect appears only at the correct lag (or practically when the mean of two processes does not reduce variance: the ratio is 1.001.00 instead of ≈0.5\approx 0.5). With s+1s + 1 nothing visible happens because this generator mixes its state well: that is a generator property, not a guarantee, so do not habitually seed with “semilla + índice”. With hash-derived seeds, estimates are independent: correlations are within noise and the variance ratio is ≈0.5\approx 0.5.

InteractiveAre two random streams independent?
Pairs (Ak,Bk)(A_k, B_k) from the two streams
0.00.00.50.51.01.0
Cross-correlation corr(Ak,Bk+ℓ)\mathrm{corr}(A_k, B_{k+\ell}) by lag ℓ\ell
0.00.51.0−6−4−201.00246desfase ℓ
π\pi estimates: process AA versus BB
2.42.43.13.13.93.9
  • small correlation (noise, ≈1/400\approx 1/\sqrt{400})
  • large correlation: overlap
  • diagonal: identical estimates (300 repetitions of 100 points)
How the two processes are seeded
100
10⁹
Correlation of (Ak,Bk)(A_k, B_k) (lag 0)1.000
Cross-correlation peak1.00 at lag 0
Correlation of the two π\pi estimates1.000
Var⁡\Var(average) / Var⁡\Var(one process)1.00
Overlap probability, 32-bit state (cycle 2322^{32})≈ 1
Overlap probability, 128-bit state (like PCG64)2.9·10⁻²⁶
Both processes generate exactly the same numbers: ρ=1\rho = 1 at lag 00 and pairs fall on the diagonal. Averaging estimates does not reduce variance (ratio ≈1\approx 1 rather than 1/21/2).
Two parallel processes receive seeds under four schemes. Inspect three views: the cloud of pairs (Ak,Bk)(A_k, B_k), cross-correlation by lag, and each process's estimates of π\pi across 300 repetitions. With the same seed the defect appears in all three. With ss and s+2s + 2 steps, the cloud on the left looks perfect: which of the other views reveals the defect? What variance ratio does the average of the processes have in each scheme, and what is expected for independent variables? Below is the birthday bound: with WW processes of LL numbers each and random seeds, what is the overlap probability for 32 and 128 bits of state?

The calculation below the figure is a birthday bound. If each stream is a segment of length LL of a cycle of length M=2bM = 2^b and starting points are uniform and independent, two segments overlap with probability ≈2L/M\approx 2L/M; among WW processes there are (W2)\binom{W}{2} pairs: P(solape)≲(W2) 2L/2b\Pr(\text{solape}) \lesssim \binom{W}{2}\,2L/2^b. With b=32b = 32, a thousand processes with 10610^6 numbers each almost surely overlap: (10002)⋅2⋅106/232≈233\binom{1000}{2} \cdot 2 \cdot 10^6 / 2^{32} \approx 233 is the expected number of overlapping pairs, and the probability of no overlap is on the order of e−233e^{-233}. With b=128b = 128 the same calculation gives probability on the order of 3⋅10−273 \cdot 10^{-27}, negligible. A serious generator therefore has a large state and an explicit mechanism to derive distant initial states, rather than seeding directly with small integers.

Using libraries

NumPy implements exactly this idea. SeedSequence takes entropy (one or several integers) and mixes it with hash functions to fill the generator’s state; its spawn(k) method returns kk child sequences whose states depend only on entropy and index (so results do not depend on execution order, as the cell checks). Each child feeds an independent Generator. In recent versions (NumPy 1.25 or later), Generator.spawn(k) does the same directly on an existing generator.

[ ]SeedSequence.spawn: independent, reproducible streamsBrowser
ss = np.random.SeedSequence(2024)
hijos = ss.spawn(4)
rngs = [np.random.default_rng(h) for h in hijos]
M = np.array([g.random(20000) for g in rngs])
print("max |corr| entre flujos hijos distintos:", np.abs(np.corrcoef(M) - np.eye(4)).max().round(4), "  (desviación típica de cada correlación: 1/sqrt(20000) = 0.007)")

orden = [np.random.default_rng(h).random(3) for h in hijos]
inverso = [np.random.default_rng(h).random(3) for h in reversed(hijos)][::-1]
print("el resultado depende del índice del hijo, no del orden de ejecución:", all(np.array_equal(u, v) for u, v in zip(orden, inverso)))

g1, g2 = np.random.default_rng(7), np.random.default_rng(7)
print("la misma semilla da los mismos números (reproducible, y por eso nunca independiente):", np.array_equal(g1.random(5), g2.random(5)))
print("claves de los hijos:", [h.spawn_key for h in hijos], " entropía común:", hijos[0].entropy)

The pattern to copy in multi-process training or simulation is always the same: one experiment seed, one SeedSequence, one spawn with a child per task indexed by task number (not by the process executing it), and one Generator per child. Task kk then gives the same result on any process in any order, and tasks are independent. With several data-loading processes (such as workers of a DataLoader), each has its own NumPy, Python and PyTorch state, and a child created by copying inherits its parent’s state: unless reseeded, all workers produce the same numbers (recent PyTorch versions seed each worker from a base seed and index, though other libraries’ state is not always covered). Check with a cell like the one above that no two processes share a stream.

Common mistakes

Exercises

ProofIndependence and factorization of the distribution function
Prove: Let XX and YY be real random variables. Then X⊥ ⁣ ⁣ ⁣⊥YX \indep Y if and only if FX,Y(x,y)=FX(x) FY(y)F_{X, Y}(x, y) = F_X(x)\,F_Y(y) for every (x,y)∈R2(x, y) \in \R^2.
0
The forward implication follows from the definition. For the converse, compare two probabilities on R2\R^2 using the π-λ theorem.

Step 1 of 4. Which implication is immediate, and why?

ProofThe tail formula for moments
Prove: If X≥0X \ge 0 and p>0p > 0, then E[Xp]=∫0∞p tp−1P(X>t)  ⁣dt\E[X^p] = \int_0^\infty p\,t^{p-1}\Pr(X > t)\,\dd t, in [0,∞][0, \infty].
0
Write XpX^p as an integral over tt, check that Tonelli applies, and exchange the order.

Step 1 of 4. How can X(ω)pX(\omega)^p be written as an integral over tt of an indicator?

NumericThe sum of two uniforms
Let X,Y∼Unif⁡(0,1)X, Y \sim \Unif(0, 1) be independent. Calculate P(X+Y≤1.5)\Pr(X + Y \le 1.5).
P(X+Y≤s)=E[1[X+Y≤s]]\Pr(X + Y \le s) = \E\big[\ind[X + Y \le s]\big]
The probability of an event is the expectation of its indicator.
1/7
QuizWhich define independent variables?
Each joint density is a probability density on the stated domain and zero outside. In which are XX and YY independent?

More than one answer may be correct.

QuizCoins, XOR and three variables
X,YX, Y are independent fair coins (values 00 and 11) and Z=X⊕YZ = X \oplus Y (addition modulo 2). Which statements are true?

More than one answer may be correct.

CodeMarginals and deciding mutual independence
Implement analizar(P, tol=1e-9), which receives a joint pmf as a NumPy tensor (one axis per variable, sum 11) and returns a pair (margs, indep). margs is the list of one-dimensional marginal laws for each axis (one-dimensional arrays), and indep is True if variables are mutually independent, meaning the tensor agrees (to absolute tolerance tol) with the outer product of its marginals. Tests include independent laws, triple (X,Y,X⊕Y)(X, Y, X \oplus Y) (pairwise but not mutually independent), and a law with zeros.
import numpy as np

def analizar(P, tol=1e-9):
  """Devuelve (lista de marginales de cada eje, True si las variables son mutuamente independientes)."""
  # tu código: suma sobre todos los ejes salvo uno para cada marginal; compara P con el producto exterior
  return [], False
Shift+Enter to run
NumericExpectation of a truncation
Let XX be exponential with rate 22 and let Y=min⁡(X,3)Y = \min(X, 3) (the variable truncated at 33). Calculate E[Y]\E[Y] using the tail formula.
QuizWhen can the order be exchanged?
In which cases do Tonelli or Fubini guarantee that the two iterated sums or integrals agree?

More than one answer may be correct.

QuizWhich families are consistent?
For each nn, Pn\Pr_n is a probability on Rn\R^n. Which families satisfy Kolmogorov consistency (the marginal of Pn+1\Pr_{n+1} on the first nn coordinates is Pn\Pr_n)?

More than one answer may be correct.

Summary

Key idea
A random vector has a joint law on Rn\R^n whose marginals are pushforwards under projections; the joint law contains dependence that marginals cannot see. Variables are independent exactly when the joint law is the product of marginals, and Fubini–Tonelli allows integration order to be exchanged (always for nonnegative functions, for signed functions when integrable). Kolmogorov’s theorem guarantees infinite independent sequences exist; in code, this requires truly independent random streams.
  • The joint law of X=(X1,…,Xn)\vb{X} = (X_1, \dots, X_n) is a measure on Rn\R^n, and X\vb{X} is measurable if and only if every XiX_i is. The marginal is the pushforward under projection: sum or integrate over the remaining variables. The joint distribution function determines the law.
  • The joint law determines marginals, not conversely: infinitely many joint laws have the same marginals, only one of them independent.
  • The product σ-algebra is generated by rectangles. Product measure μ⊗ν\mu \otimes \nu exists and is unique (σ-finite measures) with (μ⊗ν)(A×B)=μ(A)ν(B)(\mu \otimes \nu)(A \times B) = \mu(A)\nu(B). For Lebesgue measure, λn=λ⊗n\lambda^n = \lambda^{\otimes n}.
  • Tonelli: for measurable f≥0f \ge 0, iterated integrals exist, are measurable and agree with the double integral (in [0,∞][0, \infty]). Fubini: likewise for f∈L1(μ⊗ν)f \in L^1(\mu \otimes \nu). Without integrability order may matter (00 versus 11 in the lesson’s matrix, π/4\pi/4 versus −π/4-\pi/4 for the continuous integrand).
  • X1,…,XnX_1, \dots, X_n are independent if and only if PX=⨂iPXi\Pr_{\vb{X}} = \bigotimes_i \Pr_{X_i}, also if and only if FX=∏iFXiF_{\vb{X}} = \prod_i F_{X_i}, or if and only if the density is ∏ifXi\prod_i f_{X_i} (including support). In discrete tables P=pq⊤\mat{P} = \vb{p}\vb{q}\T: rank one. Pairwise is not mutual independence, and functions of disjoint blocks of independent variables are independent.
  • If X⊥ ⁣ ⁣ ⁣⊥YX \indep Y and integrable, E[XY]=E[X]E[Y]\E[XY] = \E[X]\E[Y] (the converse is false: ZZ and Z2Z^2). Tail formula: E[Xp]=∫0∞p tp−1P(X>t)  ⁣dt\E[X^p] = \int_0^\infty p\,t^{p-1}\Pr(X > t)\,\dd t by Tonelli, possibly infinite (Pareto with p≥αp \ge \alpha).
  • Kolmogorov: a consistent family of finite-dimensional laws Pn\Pr_n on Rn\R^n defines a unique probability on RN\R^{\N}. In particular, iid sequences exist, with μ⊗N\mu^{\otimes \N}.
  • For parallel simulations: one experiment seed, SeedSequence.spawn one child per task indexed by its number, and one Generator per child. Same seed means same stream; nearby seeds do not guarantee independence.