Random Variables

Dive into Deep Learning · §36.1

Random Variables: Densities, Cumulative Distributions, Moments, and Tail Bounds
probability density p(x) · CDF F'(x) = p(x) · inverse-transform sampling · expectation & variance · Markov & Chebyshev · heavy tails

A Dart Lands at Distance 0.5: What Was the Probability?

The Continuous Paradox

  • Continuous outcomes: A dart landing uniformly on a unit disk has radial distance R \in [0, 1] with disk area share P(R \le r) = r^2.
  • Shrinking bins around r = 0.5: As bin width \epsilon shrinks from 0.1 \to 0.01 \to 0.001, the probability P(R \in \text{bin}) shrinks identically while the ratio P/\epsilon = 1 stays constant.
  • Zero probability \ne impossibility: Every single point has P(R = r) = 0 because a point has zero width, yet probability accumulates at a finite local rate.

Probability Density Is Probability per Unit Length

Local Rate of Accumulation

p(x) = \lim_{\epsilon \downarrow 0} \frac{P(x \le X < x + \epsilon)}{\epsilon}

  • Deriving the dart’s density: Dividing P(r \le R < r+\epsilon) = (r+\epsilon)^2 - r^2 = 2r\epsilon + \epsilon^2 by \epsilon yields p(r) = 2r on [0, 1].
  • Geometric meaning: Density grows linearly with r because ring circumference 2\pi r is larger near the outer rim.
  • Rate, not probability: A density can exceed 1 (e.g., p(0.9) = 1.8, or p(x) = 10 on [0, 0.1]).

Probability as Area Under the Density Curve

Formal Integral Definition

  • Partitioning (a, b] into bins of width \epsilon and summing their probabilities \sum_i \epsilon\,p(\epsilon i) forms a Riemann sum that converges to the definite integral: P(X \in (a, b]) = \int_a^b p(x)\,dx
  • Two conditions define any valid density:
    1. Non-negativity: p(x) \ge 0 for all x \in \mathbb{R}.
    2. Unit total area: \int_{-\infty}^{\infty} p(x)\,dx = 1.
  • Dart outer ring: \int_{0.5}^1 2r\,dr = [r^2]_{0.5}^1 = 0.75—fully three quarters of the board lies beyond half the radius.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Simulating the Dart Board: From Bins to Ratios

Monte Carlo Verification

To throw darts uniformly on the unit disk without formulas, we sample uniformly on the bounding square [-1, 1]^2, keep points inside x^2 + y^2 \le 1, and divide bin frequencies at r = 0.5 by width \epsilon:

rng = np.random.default_rng()
xy = rng.uniform(-1, 1, size=(4 * 10**6, 2))           # darts on the square
on_board = (xy**2).sum(axis=1) <= 1                    # keep those on the board
r_dart = np.linalg.norm(xy[on_board], axis=1)          # distances R
for width in [0.1, 0.01, 0.001]:
    prob = np.mean(np.abs(r_dart - 0.5) <= width / 2)  # fraction in the bin
    print(f'width {width:<5}  probability {prob:.5f}  ratio {prob / width:.3f}')
width 0.1    probability 0.09983  ratio 0.998
width 0.01   probability 0.01002  ratio 1.002
width 0.001  probability 0.00099  ratio 0.990

Finite-sample bin noise: Narrowing \epsilon tenfold reduces the hit count tenfold (only \sim 3{,}100 of 3.14 \times 10^6 darts fall in the \epsilon = 0.001 bin), causing the empirical ratio to fluctuate by a few percent around p(0.5) = 1.

Atoms, Densities, and Mixed Variables in Deep Learning

Discrete vs. Continuous vs. Mixed

  • Atoms vs. densities: A point x with P(X = x) > 0 is an atom (discrete class labels Y \in \{1,\dots,K\}), whereas purely continuous weights W_{ij} \sim \mathcal{N}(0, \sigma^2) have zero atoms.
  • Mixed distributions (Rectified Gaussian / ReLU): Passing X \sim \mathcal{N}(0, 1) through Y = \max(0, X) collapses all negative inputs onto an atom P(Y = 0) = 1/2.
  • Positive half-line: The remaining 50\% of the probability spreads continuously over (0, \infty) with Gaussian density \frac{1}{\sqrt{2\pi}}e^{-y^2/2}.

The Cumulative Distribution Function (CDF)

Unifying Discrete, Continuous, and Mixed Variables

F(x) = P(X \le x) = \int_{-\infty}^x p(t)\,dt

  • Universal rules: Every CDF is monotone non-decreasing, right-continuous (\lim_{y \downarrow x} F(y) = F(x)), and runs from F(-\infty) = 0 to F(+\infty) = 1.
  • Visual signature: Smooth curves for continuous densities (F(r) = r^2), staircases for discrete atoms, and jumps plus smooth climbs for mixed ReLU outputs.

The Density Is the Derivative of the CDF

Fundamental Theorem of Calculus

  • Proposition: If X has a density p that is continuous at x, then F is differentiable at x and F'(x) = p(x)
  • Proof idea: Since F(x) = \int_{-\infty}^x p(t)\,dt is the area-so-far function, the Fundamental Theorem of Calculus gives F'(x) = p(x). Because single points carry zero mass, \frac{P(x \le X < x + \epsilon)}{\epsilon} = \frac{F(x + \epsilon) - F(x)}{\epsilon} \xrightarrow{\epsilon \downarrow 0} F'(x)
  • Area–slope duality: Shaded area \int_a^b p(x)\,dx on the left equals vertical rise F(b) - F(a) on the right.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Quantiles, Quartiles, and Inverse-Transform Sampling

Turning Uniform Noise into Target Samples

  • Quantile function F^{-1}(u): While F maps a value x to a probability level u \in (0, 1), its inverse F^{-1}(u) returns the threshold below which fraction u of the distribution lies.
    • Dart (F(r) = r^2 \implies F^{-1}(u) = \sqrt{u}): quartiles are 0.50, median \sqrt{0.5} \approx 0.707, and 0.866.
  • Proposition (Inverse-Transform Sampling): If U \sim \mathrm{Unif}(0, 1), then X = F^{-1}(U) has CDF F: P\bigl(F^{-1}(U) \le x\bigr) = P\bigl(U \le F(x)\bigr) = F(x)
  • Where p = F' is large, F rises steeply and compresses uniform vertical levels into dense horizontal samples.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Why the Naive Shortcut R = U Fails on the Disk

Sampling Pitfall & Verification

Comparing 10^6 inverse-transform draws R = \sqrt{U} against 2D rejection-sampled darts and the naive shortcut R = U:

u = rng.uniform(size=10**6)
r = np.sqrt(u)                                         # R = F^{-1}(U)
print(f'P(R < 0.5): darts {np.mean(r_dart < 0.5):.3f}, sqrt(U) '
      f'{np.mean(r < 0.5):.3f}, naive U {np.mean(u < 0.5):.3f}')
print(f'mean distance: darts {r_dart.mean():.3f}, sqrt(U) {r.mean():.3f}')
P(R < 0.5): darts 0.250, sqrt(U) 0.250, naive U 0.500
mean distance: darts 0.667, sqrt(U) 0.667

Geometric distortion of R = U: Setting R = U spreads radial distances uniformly on [0, 1], placing 50\% of darts inside r < 0.5 instead of 25\% and underestimating the mean radius (0.500 vs. 0.667).

Expectation: The Center of Mass of a Distribution

First Moment & Law of the Unconscious Statistician

\mu_X = \mathbb{E}[X] = \int_{-\infty}^{\infty} x\,p(x)\,dx, \qquad \mathbb{E}[g(X)] = \int_{-\infty}^{\infty} g(x)\,p(x)\,dx

  • Dart mean vs. median: \mathbb{E}[R] = \int_0^1 r(2r)\,dr = \frac{2}{3} \approx 0.667, sitting slightly below the median \sqrt{0.5} \approx 0.707 because the long left tail pulls the center of mass inward.
  • LOTUS & existence: Any function g(X) averages directly against p(x) without deriving p_{g(X)}, provided \int |g(x)|\,p(x)\,dx < \infty.

Linearity of Expectation Needs No Independence

Algebra of the Mean

Proposition (Linearity of Expectation): For any random variables X, Y with finite means and constants c, d \in \mathbb{R},

\mathbb{E}[cX + d] = c\,\mathbb{E}[X] + d, \qquad \mathbb{E}[X + Y] = \mathbb{E}[X] + \mathbb{E}[Y]

  • Proof of additivity: Weighting x_i + y_j by the joint distribution p_{ij} = P(X=x_i, Y=y_j) and marginalizing each sum separately gives \sum_{i,j} (x_i + y_j)p_{ij} = \sum_i x_i \underbrace{\sum_j p_{ij}}_{p_X(x_i)} + \sum_j y_j \underbrace{\sum_i p_{ij}}_{p_Y(y_j)}
  • Why this matters in deep learning:
    • \mathbb{E}[X + Y] = \mathbb{E}[X] + \mathbb{E}[Y] holds even when X and Y are strongly dependent.
    • The expected average loss over a correlated minibatch or sequence of tokens always equals the average of the individual expected losses.

Variance and Standard Deviation

Second Central Moment

\sigma_X^2 = \mathrm{Var}(X) = \mathbb{E}\bigl[(X - \mu_X)^2\bigr] = \mathbb{E}[X^2] - \mu_X^2

  • Affine transformation rule: Shifting by d leaves spread unchanged, while scaling by c squares the variance (\mathrm{Var}(cX + d) = c^2\,\mathrm{Var}(X) and \sigma_{cX + d} = |c|\,\sigma_X).
  • Worked benchmarks: Dart radius R has \mathbb{E}[R^2] = 1/2 \implies \mathrm{Var}(R) = 1/2 - 4/9 = 1/18 (\sigma_R \approx 0.236); uniform U(0, 1) has \mathrm{Var}(U) = 1/3 - 1/4 = 1/12.

Markov’s Inequality: Tail Bounds from the Mean Alone

The Ancestor of All Concentration Bounds

P(X \ge t) \le \frac{\mathbb{E}[X]}{t} \quad \text{for } X \ge 0,\ t > 0

  • One-line proof: Since X \ge t\,\mathbf{1}_{X \ge t} holds pointwise for every outcome X \ge 0, taking expectations gives \mathbb{E}[X] \ge t\,P(X \ge t).
  • Rule of thumb & lineage: At most 10\% of any non-negative population can exceed 10\times its average; applying Markov to (X-\mu)^2 gives Chebyshev, and to e^{\lambda X} gives Chernoff/Hoeffding.

Chebyshev’s Inequality and Its Three-Atom Sharpness

Two-Sided Variance Bound

  • Proposition (Chebyshev’s Inequality): For any X with finite variance \sigma_X^2 > 0 and any \alpha > 0, P\bigl(|X - \mu_X| \ge \alpha\sigma_X\bigr) \le \frac{1}{\alpha^2}
  • Proof: Apply Markov’s inequality to the non-negative variable Z = (X - \mu_X)^2 (which has mean \sigma_X^2) at threshold t = \alpha^2\sigma_X^2.
  • Why 1/\alpha^2 cannot be improved: A three-atom distribution at a - 2, a, a + 2 with probabilities q, 1-2q, q has \sigma_X = 2\sqrt{2q}. Setting q = \frac{1}{2\alpha^2} places the outer atoms right at \alpha\sigma_X = 2, achieving exact equality P(|X - a| \ge \alpha\sigma_X) = 2q = 1/\alpha^2.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Worst-Case vs. Typical Tails

Chebyshev vs. Smooth Distributions

Chebyshev’s inequality must cover the worst-case distribution that piles all of its tail mass right at the threshold \pm \alpha\sigma. Smooth distributions thin out much faster:

Distance from Mean |X - \mu| Chebyshev Upper Bound (1/\alpha^2) Dart Distance R (p(r)=2r) Gaussian \mathcal{N}(\mu, \sigma^2)
\ge 2\sigma (\alpha = 2) 25.0\% 3.8\% (R \le 0.195) 4.55\%
\ge 3\sigma (\alpha = 3) 11.1\% 0.0\% (outside [0,1]) 0.27\%
\ge 5\sigma (\alpha = 5) 4.0\% 0.0\% 5.7 \times 10^{-5}\%
\ge 10\sigma (\alpha = 10) 1.0\% 0.0\% 1.5 \times 10^{-21}\%

Value of distribution-free bounds: Although 1/\alpha^2 is loose for a single Gaussian, applying it to a sample average \bar{X}_n (whose variance is \sigma^2/n) suffices to prove the Weak Law of Large Numbers for any finite-variance distribution.

Heavy Tails and the Cauchy Distribution

When Moments Fail to Exist

p(x) = \frac{1}{\pi(1 + x^2)}, \qquad x \in \mathbb{R}

  • Infinite second moment (\mathbb{E}[X^2] = \infty): Because the tail decays algebraically like 1/(\pi x^2), \int_{-L}^L x^2 p(x)\,dx = \frac{2}{\pi}(L - \arctan L) \to \infty.
  • Undefined mean (\mathbb{E}[|X|] = \infty): Since \int_{-L}^L |x|\,p(x)\,dx = \frac{1}{\pi}\log(1+L^2) \to \infty, asymmetric limits [-L, 2L] shift \int x\,p(x)\,dx \to \frac{\log 2}{\pi} \approx 0.221.

When Averaging Fails: Gaussian vs. Cauchy Draws

Breakdown of the Law of Large Numbers

  • Catastrophic jumps: As n grows to 10^5, the Gaussian running mean settles smoothly to 0 at rate 1/\sqrt{n}, whereas the Cauchy running mean suffers sudden O(1) jumps whenever a single extreme tail draw arrives.
  • Scale invariance of Cauchy averages: The average of n independent standard Cauchy draws has the exact same distribution as a single Cauchy draw (P(|\bar{X}_{1000}| > 1) = 0.50, identical to P(|X_1| > 1) = 0.50).
  • Deep learning impact: When minibatch SGD gradient noise exhibits heavy power-law tails (P(|X| > t) \sim t^{-\alpha} with \alpha < 2), naive averaging fails and gradient clipping is required.

averages of 1000 Cauchy draws with |average| > 1: 0.49

Concept Check: Densities, Quantiles & Tail Bounds

Check Your Understanding

Test your intuition on three foundational calculations from this section:

  1. Power-law sampler and clipping: Let p(x) = 1/x^2 for x \ge 1 (0 otherwise). What is its CDF F(x), its inverse-transform sampler X = F^{-1}(U), and its expected value \mathbb{E}[X]?
  2. Affine variance and Chebyshev: If \mathrm{Var}(X) = 2, what is \mathrm{Var}(3X - 7)? For any random variable with \sigma_X > 0, what is the maximum possible probability that |X - \mu_X| \ge 4\sigma_X?
  3. He initialization and the Rectified Gaussian: For a ReLU output Y = \max(0, X) with X \sim \mathcal{N}(0, 1), use symmetry (X^2 = Y^2 + \min(0, X)^2) to find \mathbb{E}[Y^2]. Why does He initialization multiply weight variance by 2?

Answers:

  1. F(x) = \int_1^x t^{-2}\,dt = 1 - 1/x for x \ge 1. Solving 1 - 1/x = U gives sampler X = 1/(1 - U) (median = 2). Its mean \int_1^\infty x(1/x^2)\,dx = [\log x]_1^\infty = \boldsymbol{\infty} (clipping at c gives finite mean 1 + \log c).
  2. \mathrm{Var}(3X - 7) = 3^2 \mathrm{Var}(X) = \mathbf{18} (shift drops out, scale squares). By Chebyshev, P(|X - \mu_X| \ge 4\sigma_X) \le 1/4^2 = \mathbf{1/16 = 6.25\%}.
  3. Since \mathbb{E}[X^2] = 1 and Y^2 has the same distribution as \min(0, X)^2 with Y \cdot \min(0, X) = 0, we get 2\mathbb{E}[Y^2] = 1 \implies \boldsymbol{\mathbb{E}[Y^2] = 1/2}. He initialization multiplies weight variance by 2 to restore unit activation second moment across layers.

Summary: Random Variables, Moments, and Tails

Key Takeaways

Concept Mathematical Definition / Rule Dart Benchmark (R on Unit Disk) Deep Learning Role
Probability Density p(x) P(a < X \le b) = \int_a^b p(x)\,dx, p \ge 0, \int p = 1 p(r) = 2r on [0, 1] (P(R = r) = 0) Continuous representations, weights & noise
CDF & Derivative F(x) = P(X \le x) = \int_{-\infty}^x p(t)\,dt, F'(x) = p(x) F(r) = r^2, P(R > 0.5) = 1 - 0.5^2 = 0.75 Unifies continuous, discrete & mixed (ReLU)
Inverse-Transform Sampler X = F^{-1}(U) for U \sim \mathrm{Unif}(0, 1) has CDF F R = \sqrt{U} (median F^{-1}(0.5) \approx 0.707) Sampling arbitrary 1D distributions & calibration
Expectation & Linearity \mathbb{E}[g(X)] = \int g(x)p(x)\,dx; \mathbb{E}[X+Y] = \mathbb{E}[X]+\mathbb{E}[Y] \mathbb{E}[R] = \int_0^1 2r^2\,dr = 2/3 \approx 0.667 Unbiased empirical risk & SGD gradients
Variance & Affine Scaling \mathrm{Var}(X) = \mathbb{E}[X^2] - \mu^2; \mathrm{Var}(cX+d) = c^2\mathrm{Var}(X) \mathbb{E}[R^2] = 1/2 \implies \mathrm{Var}(R) = 1/18 Activation scale control & layer normalization
Markov & Chebyshev Bounds P(X \ge t) \le \mathbb{E}[X]/t; P(\|X-\mu\| \ge \alpha\sigma) \le 1/\alpha^2 Exact 2\sigma tail 3.8\% \le 25\% bound Distribution-free tail & convergence guarantees
Heavy Tails (Cauchy) Algebraic decay p(x) \sim x^{-(\alpha+1)} (\mathbb{E}[\|X\|^k] = \infty, k \ge \alpha) Cauchy (\alpha=1): no mean/var, \bar{X}_n \stackrel{d}{=} X_1 Gradient clipping under heavy-tailed SGD noise