36.1  Random Variables

In Section 1.6, we built probability by counting. A die has six faces, a label belongs to one of ten classes, and the probability of an event is simply the sum of the probabilities of its outcomes. Most of the numbers a neural network works with are not like that. A pixel intensity, a weight drawn at initialization, or the Gaussian noise that a diffusion model adds to an image can each take any value in an interval, and there are far too many values to list one by one. What, then, is the probability of a single one of them?

Think of a dart thrown at a round board so carelessly that it is equally likely to land anywhere on the board, and suppose it comes to rest at half the radius from the center. Asked how likely that was, we would round the distance (say, to between \(0.45\) and \(0.55\) radii), which happens about one time in ten. Asking for one more digit of precision makes the probability ten times smaller, and another digit makes it ten times smaller again. With infinitely many digits, the probability is zero, and yet the dart clearly landed somewhere.

The way out is to stop asking for the probability of a single point and ask instead how fast probability accumulates near it. Each time we narrow the interval tenfold, its probability drops tenfold, so the ratio of probability to width stays constant. This probability per unit length is the density. With it, every tool of discrete probability carries over to quantities that vary continuously, with sums replaced by integrals.

Some of what follows revisits Section 1.6, now extended to continuous variables and backed by proofs: we already motivated the mean and variance there, so we move straight to their continuous forms and algebra. Alongside them, we introduce the density itself, a general method for drawing samples from the cumulative distribution function, the tail bounds of Markov and Chebyshev, and a bell-shaped density whose tails are so heavy that both bounds fail. If you carry only two results out of this section, make them the relationship between the density and the cumulative distribution function Equation 36.1.6 and Markov’s inequality Equation 36.1.14, from which the rest of this chapter’s tail bounds descend. We follow the dart throughout, focusing on a single number, its distance from the center, and leave its two coordinates and transformations of densities for Section 36.2.

36.1.1 Densities

We develop the idea of a density in three steps: first at a single point, as the limit of ever narrower bins; next over an interval, as an area under a curve; and finally through the function that accumulates that area, which also gives us a practical way to draw random samples.

36.1.1.1 From Bins to a Density

To make “probability per unit length” precise, we first need the probability that the dart lands within a given range of distances. Let \(R\) be the dart’s distance from the center of a board of radius \(1\). The dart lands within distance \(r\) of the center whenever it hits the disk of radius \(r\). Because every part of the board is equally likely, this probability is simply that disk’s share of the board’s area:

\[ P(R\le r)=\frac{\pi r^2}{\pi}=r^2,\qquad 0\le r\le 1. \]

Half the radius holds only a quarter of the probability, because it holds only a quarter of the area. A bin of width \(\epsilon\) centered at \(0.5\) therefore has probability \((0.5+\epsilon/2)^2-(0.5-\epsilon/2)^2=\epsilon\), which produces the numbers from our opening example:

bin width \(\epsilon\) probability probability \(/\ \epsilon\)
\([0.45, 0.55]\) \(0.1\) \(0.1\) \(1\)
\([0.495, 0.505]\) \(0.01\) \(0.01\) \(1\)
\([0.4995, 0.5005]\) \(0.001\) \(0.001\) \(1\)

Each tenfold narrowing divides the probability by ten, leaving the ratio unchanged. That limiting ratio is the quantity we want to name. The probability density of a random variable \(X\) at \(x\) is the probability per unit length near \(x\),

\[ p(x)=\lim_{\epsilon\downarrow0}\frac{P(x\le X<x+\epsilon)}{\epsilon}, \]

wherever this limit exists. Equivalently, for a short interval, the probability is approximately its length times the density,

\[P(x\leq X<x+\epsilon)\approx\epsilon\, p(x), \tag{36.1.1}\]

with an error that shrinks faster than \(\epsilon\). This describes the density one point at a time, which is all we need for now; we give the formal definition in terms of intervals in the next subsection. For our dart at any distance \(r\) in \((0,1)\), the interval \([r,r+\epsilon)\) has probability \((r+\epsilon)^2-r^2=2r\epsilon+\epsilon^2\). Dividing by the width \(\epsilon\) gives \(2r+\epsilon\), and letting \(\epsilon\to 0\) yields

\[p(r)=2r,\qquad 0\le r\le 1. \tag{36.1.2}\]

The density grows linearly from the center to the rim, mirroring the circumference of the circle at radius \(r\): there is simply more board farther out. At \(r=0.5\) the density equals \(1\), matching the ratio in the table above.

Notice that a density is not a probability. At \(r=0.9\), the dart’s density is \(1.8\), and a variable that is equally likely to land anywhere in \([0,0.1]\) has density \(10\) on that interval, since it packs a total probability of \(1\) into a length of \(0.1\). A density can take any non-negative value, though it can exceed \(10\) only on a set of total length less than \(1/10\), or else the probability of that set would exceed \(1\). Think of a density as a rate, much like speed. A car’s speed tells you how fast distance accumulates, not how far the car has traveled. In the same way, a density of \(1.8\) at \(r=0.9\) tells you how fast probability accumulates as \(r\) increases past \(0.9\), not how much probability sits at the point \(0.9\) itself.

Because a single point has zero length, it also carries zero probability. For every \(\epsilon>0\), the point \(x\) lies inside \([x,x+\epsilon)\), so \(P(X=x)\) is at most about \(\epsilon\,p(x)\), which vanishes as \(\epsilon\) shrinks to zero. Thus, for any random variable with a density,

\[P(X=x)=0\qquad\textrm{for every } x. \tag{36.1.3}\]

This resolves our opening puzzle: the dart lands at distance \(0.5\) with probability zero, just as it does at every other exact distance, and yet it must land somewhere. In continuous probability, an event of probability zero is not impossible.

A single point that does carry positive probability is called an atom. A variable with a density has no atoms, whereas a discrete variable such as a die roll consists entirely of atoms. Some variables have both. For example, the output of a ReLU unit fed a standard normal input equals \(0\) with probability \(\tfrac12\) (an atom) and spreads the remaining half of its probability over \((0,\infty)\) with a density (Exercise 2 works out the details).

The table above came from an exact area formula, but a simulation needs no formula at all. To throw darts uniformly at the circular board, a computer can throw them uniformly at the surrounding square \([-1,1]^2\) and keep only those that land inside the circle, which leaves every part of the board equally likely. Below, we count the fraction of darts falling in each of our three bins and divide by the bin width.

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
width 0.1    probability 0.09992  ratio 0.999
width 0.01   probability 0.00994  ratio 0.994
width 0.001  probability 0.00098  ratio 0.983
width 0.1    probability 0.10008  ratio 1.001
width 0.01   probability 0.01009  ratio 1.009
width 0.001  probability 0.00104  ratio 1.041
width 0.1    probability 0.10013  ratio 1.001
width 0.01   probability 0.00995  ratio 0.995
width 0.001  probability 0.00102  ratio 1.018

As expected, each tenfold narrowing reduces the fraction tenfold while keeping the ratio close to \(1=p(0.5)\). What the exact table hid, however, is how noisy a very narrow bin becomes in practice. Roughly \(3.1\) million of the four million darts land on the board, and only about \(3{,}000\) of those fall into the bin of width \(0.001\), so the final ratio fluctuates by a few percent from run to run.

36.1.1.2 Probability as Area

So far we have read the density off from the probabilities of tiny intervals. Now let us reverse the direction: given a density, how do we find the probability of a full interval? Partition the real line into bins \([\epsilon i,\epsilon(i+1))\) of width \(\epsilon\). By Equation 36.1.1, each bin has probability roughly \(\epsilon\,p(\epsilon i)\), and because the bins are disjoint, their probabilities add. Summing widths times heights forms a Riemann sum, which approaches the area under the curve, namely the integral (Section 34.6), as \(\epsilon\) shrinks to zero. Since \(X\) must take some real value, all bins together have probability one:

\[ 1=P(X\in\mathbb{R})\approx\sum_i \epsilon\, p(\epsilon i) \;\xrightarrow[\epsilon\to0]{}\; \int_{-\infty}^{\infty} p(x)\,dx . \]

Summing only the bins between \(a\) and \(b\) suggests that the probability of an interval is simply the area under the density above it. Strictly speaking, this argument is motivation rather than a proof: there are roughly \(1/\epsilon\) bins, and their individual errors, each small compared with \(\epsilon\), sum to a negligible total only if they shrink uniformly across \(x\). To put things on solid footing, we turn this area formula into our formal definition.

Definition. A random variable \(X\) has the density \(p\) when \(p\ge0\) and, for all \(a<b\),

\[P(X\in(a, b]) = \int_{a}^{b} p(x)\,dx. \tag{36.1.4}\]

Letting \(a\to-\infty\) and \(b\to\infty\) confirms that the total area under any density is \(1\). In fact, these two conditions, non-negativity (\(p\ge 0\)) and unit total area, are all a function needs to qualify as a valid density. Figure 36.1.1 illustrates this definition for a density with two peaks. Our dart passes the test as well: for \(0\le a<b\le 1\), the integral \(\int_a^b 2r\,dr=b^2-a^2\) recovers the area-based probability \(P(a<R\le b)\), confirming that \(2r\) is indeed its density. In particular, the probability of landing in the outer half of the radius is \(\int_{0.5}^1 2r\,dr=1-0.25=0.75\): fully three quarters of the board lies more than half the radius from the center.

Figure 36.1.1: A probability density \(p(x)\). The total area under the curve is \(1\); the probability that \(X\) lands in the interval from \(a\) to \(b\) is the area of the shaded slab above it, \(\int_a^b p(x)\,dx\). The density itself is not a probability (it may exceed \(1\)); only its integral over an interval is.

36.1.1.3 The Cumulative Distribution Function

Often it is convenient to work with a function whose values are genuine probabilities, and one that handles discrete and continuous variables alike. The cumulative distribution function (c.d.f.) of \(X\) gives the probability that \(X\) lands at or below \(x\). When \(X\) has a density, this is simply the area under the density to the left of \(x\):

\[ F(x) = P(X \le x) = \int_{-\infty}^{x} p(t)\,dt. \tag{36.1.5}\]

In other words, \(F\) sweeps across the real line from left to right, accumulating probability as it goes. It starts at \(0\) as \(x\to-\infty\) and rises to \(1\) as \(x\to\infty\). It can never decrease, because the non-negative density \(p\) only adds area, and whenever \(X\) has a density, \(F\) is continuous. For our dart, we computed it at the very beginning: \(F(r)=0\) for \(r<0\), \(F(r)=r^2\) for \(0\le r\le 1\), and \(F(r)=1\) for \(r>1\). That function is where we started, and the density \(2r\) came directly from it.

Unlike a density, the c.d.f. is defined for every random variable. A fair coin that reports \(0\) or \(1\) has

\[ F(x) = \begin{cases} 0 & x < 0, \\ \tfrac12 & 0 \le x < 1, \\ 1 & x \ge 1, \end{cases} \]

which is a staircase that jumps upward by the probability of each atom. Because \(F(x)=P(X\le x)\) includes any atom sitting right at \(x\), the function takes the upper value at every jump. More generally, every c.d.f. is right-continuous, meaning \(\lim_{y\downarrow x}F(y)=F(x)\). A mixed variable combines both behaviors: the ReLU output mentioned earlier has a c.d.f. that is \(0\) for \(x<0\), jumps to \(\tfrac12\) at \(x=0\), and then climbs smoothly toward \(1\). A single function therefore unifies discrete, continuous, and mixed random variables; Figure 36.1.2 shows one of each.

Figure 36.1.2: Three cumulative distribution functions. (a) The dart’s distance from the center: \(F(r)=r^2\) rises continuously from \(0\) to \(1\). (b) A fair coin reporting \(0\) or \(1\): a staircase that jumps by \(\tfrac12\) at each atom and takes the upper value there (filled dots). (c) The ReLU of a standard Gaussian: \(F\) is \(0\) for \(x<0\), jumps to \(\tfrac12\) at \(x=0\), and from there follows the Gaussian c.d.f. \(\Phi(x)\).

When a density exists, the c.d.f. and the density carry the same information: integrating \(p\) produces \(F\), and differentiating \(F\) recovers \(p\). This brings back our opening limit of shrinking bins, now established as a theorem.

Proposition (density is the derivative of the c.d.f.). If \(X\) has a density \(p\) that is continuous at \(x\), then \(F\) is differentiable at \(x\) and

\[ F'(x) = p(x). \tag{36.1.6}\]

In particular, the probability per unit length \(P(x\le X<x+\epsilon)/\epsilon\) tends to \(p(x)\) as \(\epsilon\downarrow0\).

Proof. By Equation 36.1.5, \(F\) is the area-so-far function of \(p\). The fundamental theorem of calculus says that the derivative of an area-so-far function is the integrand at every point where the integrand is continuous (Section 34.6). For the second statement, the single point \(x\) has probability at most \(\int_{x-\delta}^{x}p(t)\,dt\) for every \(\delta>0\), and these integrals tend to zero with \(\delta\). Including or excluding an endpoint therefore changes nothing, so \(P(x\le X<x+\epsilon)=F(x+\epsilon)-F(x)\), and the ratio is simply a difference quotient of \(F\). \(\blacksquare\)

For the dart, \(F'(r)=2r\) on \((0,1)\), recovering the density we found from the bins. Figure 36.1.3 places the two functions side by side: the shaded area \(\int_a^b p\) on the left equals the vertical rise \(F(b)-F(a)\) on the right.

Figure 36.1.3: Left: a density \(p\) with the area over the interval from \(a\) to \(b\) shaded. Right: the matching c.d.f. \(F(x)=\int_{-\infty}^x p\), an increasing curve from \(0\) to \(1\); the rise \(F(b)-F(a)\) equals the shaded area on the left. The density is the slope of the c.d.f. \(\left(F'=p\right)\) and the c.d.f. is the accumulated area under the density.

36.1.1.4 Quantiles and Inverse-Transform Sampling

Computers give us ready access to random numbers that are equally likely to fall anywhere between \(0\) and \(1\). To simulate the dart, or any other continuous distribution, we need a way to turn those uniform draws into samples from our target distribution.

Our building block is the simplest density of all. A random variable \(U\) is uniform on \([0,1]\) if its density is \(1\) on \([0,1]\) and \(0\) elsewhere. Every subinterval of \([0,1]\) then has probability equal to its length, and the c.d.f. is simply \(F_U(u)=u\) for \(0\le u\le 1\).

The c.d.f. maps a value \(x\) to a probability level \(u\). Reversing that map, asking for the value below which a given fraction \(u\) of the probability lies, yields the quantile function. Whenever \(F\) is continuous and strictly increasing on the interval \(I\) where \(0<F<1\), it maps \(I\) one-to-one onto \((0,1)\), and its inverse \(F^{-1}:(0,1)\to I\) is the quantile function. Its values at \(u=0.25, 0.5, 0.75\) are the quartiles, with the middle quartile \(F^{-1}(0.5)\) called the median. For our dart, \(F(r)=r^2\) inverts to \(F^{-1}(u)=\sqrt{u}\), giving quartiles of \(0.5\), \(0.707\), and \(0.866\). Notice that the median dart lands at \(0.707\), well past half the radius, because three quarters of the board lies beyond \(0.5\).

Remarkably, the quantile function is also a universal sampler.

Proposition (inverse-transform sampling). Let \(F\) be a continuous c.d.f. that is strictly increasing on the interval \(I\) where \(0<F<1\), and let \(U\) be uniform on \([0,1]\). Then \(X=F^{-1}(U)\) has c.d.f. \(F\).

Proof. With probability one, \(U\) lies in \((0,1)\), so \(X\) is defined and lies in \(I\). For \(x\) in \(I\), the events \(F^{-1}(U)\le x\) and \(U\le F(x)\) coincide, because \(F\) is increasing on \(I\). Since \(U\) is uniform on \([0,1]\), the second event has probability equal to the length of \([0,F(x)]\):

\[ P\bigl(F^{-1}(U)\le x\bigr) = P\bigl(U\le F(x)\bigr) = F(x). \]

For \(x\) to the left of \(I\), \(F(x)=0\) and \(X>x\) always; for \(x\) to the right of \(I\), \(F(x)=1\) and \(X\le x\) always. \(\blacksquare\)

Notice that this hypothesis allows \(F\) to be flat outside an interval, just as the dart’s c.d.f. is (\(F=0\) for \(r<0\) and \(F=1\) for \(r>1\)). Replacing \(F^{-1}\) with the generalized inverse \(F^{-}(u)=\min\{x:F(x)\ge u\}\) removes the hypothesis altogether and samples staircase c.d.f.s as well.

For the dart, inverse-transform sampling gives \(R=\sqrt{U}\). It is tempting to take the shortcut \(R=U\), and we can see immediately why that fails without running a single line of code: \(R=U\) places half the darts inside \(r<0.5\), where only a quarter belong. Figure 36.1.4 shows the geometry of the construction on our two-bump density. Wherever the density is high, the c.d.f. rises steeply, so an evenly spaced set of levels on the vertical axis is compressed into a tight cluster of samples on the horizontal axis.

Figure 36.1.4: Inverse-transform sampling. Uniform levels \(U\) on the vertical axis (left) reflect through the c.d.f. \(F\) down to values \(x=F^{-1}(U)\) on the horizontal axis. Where \(F\) is steep, that is, where the density \(p=F'\) is large, a uniform spread of levels is compressed into a dense cluster of samples, so the histogram of reflected points reproduces \(p\).

We now have two completely different ways to generate the dart’s distance: throwing darts at the square and keeping those on the board, or simply computing \(\sqrt{U}\). The cell below compares the two, alongside 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
P(R < 0.5): darts 0.250, sqrt(U) 0.250, naive U 0.500
mean distance: darts 0.667, sqrt(U) 0.667
P(R < 0.5): darts 0.250, sqrt(U) 0.250, naive U 0.500
mean distance: darts 0.667, sqrt(U) 0.667
P(R < 0.5): darts 0.250, sqrt(U) 0.251, naive U 0.500
mean distance: darts 0.667, sqrt(U) 0.667

The two valid methods agree. Both place a quarter of their distances below \(0.5\), and both have a mean distance close to \(0.667\), a number we will derive in the next subsection. The naive shortcut \(U\) puts half its samples below \(0.5\) because it spreads distances evenly across \([0,1]\), ignoring the fact that the board has far more area near the rim than near the center.

36.1.2 Mean and Variance

A density specifies an entire distribution, yet two summary numbers often tell us most of what we need to know: where the distribution is centered, and how widely it spreads. Section 1.6 introduced both for discrete variables and motivated their use; here we extend them to densities and prove the algebraic rules we rely on.

36.1.2.1 The Mean

The mean averages the values of \(X\), weighting each by its probability. For a variable with a density, slicing the real line into bins of width \(\epsilon\) as before shows that the bin at \(\epsilon i\) contributes its value \(\epsilon i\) times its probability, roughly \(\epsilon\,p(\epsilon i)\), and the resulting sum tends to an integral. The mean, or expectation, of \(X\) is therefore

\[ \mu_X=\mathbb{E}[X]=\sum_i x_i\,p_i\quad\textrm{(discrete)},\qquad \mu_X=\mathbb{E}[X]=\int_{-\infty}^{\infty} x\,p(x)\,dx\quad\textrm{(density)}. \tag{36.1.7}\]

Just as in the discrete case, the mean acts as a balance point: a thin rod with mass density \(p\) along its length balances at \(\mu_X\). For this definition to make sense, we require \(\sum_i|x_i|\,p_i<\infty\) in the discrete case and \(\int|x|\,p(x)\,dx<\infty\) for a density. When that condition fails, the mean does not exist, and we will soon meet a concrete density where this happens. Using the same probability weights lets us average any function \(g(X)\) directly,

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

again provided the sum or integral of \(|g|\) is finite. Notice how convenient this is: we weight the values of \(g\) by the probabilities of \(X\), without first having to work out the distribution of the transformed variable \(g(X)\). This rule is famously called the law of the unconscious statistician, because it is so natural to apply that one easily forgets it is a theorem rather than the definition of \(\mathbb{E}[g(X)]\). Keep in mind that \(\mathbb{E}[g(X)]\) generally differs from \(g(\mathbb{E}[X])\); when \(g\) is convex, Jensen’s inequality (Section 35.3.3.1) tells us which of the two is larger.

For our dart,

\[ \mathbb{E}[R]=\int_0^1 r\cdot 2r\,dr=\tfrac23 . \]

The mean distance is \(0.667\), not \(0.5\), again because the board has more area near the rim than near the center. Notice also that the mean sits slightly below the median \(0.707\): the relatively few darts that land near the center pull the average downward more than they shift the middle value.

The property of expectation we use most often is linearity. We relied on it in Section 1.6; here we prove it.

Proposition (linearity of expectation). For random variables \(X,Y\) whose means exist and constants \(c,d\),

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

Proof. Both identities follow from the linearity of the sum (or integral) that defines the mean. For the first, \(\mathbb{E}[cX+d]=\sum_i(cx_i+d)p_i = c\sum_i x_i p_i + d\sum_i p_i = c\,\mathbb{E}[X]+d\), using \(\sum_i p_i=1\). For the second, let \(p_{ij}\) be the probability that \((X,Y)=(x_i,y_j)\), the joint distribution of the pair as in Section 1.6. Splitting the sum and recognizing the marginals \(\sum_j p_{ij}=P(X=x_i)\) and \(\sum_i p_{ij}=P(Y=y_j)\) gives

\[ \mathbb{E}[X+Y]=\sum_{i,j}(x_i+y_j)\,p_{ij} =\sum_{i,j} x_i\,p_{ij} + \sum_{i,j} y_j\,p_{ij} = \mathbb{E}[X]+\mathbb{E}[Y]. \]

For densities, the exact same computation runs with integrals over a joint density, the continuous counterpart of \(p_{ij}\), which Section 36.2 defines. \(\blacksquare\)

Crucially, the second identity requires no independence at all: the mean of a sum equals the sum of the means no matter how tightly \(X\) and \(Y\) depend on each other. Every time we take the expected loss as an average over a dataset, we are relying on this fact.

36.1.2.2 Variance and Standard Deviation

The mean tells us where a distribution sits, but nothing about how tightly it clusters there. As in Section 1.6, we measure spread by the average squared distance from the mean, called the variance,

\[\sigma_X^2 = \textrm{Var}(X) = \mathbb{E}\bigl[(X-\mu_X)^2\bigr], \tag{36.1.9}\]

which is defined whenever \(\mathbb{E}[X^2]<\infty\). Expanding the square and applying linearity Equation 36.1.8, treating \(\mu_X\) as a constant, yields a form that is usually much easier to compute: the mean of the square minus the square of the mean,

\[ \textrm{Var}(X) = \mathbb{E}\bigl[X^2 - 2\mu_X X + \mu_X^2\bigr] = \mathbb{E}[X^2] - 2\mu_X\,\mathbb{E}[X] + \mu_X^2 = \mathbb{E}[X^2] - \mu_X^2. \tag{36.1.10}\]

For a variable with a density, the mean and variance are therefore given by the two integrals

\[ \mu_X = \int_{-\infty}^\infty x\,p(x)\,dx, \qquad \sigma^2_X = \int_{-\infty}^\infty x^2 p(x)\,dx - \mu_X^2 . \tag{36.1.11}\]

For the dart, \(\mathbb{E}[R^2]=\int_0^1 r^2\cdot 2r\,dr=\tfrac12\), so \(\textrm{Var}(R)=\tfrac12-\tfrac49=\tfrac1{18}\approx 0.056\). For the uniform variable \(U\) on \([0,1]\), \(\mu_U=\int_0^1 u\,du=\tfrac12\) and \(\textrm{Var}(U)=\tfrac13-\tfrac14=\tfrac1{12}\).

Rescaling units or centering data are affine transformations. Under an affine map \(cX+d\), the shift \(d\) drops out of the variance while the scale factor \(c\) comes out squared. Indeed, linearity gives \(\mu_{cX+d}=c\mu_X+d\), so the deviation from the mean is \((cX+d)-\mu_{cX+d}=c(X-\mu_X)\); squaring and taking the expectation gives

\[ \textrm{Var}(cX+d) = c^2\,\textrm{Var}(X). \tag{36.1.12}\]

Two further properties are worth keeping in mind. First, variance is never negative, and it equals zero if and only if \(X\) is constant with probability one, since the expectation of the non-negative quantity \((X-\mu_X)^2\) can vanish only when that quantity is zero with probability one. Second, variances of independent random variables add (Section 1.6); we will prove this in Section 36.2.2.1, along with the covariance term that replaces independence when variables interact.

Because variance squares the deviations, it carries squared units, such as dollars squared for a profit measured in dollars. Taking its square root restores the original units and gives the standard deviation,

\[ \sigma_X = \sqrt{\textrm{Var}(X)}, \tag{36.1.13}\]

which scales linearly under affine maps as \(\sigma_{cX+d}=|c|\,\sigma_X\). For our dart, \(\sigma_R=\sqrt{1/18}\approx 0.236\), measured in units of the board’s radius.

36.1.3 Tails

The standard deviation sets a natural scale for typical fluctuations around the mean. A natural next question is how much probability can sit far out in the tails when all we know is the mean, or the mean and variance. Two classic inequalities answer this for every distribution at once. Both bounds are quite crude, yet surprisingly they are the sharpest possible without extra assumptions, as a simple three-point distribution will demonstrate. We then turn to a bell-shaped density that has neither a mean nor a variance, showing what those two assumptions were protecting us from.

36.1.3.1 Markov’s and Chebyshev’s Inequalities

The first bound uses only the mean and applies to any non-negative random variable. Its proof takes a single line, yet nearly every tail bound in this chapter comes from applying it to a well-chosen function of the variable.

Proposition (Markov’s inequality). If \(X\ge 0\) has a mean and \(t>0\), then

\[ P(X \ge t) \le \frac{\mathbb{E}[X]}{t}. \tag{36.1.14}\]

Proof. Let \(\mathbf{1}_{X\ge t}\) be the indicator variable that equals \(1\) when \(X\ge t\) and \(0\) otherwise. Then \(X \ge t\,\mathbf{1}_{X\ge t}\) for every outcome: when \(X\ge t\) the right-hand side is \(t\le X\), and otherwise it is \(0\le X\). Taking expectations of both sides and using \(\mathbb{E}[\mathbf{1}_{X\ge t}]=P(X\ge t)\) gives \(\mathbb{E}[X]\ge t\,P(X\ge t)\). \(\blacksquare\)

Geometrically, on \([0,\infty)\) the step function that is \(0\) below \(t\) and \(t\) from \(t\) onward stays underneath the line \(y=x\) (Figure 36.1.5), so its average value \(t\,P(X\ge t)\) must stay underneath the average value of \(X\). Setting \(t\) to ten times the mean gives an immediate rule of thumb: at most a tenth of any non-negative population can exceed ten times its average, whether we are looking at incomes, file sizes, or gradient norms.

Figure 36.1.5: Geometry of Markov’s inequality. For \(x\ge0\) the step function \(t\,\mathbf{1}\{x\geq t\}\) (orange) lies under the line \(y=x\) (blue), so its average \(t\,P(X\geq t)\) cannot exceed \(\mathbb{E}[X]\). The shaded gap is what the bound gives away.

Because Markov’s inequality uses only the mean, it is necessarily crude. Applying it to the squared deviation \((X-\mu_X)^2\), whose mean is the variance, bounds both tails at once. This result is due to Bienaymé and Chebyshev (Chebyshev 1867).

Proposition (Chebyshev’s inequality). For any \(X\) with finite, nonzero variance and any \(\alpha>0\),

\[P\bigl(|X - \mu_X| \ge \alpha\sigma_X\bigr) \le \frac{1}{\alpha^2}. \tag{36.1.15}\]

Proof. The variable \(Z=(X-\mu_X)^2\) is non-negative with mean \(\textrm{Var}(X)=\sigma_X^2\), and the event \(|X-\mu_X|\ge\alpha\sigma_X\) is identical to the event \(Z\ge\alpha^2\sigma_X^2\). Since \(\sigma_X>0\), the threshold \(t=\alpha^2\sigma_X^2\) is positive, so Markov’s inequality Equation 36.1.14 gives \(P(|X-\mu_X|\ge\alpha\sigma_X) \le \sigma_X^2/(\alpha^2\sigma_X^2) = 1/\alpha^2\). \(\blacksquare\)

In particular, at most \(1\%\) of any distribution can lie ten or more standard deviations from its mean. Running the same proof with an absolute threshold \(\epsilon>0\) in place of \(\alpha\sigma_X\) gives an equivalent form that requires only finite variance and also covers the degenerate case \(\sigma_X=0\):

\[ P\bigl(|X-\mu_X| \ge \epsilon\bigr) \le \frac{\textrm{Var}(X)}{\epsilon^2}. \]

For our dart, \(\mu_R=0.667\) and \(\sigma_R=0.236\). Two standard deviations below the mean is \(0.195\), while two above lies outside the board altogether, so \(P(|R-\mu_R|\ge 2\sigma_R)=P(R\le 0.195)=0.195^2\approx 0.038\), far smaller than Chebyshev’s bound of \(\tfrac14\).

Given how loose \(\tfrac14\) is for the dart, can a bound valid for every distribution be sharpened? Not without further assumptions, and a distribution supported on just three points proves it. Let \(X\) take the values \(a-2\) and \(a+2\) with probability \(q\) each, and \(a\) with the remaining probability \(1-2q\), where \(0<q\le\tfrac12\). We call this the three-atom example. By symmetry its mean is \(a\), and its variance is \(\textrm{Var}(X)=\mathbb{E}[(X-a)^2]=4q+4q=8q\), so \(\sigma_X=2\sqrt{2q}\). Take \(\alpha=2\). As \(q\) shrinks, the threshold \(2\sigma_X=4\sqrt{2q}\) shrinks with it, while the two outer atoms stay fixed at distance \(2\) from \(a\). Figure 36.1.6 shows the three resulting regimes. When \(q>\tfrac18\), the threshold exceeds \(2\), so neither outer atom falls in the tail and the probability is \(0\). At \(q=\tfrac18\), the threshold lands right at \(2\), giving \(\sigma_X=1\) and placing \(a\pm 2\) two standard deviations from the mean; both outer atoms now count, their total probability is \(2q=\tfrac14\), and Chebyshev’s bound holds with equality. When \(q<\tfrac18\), both outer atoms still lie beyond the threshold, and their combined mass \(2q\) falls below \(\tfrac14\).

Figure 36.1.6: Chebyshev’s bound on the three-atom example: masses \(q\), \(1-2q\), \(q\) drawn as vertical bars at \(a-2\), \(a\), \(a+2\), with the threshold distance \(\alpha\sigma_X=4\sqrt{2q}\) for \(\alpha=2\) marked as a horizontal bracket from \(a-\alpha\sigma_X\) to \(a+\alpha\sigma_X\). The three panels show the regimes \(q>1/8\), \(q=1/8\) (where the bound is attained with equality), and \(q<1/8\). Orange atoms lie at or beyond the threshold and count toward the event \(|X-a|\ge\alpha\sigma_X\).

The same construction settles every \(\alpha\ge 1\). Choosing \(q=1/(2\alpha^2)\), which is at most \(\tfrac12\), gives \(\sigma_X=2\sqrt{2q}=2/\alpha\), so the threshold \(\alpha\sigma_X=2\) lands squarely on the outer atoms and \(P(|X-a|\ge\alpha\sigma_X)=2q=1/\alpha^2\). Equality holds, proving that no constant smaller than \(1/\alpha^2\) can work for all distributions. (For \(\alpha<1\), the bound exceeds \(1\) and says nothing.)

Chebyshev’s inequality therefore captures the worst case over all distributions with a given variance. For the distributions we usually encounter, it is quite loose. A Gaussian with mean \(\mu\) and standard deviation \(\sigma\), the bell curve with density \(e^{-(x-\mu)^2/(2\sigma^2)}/(\sigma\sqrt{2\pi})\) studied in full in Section 36.3.2.3, puts far less probability beyond two and three standard deviations than Chebyshev allows:

distance from the mean Chebyshev’s bound Gaussian
\(2\sigma\) or more \(25\%\) \(4.6\%\)
\(3\sigma\) or more \(11\%\) \(0.27\%\)

The worst-case distribution concentrates all of its tail mass at a single distance, just as our three-atom example does. Typical distributions spread their tails out and thin them rapidly.

36.1.3.2 Heavy Tails

Chebyshev’s inequality requires a finite variance, and the mean itself requires \(\int|x|\,p(x)\,dx<\infty\). Surprisingly, both conditions can fail for a smooth, harmless-looking bell curve. The Cauchy distribution has the density

\[ p(x)=\frac{1}{\pi(1+x^2)} . \]

This is a valid density, since \(\int_{-\infty}^\infty\frac{dx}{1+x^2}=[\arctan x]_{-\infty}^{\infty}=\pi\). Unlike a Gaussian, whose tails plummet like \(e^{-x^2/2}\), the Cauchy tails decay only algebraically, like \(1/(\pi x^2)\). The second moment fails first. Integrating over \([-L,L]\) gives

\[ \int_{-L}^{L} x^2 p(x)\,dx=\frac{2}{\pi}\bigl(L-\arctan L\bigr), \]

which evaluates to \(5.43\), \(62.7\), and \(636\) at \(L=10\), \(100\), and \(1000\), growing without bound because the integrand \(x^2/(\pi(1+x^2))\) approaches the nonzero constant \(1/\pi\). Hence \(\mathbb{E}[X^2]=\infty\), and the Cauchy distribution has no finite variance.

The mean fails in a subtler way. Because the integrand \(x\,p(x)\) is odd, it is tempting to declare the mean to be \(0\) by symmetry, and indeed \(\int_{-L}^{L}x\,p(x)\,dx=0\) for every \(L\). However, the definition of expectation requires absolute convergence, and

\[ \int_{-L}^{L}|x|\,p(x)\,dx=\frac1\pi\log(1+L^2) \]

grows without bound as \(L\to\infty\). Consequently, the Cauchy mean does not exist. Without absolute convergence, the value of the integral depends on how the limits are taken: over the lopsided interval \([-L,2L]\), for example,

\[ \int_{-L}^{2L}x\,p(x)\,dx=\frac{1}{2\pi}\log\frac{1+4L^2}{1+L^2} \;\xrightarrow[L\to\infty]{}\;\frac{\log 2}{\pi}\approx0.221 . \]

With no mean to settle toward, what happens when we average independent Cauchy draws? One might still hope that averaging \(1000\) draws lands closer to \(0\) than a single draw, which falls outside \([-1,1]\) with probability \(P(|X|>1)=1-\tfrac2\pi\arctan 1=\tfrac12\). The cell below plots the running mean of \(10^5\) Cauchy draws alongside that of \(10^5\) standard Gaussian draws, and then counts how many of \(1000\) separate averages (each over \(1000\) Cauchy draws) still lie farther than \(1\) from \(0\).

n = 10**5
idx = np.unique(np.logspace(0, 5, 500).astype(int)) - 1  # log-spaced n
running_mean = lambda x: (np.cumsum(x) / np.arange(1, n + 1))[idx]
d2l.plot(idx + 1, [running_mean(rng.standard_normal(n)),
                   running_mean(rng.standard_cauchy(n))],
         'n', 'running mean', legend=['Gaussian', 'Cauchy'],
         xscale='log', ylim=[-4, 4], figsize=(5, 3))
averages = rng.standard_cauchy((1000, 1000)).mean(axis=1)
print(f'averages of 1000 Cauchy draws with |average| > 1: '
      f'{np.mean(np.abs(averages) > 1):.2f}')
averages of 1000 Cauchy draws with |average| > 1: 0.49

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

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

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

The Gaussian running mean settles smoothly toward \(0\). The Cauchy running mean never settles: it lurches in sudden jumps, each triggered by a single extreme draw, and an order-one jump can strike at any \(n\). Averaging brings no improvement at all. Roughly half of the averages of \(1000\) draws still lie farther than \(1\) from \(0\), matching the fraction for a single draw. In fact, as we state without proof, the average of \(n\) independent standard Cauchy variables has the same distribution as a single standard Cauchy variable.

A distribution is called heavy-tailed when its tails decay more slowly than every exponential \(e^{-\lambda t}\) with \(\lambda>0\). Power-law tails, where \(P(|X|>t)\) decays like \(t^{-\alpha}\), are the canonical example: they force every moment \(\mathbb{E}[|X|^k]\) with \(k\ge\alpha\) to be infinite, with the Cauchy distribution corresponding to \(\alpha=1\). Heavy tails do not automatically imply infinite moments, however; the log-normal distribution, which we derive in Section 36.2.3.1, is heavy-tailed yet has all moments finite. Heavy tails matter in deep learning because sample averages over them converge slowly or fail to converge altogether. Minibatch gradient noise, for example, has been argued to be heavy-tailed (Simsekli et al. 2019), a hypothesis that Exercise 5 lets you test.

Everything in this section dealt with one number at a time, whereas our dart lands in a plane and has two coordinates. Those two coordinates turn out to be uncorrelated yet far from independent, and making sense of that requires densities over the plane, which we take up in Section 36.2.

36.1.4 Summary

A continuous random variable assigns probability zero to every individual value, so we describe its distribution through a density, the probability per unit length. Integrating the density over an interval gives that interval’s probability, the c.d.f. accumulates this area from left to right with \(F'=p\), and inverting the c.d.f. turns uniform noise into samples from the distribution. Markov’s and Chebyshev’s inequalities bound the tails of any distribution using only its mean or variance; Chebyshev’s bound is tight in the worst case yet loose for typical distributions. Heavy-tailed distributions like the Cauchy have neither a mean nor a variance, and averaging their draws does nothing to reduce their spread. Above all, carry Markov’s inequality forward: every tail bound in Section 36.9 descends from it.

36.1.5 Exercises

  1. Power-law tail. Let \(X\) have the density \(p(x) = 1/x^2\) for \(x \ge 1\) and \(p(x) = 0\) otherwise.

    1. Verify that \(p\) is a density, and compute \(P(X > 2)\) and the c.d.f. \(F(x)\) for every real \(x\).
    2. Find the quantile function \(F^{-1}(u)\) for \(u \in (0, 1)\), the median, and the other two quartiles. Write down the inverse-transform sampler \(X = F^{-1}(U)\) of Figure 36.1.4 for this distribution.
    3. Show that \(\mathbb{E}[X] = \infty\). Clipping \(X\) at a level \(c > 1\), as gradient clipping does for a gradient norm, gives \(\min(X, c)\). Compute \(\mathbb{E}[\min(X, c)]\), and describe how it grows with \(c\).
    4. For the Cauchy density \(p_C(x) = 1/\bigl(\pi(1+x^2)\bigr)\), derive the values of \(\int_{-L}^{L} x\,p_C(x)\,dx\) and \(\int_{-L}^{2L} x\,p_C(x)\,dx\) quoted in the text, and their limits as \(L \to \infty\). What do the two limits say about the mean of the Cauchy distribution? Why can no such ambiguity arise for the mean of the non-negative variable \(X\) of part (a)?
  2. Rectified Gaussian. Let \(X \sim \mathcal{N}(0, 1)\) have the standard Gaussian density \(p_X(x) = \tfrac{1}{\sqrt{2\pi}}e^{-x^2/2}\) and c.d.f. \(\Phi(x) = \int_{-\infty}^x p_X(t)\,dt\), and let \(Y = \max(0, X)\). This is the output of a ReLU unit with a standard normal pre-activation, a common model of a unit at initialization.

    1. Express the c.d.f. \(F_Y\) through \(\Phi\) and sketch it. Where does \(Y\) have an atom, and what is its mass? Is \(Y\) discrete, does it have a density, or is it mixed?
    2. Explain why \(Y\) has no density. For a strictly monotone, continuously differentiable transformation \(Y = g(X)\), the change-of-variables rule of Section 36.2.3.1 gives the density \(p_Y(y) = p_X(g^{-1}(y))\,|(g^{-1})'(y)|\). Which of its hypotheses fails for the ReLU?
    3. Clipping to \([-c, c]\) for a threshold \(c > 0\), as the hard-tanh activation does for \(c = 1\), gives \(C = \min(\max(X, -c), c)\). Write down the c.d.f. of \(C\), and find the threshold \(c\) at which the atoms of \(C\) together hold \(10\%\) of the probability. The equation has no closed-form solution; use tabulated values of \(\Phi\), or math.erf with \(\Phi(z) = \tfrac12\bigl(1 + \operatorname{erf}(z/\sqrt{2})\bigr)\).
    4. Show that \(\mathbb{E}[Y^2] = \tfrac12\) and \(\mathbb{E}[Y] = 1/\sqrt{2\pi}\). Hint: write \(X^2 = Y^2 + \min(0, X)^2\) and use the symmetry of \(X\). The He initialization of Section 4.4.2.2 multiplies the weight variance by \(2\); which of these two moments does the factor compensate for?
  3. [code] Logistic distribution and calibration. The logistic distribution has the c.d.f. \(F(x) = \operatorname{sigmoid}(x) = 1/(1 + e^{-x})\).

    1. Find its density with Equation 36.1.6 and its quantile function. What are its quartiles?
    2. Let \(X\) have a continuous, strictly increasing c.d.f. \(F\). Show that \(F(X)\) is uniform on \([0, 1]\). This is the converse of inverse-transform sampling.
    3. A probabilistic regression model predicts for each input \(i\) a logistic distribution for the target \(y_i\), centered at the correct location \(\mu_i\) but with a scale \(s\), that is, the c.d.f. \(\operatorname{sigmoid}\bigl((y - \mu_i)/s\bigr)\). The actual errors \(y_i - \mu_i\) follow the standard logistic distribution. Draw \(10^4\) errors with the quantile function from (a), compute \(u_i = \operatorname{sigmoid}\bigl((y_i - \mu_i)/s\bigr)\) for \(s \in \{0.5, 1, 2\}\), and plot the three histograms of the \(u_i\). Which shape reveals predicted distributions that are too narrow, and which reveals distributions that are too wide? Such histograms are a standard check of the calibration of probabilistic forecasts (Gneiting et al. 2007).
  4. One-sided Chebyshev. ● Chebyshev’s inequality Equation 36.1.15 bounds both tails at once. Cantelli’s inequality bounds one tail: for \(X\) with mean \(\mu\) and variance \(\sigma^2\), and for every \(t > 0\),

    \[P(X - \mu \ge t) \le \frac{\sigma^2}{\sigma^2 + t^2}. \tag{36.1.16}\]

    1. For every \(u \ge 0\), apply Markov’s inequality Equation 36.1.14 to \((X - \mu + u)^2\) to show that \(P(X - \mu \ge t) \le (\sigma^2 + u^2)/(t + u)^2\). Choose \(u\) to prove Cantelli’s inequality.
    2. Write the bound for \(t = \alpha\sigma\), and compare it with Equation 36.1.15 at \(\alpha = 1\) and \(\alpha = 2\).
    3. For given \(\mu\), \(\sigma\) and \(t\), find a distribution on two points with mean \(\mu\) and variance \(\sigma^2\) that attains the bound.
  5. [extended] Averages of heavy tails. ●● Simsekli et al. (2019) argued that the gradient noise of SGD in deep networks is heavy-tailed and better described by an \(\alpha\)-stable distribution, whose variance is infinite for \(\alpha < 2\), than by a Gaussian. This project measures how a Monte Carlo average behaves in that regime and then tests the premise on a small model. The Pareto density \(p(x) = \alpha x^{-\alpha-1}\) on \(x \ge 1\), with \(\alpha > 0\), contains the density of problem 1 as the case \(\alpha = 1\).

    1. Generalize problem 1b and c to this family: show that \(\mathbb{E}[X^k] < \infty\) exactly when \(k < \alpha\), compute the mean \(\mu\) for \(\alpha > 1\), and write down an inverse-transform sampler.

    2. Let \(1 < \alpha < 2\), so that the mean is finite but the variance is not. Show that the largest of \(n\) independent draws exceeds \(t\) with probability close to \(n t^{-\alpha}\) when \(n t^{-\alpha}\) is small, and find the scale \(t_n\) that the largest draw typically reaches. Argue heuristically that the error \(|\bar X_n - \mu|\) of the sample mean is of order \(n^{1/\alpha - 1}\) rather than \(n^{-1/2}\). The generalized central limit theorem that Simsekli et al. invoke makes this argument precise.

    3. For \(\alpha \in \{1.5, 2.5, 3\}\) and \(n \in \{10, 10^2, \ldots, 10^5\}\), estimate the median of \(|\bar X_n - \mu|\) over \(400\) repetitions, and fit the slope of the logarithm of the median error against \(\log n\). Compare the slope at \(\alpha = 1.5\) with the rate \(n^{1/\alpha - 1}\) from (b). Compare the slopes at \(\alpha = 2.5\) and \(\alpha = 3\) with the rate \(n^{-1/2}\) that holds when the variance is finite.

    4. In each repetition, form the interval \(\bar X_n \pm 1.96\,\hat\sigma_n/\sqrt{n}\), where \(\hat\sigma_n\) is the sample standard deviation; for Gaussian averages it covers \(\mu\) with probability about \(95\%\). Record how often it covers \(\mu\). Explain the coverage at \(\alpha = 1.5\) and \(n = 10^5\), given that \(\hat\sigma_n\) is finite in every run. What does this imply for error bars computed from heavy-tailed samples, such as minibatch gradients?

    5. The Hill estimator (Hill 1975) estimates the tail index from the \(k\) largest of \(m\) positive draws \(X_{(1)} \ge X_{(2)} \ge \cdots \ge X_{(m)}\) as

      \[\hat\alpha_k = \Bigl(\frac1k \sum_{i=1}^k \log\frac{X_{(i)}}{X_{(k+1)}}\Bigr)^{-1}. \tag{36.1.17}\]

      Check it on \(10^5\) Pareto draws for \(\alpha \in \{1.5, 3\}\) and \(k \in \{10^2, 10^3, 10^4\}\). Then train the softmax regression of Section 3.3.5. At the trained parameters, collect the coordinates of the difference between the minibatch gradient and the full-batch gradient over \(1000\) minibatches, for batch sizes \(32\) and \(256\). Plot \(\hat\alpha_k\) of their absolute values against \(k\) for both batch sizes. Is the estimate below \(2\)? How much does the conclusion depend on \(k\)?