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
- 04Measure and measure spaceLaw of a random variable (pushforward measure)Lebesgue integralExpectationIndependence of eventsProbability densityDynkin's π-λ theoremCarathéodory extension theoremMonotone convergence theoremCumulative distribution functionSigma-algebra generated by a random variable
- 03Multiple integralFubini theorem
Motivation: what does iid mean in a minibatch?
You train a network with minibatches of examples and write without thinking, “let 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 taking values in , and iid is a statement about its joint law. Given what you know, that law is a measure on ; the question is which one. This lesson answers four interdependent questions.
- Random vectors and joint laws. A random vector has a law on , 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.
- 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.
- Independence. Variables 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, ), along with the tail formula for expectation.
- 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
() and is continuous, hence Borel measurable. () Boxes generate , and of a box is . The generator criterion from the random variables lesson concludes the proof.
∎This is why one can say “ is a random variable” from “ and are random variables”, and why , or are measurable: they are compositions of a measurable vector with a continuous function. Also, the joint distribution function determines the joint law. Quadrants form a π-system generating (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 with nonnegative entries summing to ; the marginal of is obtained by summing over every other axis:
This is the total probability formula from the conditioning lesson applied to event and the partition by the other variables’ values; in NumPy it is P.sum(axis=...). With a joint Lebesgue density , the marginal is obtained by integrating 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 ; the dotted square is the area that would result if and were independent, .
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 and are measure spaces, the product has a natural σ-algebra: the one making the rectangles measurable for and . It is the σ-algebra generated by the two projections, the smallest one making them measurable.
For the line, : open rectangles generate the open sets of , and open sets generate the Borel sets. The same holds in every finite dimension, so . The next theorem states that a measure with that property exists and is unique, and contains half of Fubini–Tonelli.
Proof
Measurable sections. For and let be its section. Let be the class of such that for every and is -measurable. It contains rectangles because is if and otherwise, so . Rectangles are a π-system (the intersection of two rectangles is a rectangle). And is a Dynkin system: it contains ; if are in then and (here finiteness of is used); and if with , sections increase, and is a limit of measurable functions. By the π-λ theorem, . The same holds with the roles of and exchanged.
Existence. Let . This is a measure: , and if are disjoint, sections are disjoint and is σ-additive, so , and the monotone convergence theorem (for series of nonnegative functions) permits exchanging sum and integral. On rectangles, . Similarly, is another measure with the same values on rectangles.
Uniqueness and equality. and agree on the π-system of rectangles, which generates , and have the same total mass . By π-λ, , and any other measure with the product property agrees with them by the same argument. Call it . This is (a), and (b) for : .
Functions. By linearity, (b) holds for nonnegative simple functions. If is measurable, let be simple. By monotone convergence, for every , so the limit is measurable, and applying it again to the outer integrals gives equality for . Both iterated integrals agree with for the same reason.
σ-finite case. If and have finite, increasing measures, apply the preceding result to restrictions to and take using monotone convergence. Uniqueness holds because rectangles have finite measure and cover the product.
∎This explains why in probability nearly everything works without additional assumptions: probability measures and are finite. The σ-finite cases used here are Lebesgue and counting measures. With Lebesgue measure, on : 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 of is closed, hence Borel, and by Tonelli . Therefore the vector , with uniform on , has no density on 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 , . A nonnegative function with finite integral is finite almost everywhere, so for -almost every . Write . Tonelli gives equality of the iterated integrals for and , both finite, so they can be subtracted.
∎The theorem in the calculus lesson is the same result with Lebesgue measure. Assumption 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.
With decay the matrix is integrable: , and both iterated sums equal , tending to as . A decay-based summation method (Abel summation of the double series with the same factor on rows and columns) assigns the original matrix value , neither ordered sum. This is another way to see that and 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 on , whose iterated integrals equal and .
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 in total, and square blocks give at any size, while in the block grows like . In the continuous example the integrand is not integrable on (near the origin it behaves as in polar coordinates with measure , and ), and the two iterated integrals are opposite. Practical rule: for nonnegative functions use Tonelli; for others first verify by calculating it using Tonelli. Everything follows from that check.
Two immediate consequences
Tonelli gives the marginal formula for a joint density. Let have density relative to Lebesgue measure on , and . Then
so has density (defined almost everywhere), and similarly for . Marginalizing a density means integrating out the other variables. With 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 .
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 is independent if for any choice of (since every contains , this includes all subfamilies).
Taking 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 be the joint law and the product measure of the marginals (which exists uniquely by the previous theorem, applied iteratively). On a rectangle, , and . The definition of independence thus says exactly that the two probabilities agree on rectangles. Since rectangles are a π-system generating and both measures are probabilities, π-λ makes them equal on all . Conversely, if , evaluating on a rectangle gives factorization.
∎This is the claim at the start: a minibatch with is a random vector whose law is . 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) () evaluates the definition at . () Measures and agree on quadrants (the first by definition, the second by the product property), a generating π-system of , and have total mass . By π-λ they agree, and the previous theorem applies. The first exercise guides this proof step by step.
(b) If almost everywhere, with measurable , Tonelli gives for every rectangle. Taking shows , so each is finite and positive with , and , so , and rectangle probability is . Conversely, under independence, product measure has density (by the same Tonelli calculation, on rectangles then by π-λ), and equals , which has density . Two densities of the same measure agree almost everywhere (density uniqueness). (c) () is the definition with . () Measures and are concentrated on the countable product of the value sets and agree at every point, each a rectangle . By σ-additivity they agree on all Borel sets, and the product-law theorem applies.
∎In tables: independence is rank one
For two discrete variables with joint table , factorization (c) says , that is : an outer product, a rank-one matrix. Conversely, a rank-one matrix with nonnegative entries summing to is , and its marginals are and , so is the product of its marginals (because ). Thus independence is equivalent to rank one, detectable using linear algebra: the second singular value of the SVD is , or more elementarily every minor vanishes (the odds ratio is : no interaction between and ).
The figure reveals a detail. The product of marginals is the product law closest to in Kullback–Leibler divergence (it minimizes 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 (Eckart–Young theorem). The first is a probability law with the same marginals, while the second generally has neither its marginals nor sum . 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) , and a subfamily of smaller independent σ-algebras remains independent. (b) By the product-law theorem, . Grouping by blocks is associativity of the product: each block vector’s law is (obtained by marginalizing), and the product of block laws agrees with on rectangles, hence everywhere (by π-λ). The block vectors are therefore independent, and by (a), so are any Borel functions of each.
∎Pairwise independence is not mutual independence
The product law factorizes all subfamilies simultaneously. Pairwise factorization can make it look true, but is insufficient. Let be independent fair coins and (exclusive or): each pair is independent (the table of has four cells of ), but the triple is not, because takes only four of eight possible values, each with probability , whereas the product law of marginals assigns to each of eight. This is the XOR interactive from the conditioning lesson, in the language of laws: 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 , the distribution function of is
Integrate first over (for fixed it is the measure of the half-line , namely ), then over . If and have densities and , differentiation gives convolution , studied in the random-variable transformations lesson. With and , if and if , so . This is the area of a square minus the corner of a triangle with legs : .
Expectation of a product and the tail formula
For two independent variables and functions of each, expectation (the Lebesgue integral with respect to ) factorizes. This is the most frequent use of Fubini in the course.
Proof
By change of variables for pushforward measures, , and by independence . For , Tonelli gives . Applied to and , it gives , so and Fubini permits the same signed calculation.
∎The converse is false, sufficiently so to deserve the following rule. If , , yet and are far from independent: . Independence is for all bounded functions and (indicators suffice, by definition), while , is only one case.
The tail formula
The second use of Tonelli calculates expectation by changing the geometry of the problem: instead of integrating against the law, integrate the probability of exceeding a threshold.
Proof
For each , (the length of interval ). Function is measurable with respect to because is the positivity set of , a difference of measurable functions on the product. Since it is nonnegative and and are σ-finite, Tonelli allows integration in first:
∎Picture a region in plane below the graph of . Expectation is its area cut into columns (for each , average height ) or into layers (for each level , the fraction of exceeding it). Tonelli says both agree. The interactive constructs this region from samples.
Four useful applications. For a variable with values in , (the tail formula with counting measure). For an exponential with rate , and . For truncation , (used in finance and reward clipping). And for integrability: is integrable if and only if , because and . With tail for (Pareto), expectation equals if and is infinite if . 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 , and product exists by Tonelli. But nearly every asymptotic result speaks of an infinite sequence 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 , the space of real sequences , with product σ-algebra generated by cylinders
Variables are the coordinates. To define a probability on this space, specify every cylinder’s value; these values cannot be arbitrary: the probability of cannot depend on whether it is viewed as a cylinder of or coordinates, because .
Kolmogorov’s extension theorem is an existence theorem based on Carathéodory extension: defining on the algebra of cylinders is easy; σ-additivity is hard.
Proof
Uniqueness. Cylinders form a π-system generating (the intersection of cylinders is a cylinder: write them with the same and intersect the sets). Probabilities agreeing there are equal (π-λ).
Definition on the algebra. Let be the algebra of cylinders. Define . It is well defined: if with , then and applying consistency times gives . It is finitely additive (write two disjoint cylinders with the same and use additivity of ) and .
σ-additivity. By Carathéodory’s theorem, it suffices to show is continuous at the empty set: if decrease to , then . Suppose otherwise: for every . Write with (coordinates may be added using factors ). Every probability on is regular: for Borel and there is a compact with (approximate from inside by closed sets and intersect with a large box that carries almost all mass by continuity of probability). Choose compacts with and set and . Since if , , so and : every is nonempty.
Choose . For each , , which is compact. A diagonal argument extracts a coordinatewise convergent subsequence of : first a subsequence whose first coordinates converge (compactness of ), then one of that subsequence for coordinates, and so on; the diagonal makes all converge. Its limit satisfies for every (the are closed), that is, for every . But , a contradiction.
∎Consequence: iid sequences exist. If is a probability on , the family is consistent because . The theorem gives a probability on , and on coordinates are independent, each with law : their finite-dimensional laws are . From now on, “let be an iid sequence” is a legitimate statement.
Two observations about the theorem’s scope:
- Consistency is essential. The family , is not consistent (the first marginal of is ) 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: contains events such as “” or “”. The theorem has a version for arbitrary indices such as , on 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 contains an iid bit sequence: its binary digits (used to construct the Cantor law in the random variables lesson) are independent with law , 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 .
Implementation from scratch
A discrete joint law of variables is a tensor with 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.
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 is computed without error and must agree with the average of for every sample.
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 , the exact expectation of 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 and 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 with points, whose average should have half the variance of each.
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 is exactly . With and the peak is at lag and equals : the cloud of pairs at lag 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 instead of ). With 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 .
The calculation below the figure is a birthday bound. If each stream is a segment of length of a cycle of length and starting points are uniform and independent, two segments overlap with probability ; among processes there are pairs: . With , a thousand processes with numbers each almost surely overlap: is the expected number of overlapping pairs, and the probability of no overlap is on the order of . With the same calculation gives probability on the order of , 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 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.
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 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
Step 1 of 4. Which implication is immediate, and why?
Step 1 of 4. How can be written as an integral over of an indicator?
More than one answer may be correct.
More than one answer may be correct.
analizar(P, tol=1e-9), which receives a joint pmf as a NumPy tensor (one axis per variable, sum ) 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 (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 [], FalseMore than one answer may be correct.
More than one answer may be correct.
Summary
- The joint law of is a measure on , and is measurable if and only if every 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 exists and is unique (σ-finite measures) with . For Lebesgue measure, .
- Tonelli: for measurable , iterated integrals exist, are measurable and agree with the double integral (in ). Fubini: likewise for . Without integrability order may matter ( versus in the lesson’s matrix, versus for the continuous integrand).
- are independent if and only if , also if and only if , or if and only if the density is (including support). In discrete tables : rank one. Pairwise is not mutual independence, and functions of disjoint blocks of independent variables are independent.
- If and integrable, (the converse is false: and ). Tail formula: by Tonelli, possibly infinite (Pareto with ).
- Kolmogorov: a consistent family of finite-dimensional laws on defines a unique probability on . In particular, iid sequences exist, with .
- For parallel simulations: one experiment seed,
SeedSequence.spawnone child per task indexed by its number, and oneGeneratorper child. Same seed means same stream; nearby seeds do not guarantee independence.