24.2 Joint Distributions and Transformations

In Section 24.1, we reduced our dart on a board of radius 11 to a single number: its distance RR from the center, which has density 2r2r. A dart actually lands at a point, however, with both a horizontal coordinate XX and a vertical coordinate YY. Most quantities we model in machine learning arrive in groups like this. An image consists of thousands of pixels whose values depend on one another, and every supervised learning problem pairs an input with a target. Knowing the density of each variable on its own is not enough, because separate densities say nothing about how the variables move together.

Two questions guide us in this section. The first is what one variable tells us about another. If the dart lands near the top of the board, at Y=0.9Y=0.9, then XX must lie within 0.440.44 of the center line, so observing YY certainly tells us something about XX. Yet, surprisingly, we will find that our best single guess for XX is still 00 no matter what YY is, and that the covariance between the two coordinates is zero. Dependence, predictability, and correlation are three distinct ideas, and we need the joint density of the pair to tell them apart. The second question is what happens to a density when we transform a random variable, as when a neural network layer acts on its input or a sampler reshapes uniform noise. We already saw that the dart's distance can be drawn as R=UR=\sqrt U from a uniform variable UU, and taking the square root turns a flat density into the linear density 2r2r. Clearly, a transformation does more to a density than simply relabel its axis.

Three results from this section will carry most of the weight later in the book: the law of total variance (24.2.5), the conditional mean as the best squared-error predictor (24.2.6), and the change-of-variables formula (24.2.14). The covariance matrix and the geometric remark that a correlation is a cosine can safely be skipped on a first reading.

rng = np.random.default_rng()

24.2.1 Joint and Conditional Densities#

Everything we might want to ask about a pair of continuous random variables is captured by a single function of two arguments. Let us define that function, and then see how to extract three essential quantities from it: the distribution of one coordinate on its own, the distribution of one coordinate once the other is observed, and the average of one given the other, which is what a regression model estimates.

24.2.1.1 Joint and Marginal Densities#

Just as a one-dimensional density measures probability per unit length over short intervals, its two-dimensional counterpart measures probability per unit area over small squares. The joint density pX,Yp_{X,Y} of a pair (X,Y)(X,Y) gives the probability of landing in a small square of side ϵ\epsilon at (x,y)(x,y) as roughly its area times the density,

P(X∈[x,x+ϵ], Y∈[y,y+ϵ])≈ϵ2 pX,Y(x,y).P\bigl(X\in[x,x+\epsilon],\ Y\in[y,y+\epsilon]\bigr)\approx\epsilon^2\,p_{X,Y}(x,y).

As in one dimension, tiling a region D\mathcal D of the plane with such squares leads to the property we take as the formal definition: pX,Y≥0p_{X,Y}\ge0, and P((X,Y)∈D)=∬DpX,Y(x,y) dx dyP((X,Y)\in\mathcal{D})=\iint_{\mathcal{D}} p_{X,Y}(x,y)\,dx\,dy, so that the total volume under the joint density over the whole plane equals 11. For nn variables, the same definition holds with nn-dimensional boxes and nn-fold integrals.

For our dart, every part of the unit disk is equally likely and the board has area π\pi, so the joint density is pX,Y(x,y)=1/πp_{X,Y}(x,y)=1/\pi inside the disk and 00 outside. Notice that even though this density is flat on the disk, it cannot be written as a function of xx times a function of yy: the circular edge of the board ties the two coordinates together.

Often we know a joint density, yet we only care about the distribution of one coordinate on its own, called its marginal distribution. A thin vertical strip X∈[x,x+ϵ]X\in[x,x+\epsilon] has probability about ϵ pX(x)\epsilon\,p_X(x). Slicing that strip into small squares along yy and adding their probabilities gives

ϵ pX(x)≈∑iP(X∈[x,x+ϵ], Y∈[ϵi,ϵ(i+1)])≈∑iϵ2 pX,Y(x,ϵi).\epsilon\,p_X(x) \approx \sum_i P\bigl(X\in[x,x{+}\epsilon],\ Y\in[\epsilon i,\epsilon(i{+}1)]\bigr) \approx \sum_i \epsilon^{2}\,p_{X,Y}(x,\epsilon i).

Canceling one factor of ϵ\epsilon and recognizing the remaining sum as a Riemann sum in yy, we obtain

pX(x)=∫−∞∞pX,Y(x,y) dy.(24.2.1)p_X(x) = \int_{-\infty}^\infty p_{X, Y}(x, y)\,dy. \tag{24.2.1}

In words, the marginal density at xx is the joint density integrated up the vertical strip at xx, as illustrated in Figure 24.2.1: we simply integrate out the variable we do not need. For the dart, the vertical strip at xx crosses the board from −1−x2-\sqrt{1-x^2} to 1−x2\sqrt{1-x^2}, giving

pX(x)=∫−1−x21−x21π dy=2π1−x2,−1≤x≤1,p_X(x)=\int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}}\frac1\pi\,dy=\frac2\pi\sqrt{1-x^2}, \qquad -1\le x\le 1,

which traces out a semicircle. As a quick check, ∫−111−x2 dx\int_{-1}^1\sqrt{1-x^2}\,dx is the area of half the unit disk, π/2\pi/2, so pXp_X indeed integrates to 11. Even though the joint density is flat, the marginal density is curved: a vertical strip through the middle of the board is longer than one near the rim.

Figure 24.2.1:

A continuous joint density pX,Y(x,y)p_{X,Y}(x,y) shown by its contours, with one vertical strip at xx highlighted. Integrating the joint density up that strip, over all yy, gives the height of the marginal density pX(x)p_X(x) plotted along the x\mathit{x}-axis below. Sweeping the strip across xx traces out the whole marginal.

24.2.1.2 Conditional Densities and Independence#

Once we observe that Y=yY=y, how should our density for XX change? For discrete variables, the answer is simply P(X=x∣Y=y)=P(X=x,Y=y)/P(Y=y)P(X=x\mid Y=y)=P(X=x,Y=y)/P(Y=y). With continuous densities, however, that formula divides zero by zero because P(Y=y)=0P(Y=y)=0. The way out is the same limiting argument that defined the density in the first place: we condition on a thin horizontal strip Y∈[y,y+ϵ]Y\in[y,y+\epsilon], which has positive probability, and then let the strip shrink. Applying our square approximation to the numerator and the one-variable rule to the denominator gives

P(X∈[x,x+ϵ]∣Y∈[y,y+ϵ])≈ϵ2 pX,Y(x,y)ϵ pY(y)=ϵ pX,Y(x,y)pY(y).P\bigl(X\in[x,x+\epsilon]\bigm| Y\in[y,y+\epsilon]\bigr) \approx\frac{\epsilon^2\,p_{X,Y}(x,y)}{\epsilon\,p_Y(y)} =\epsilon\,\frac{p_{X,Y}(x,y)}{p_Y(y)}.

Inside the strip, the probability of a short xx-interval is its length ϵ\epsilon times pX,Y(x,y)/pY(y)p_{X,Y}(x,y)/p_Y(y). That ratio is the probability per unit length of XX given Y=yY=y, so we define the conditional density as

pX∣Y(x∣y)=pX,Y(x,y)pY(y),pY(y)>0.(24.2.2)p_{X\mid Y}(x\mid y) = \frac{p_{X,Y}(x,y)}{p_Y(y)}, \qquad p_Y(y) > 0. \tag{24.2.2}

For every fixed yy with pY(y)>0p_Y(y)>0, this is a valid density in xx: it is non-negative, and by the marginal rule (24.2.1) it integrates to pY(y)/pY(y)=1p_Y(y)/p_Y(y)=1. Geometrically, we slice the joint density along the horizontal line Y=yY=y and rescale that cross-section to unit area. For the dart, the horizontal line Y=yY=y cuts across the board on the chord [−1−y2,1−y2][-\sqrt{1-y^2},\sqrt{1-y^2}], so

pX∣Y(x∣y)=1/π(2/π)1−y2=121−y2for ∣x∣≤1−y2.p_{X\mid Y}(x\mid y)=\frac{1/\pi}{(2/\pi)\sqrt{1-y^2}}=\frac{1}{2\sqrt{1-y^2}} \qquad\textrm{for } |x|\le\sqrt{1-y^2}.

Given Y=yY=y, the horizontal position XX is uniform along the chord at height yy. Because that chord shrinks as ∣y∣|y| grows, observing YY changes the distribution of XX.

Rearranging (24.2.2) gives the chain rule pX,Y(x,y)=pX∣Y(x∣y) pY(y)p_{X,Y}(x,y)=p_{X\mid Y}(x\mid y)\,p_Y(y). Writing the joint density both ways, pX∣Y pY=pY∣X pXp_{X\mid Y}\,p_Y=p_{Y\mid X}\,p_X, and solving for pX∣Yp_{X\mid Y} yields Bayes' rule for densities,

pX∣Y(x∣y)=pY∣X(y∣x) pX(x)pY(y).(24.2.3)p_{X\mid Y}(x\mid y) = \frac{p_{Y\mid X}(y\mid x)\,p_X(x)}{p_Y(y)}. \tag{24.2.3}

Just as Bayes' theorem did for discrete variables in Section 1.6, this identity turns a model of how YY is generated from XX into a distribution over XX after seeing YY.

In the special case where observing YY tells us nothing new about XX, so that pX∣Y(x∣y)=pX(x)p_{X\mid Y}(x\mid y)=p_X(x) whenever pY(y)>0p_Y(y)>0, we call the two variables independent and write X⊥YX\perp Y. By the chain rule, independence is equivalent to saying that the joint density factorizes, pX,Y(x,y)=pX(x) pY(y)p_{X,Y}(x,y)=p_X(x)\,p_Y(y) (up to sets of probability zero): multiply by pY(y)p_Y(y) to go one way and divide by it to go the other.

Intuitively, independence means that the conditional density of XX is the same function of xx, with the same location and the same shape, at every height yy. Consider the joint density pX,Y(x,y)=4xyp_{X,Y}(x,y)=4xy on the unit square [0,1]2[0,1]^2. Its marginal is pY(y)=∫014xy dx=2yp_Y(y)=\int_0^1 4xy\,dx=2y, which gives pX∣Y(x∣y)=4xy/(2y)=2xp_{X\mid Y}(x\mid y)=4xy/(2y)=2x regardless of yy, so X⊥YX\perp Y. The dart is the opposite case: its conditional density is uniform at every yy, yet it lives on a chord whose length depends on yy.

As Figure 24.2.2 shows, having the same shape is not enough for independence. For a correlated pair, the conditional densities at three heights share the same shape but have shifted centers, so the pair is dependent; only when the joint density factorizes do all three slices coincide.

Figure 24.2.2:

Conditioning as slicing. Left: a joint density with three horizontal slices at y0=−1,0,1y_0=-1,0,1. Right: each slice renormalized to unit area is the conditional density p(x∣y0)p(x\mid y_0). Top: a correlated pair; the three conditionals have the same shape but shifted centers, so the conditional depends on y0y_0 and the pair is dependent. Bottom: a pair whose joint factorizes; the three conditionals coincide, which is independence.

Independence also gives a clean formula for the density of a sum. When X⊥YX\perp Y, the pair (X,X+Y)(X,X+Y) has joint density pX(x) pY(s−x)p_X(x)\,p_Y(s-x) at (x,s)(x,s), and integrating out xx via (24.2.1) leaves the convolution pX+Y(s)=∫pX(x) pY(s−x) dxp_{X+Y}(s)=\int p_X(x)\,p_Y(s-x)\,dx.

24.2.1.3 Conditional Expectation#

A regression model predicts a target from an input. To stay consistent with the previous subsection, we keep XX as the target and YY as the observed input (whereas the main text writes the pair the other way around). Training with squared loss searches for a function hh that makes E[(X−h(Y))2]\mathbb{E}[(X-h(Y))^2] as small as possible. Which function is best? Within any thin strip Y≈yY\approx y, the model must predict a single number for an entire spread of possible targets. For any random variable XX, the constant cc closest to it in mean squared distance is its mean μX\mu_X, since expanding the square around μX\mu_X gives E[(X−c)2]=Var(X)+(μX−c)2\mathbb{E}[(X-c)^2]=\textrm{Var}(X)+(\mu_X-c)^2. That suggests predicting the average of XX inside each strip. Accordingly, the conditional expectation of XX given Y=yY=y is the mean of the conditional density,

E[X∣Y=y]=∫x pX∣Y(x∣y) dx.(24.2.4)\mathbb{E}[X\mid Y{=}y] = \int x\,p_{X\mid Y}(x\mid y)\,dx. \tag{24.2.4}

It is simply the average of XX among all outcomes with Y=yY=y. As yy varies, E[X∣Y=y]\mathbb{E}[X\mid Y{=}y] traces out a function of yy; evaluated at the random variable YY, it becomes a random variable E[X∣Y]\mathbb{E}[X\mid Y] that depends on YY alone. The same strip average defines E[g(X,Y)∣Y=y]=∫g(x,y) pX∣Y(x∣y) dx\mathbb{E}[g(X,Y)\mid Y{=}y]=\int g(x,y)\,p_{X\mid Y}(x\mid y)\,dx for any function gg. Because a factor h(Y)h(Y) is constant within each strip, it pulls straight out of the conditional expectation:

E[h(Y) g(X,Y)∣Y]=h(Y) E[g(X,Y)∣Y].\mathbb{E}[h(Y)\,g(X,Y)\mid Y]=h(Y)\,\mathbb{E}[g(X,Y)\mid Y].

Similarly, the spread of XX within a strip is the conditional variance Var(X∣Y)=E[X2∣Y]−(E[X∣Y])2\textrm{Var}(X\mid Y)=\mathbb{E}[X^2\mid Y]-(\mathbb{E}[X\mid Y])^2, which is just the computational variance identity of Section 24.1 applied inside each strip.

Intuitively, averaging the strip averages should recover the overall average, and the overall variance should split into the spread within strips plus the spread between them. Both statements hold, and the second turns out to be especially useful.

Proposition (laws of total expectation and variance). Let X,YX,Y have a joint density, and let XX have finite variance (for discrete pairs, the same identities hold with integrals replaced by sums). Then

E[X]=E[E[X∣Y]],Var(X)=E[Var(X∣Y)]+Var(E[X∣Y]).(24.2.5)\begin{aligned} \mathbb{E}[X] &= \mathbb{E}\bigl[\mathbb{E}[X\mid Y]\bigr], \\ \textrm{Var}(X) &= \mathbb{E}\bigl[\textrm{Var}(X\mid Y)\bigr] + \textrm{Var}\bigl(\mathbb{E}[X\mid Y]\bigr). \end{aligned} \tag{24.2.5}

Proof. For the first identity, known as the tower property, write out the inner expectation and apply the chain rule pX∣Y(x∣y) pY(y)=pX,Y(x,y)p_{X\mid Y}(x\mid y)\,p_Y(y)=p_{X,Y}(x,y) to reassemble the strips into the joint density:

E[E[X∣Y]]=∫ ⁣(∫x pX∣Y(x∣y) dx)pY(y) dy=∬x pX,Y(x,y) dx dy=E[X].\mathbb{E}\bigl[\mathbb{E}[X\mid Y]\bigr] = \int\!\Bigl(\int x\,p_{X\mid Y}(x\mid y)\,dx\Bigr)p_Y(y)\,dy = \iint x\,p_{X,Y}(x,y)\,dx\,dy = \mathbb{E}[X].

Values of yy with pY(y)=0p_Y(y)=0, where the conditional density is undefined, contribute to neither side because YY lands there with probability zero. The same computation with g(x,y)g(x,y) in place of xx gives E[E[g(X,Y)∣Y]]=E[g(X,Y)]\mathbb{E}\bigl[\mathbb{E}[g(X,Y)\mid Y]\bigr]=\mathbb{E}[g(X,Y)]. For the second identity, expand both terms on the right. Applying the tower property to X2X^2 gives

E[Var(X∣Y)]=E[E[X2∣Y]]−E[(E[X∣Y])2]=E[X2]−E[(E[X∣Y])2].\begin{aligned} \mathbb{E}\bigl[\textrm{Var}(X\mid Y)\bigr] &=\mathbb{E}\bigl[\mathbb{E}[X^2\mid Y]\bigr]-\mathbb{E}\bigl[(\mathbb{E}[X\mid Y])^2\bigr] \\ &=\mathbb{E}[X^2]-\mathbb{E}\bigl[(\mathbb{E}[X\mid Y])^2\bigr]. \end{aligned}

Applying Var(Z)=E[Z2]−(E[Z])2\textrm{Var}(Z)=\mathbb{E}[Z^2]-(\mathbb{E}[Z])^2 (Section 24.1) to the random variable E[X∣Y]\mathbb{E}[X\mid Y], whose mean is E[X]\mathbb{E}[X] by the tower property, gives

Var(E[X∣Y])=E[(E[X∣Y])2]−E[X]2.\textrm{Var}\bigl(\mathbb{E}[X\mid Y]\bigr) =\mathbb{E}\bigl[(\mathbb{E}[X\mid Y])^2\bigr]-\mathbb{E}[X]^2 .

Adding the two lines, the middle term E[(E[X∣Y])2]\mathbb{E}[(\mathbb{E}[X\mid Y])^2] cancels and leaves E[X2]−E[X]2=Var(X)\mathbb{E}[X^2]-\mathbb{E}[X]^2=\textrm{Var}(X). ■\blacksquare

The second identity is often called Eve's law, after the pattern E, V, V, E on its right-hand side. It splits the total variance of XX into two pieces: the average variance within each strip, which knowing YY can never remove, and the variance of the strip averages themselves, which is the portion that YY explains. Statisticians use this decomposition to attribute variation in data to groups under the name analysis of variance. As we now show, the same decomposition also settles our regression question.

Proposition (the conditional mean is the best squared-error predictor). Let XX have finite variance, and let hh be any function with E[h(Y)2]<∞\mathbb{E}[h(Y)^2]\lt \infty. Then

E[(X−h(Y))2]=E[Var(X∣Y)]+E[(E[X∣Y]−h(Y))2].(24.2.6)\mathbb{E}\bigl[(X-h(Y))^2\bigr] =\mathbb{E}\bigl[\textrm{Var}(X\mid Y)\bigr] +\mathbb{E}\bigl[(\mathbb{E}[X\mid Y]-h(Y))^2\bigr]. \tag{24.2.6}

Proof. Write m(Y)=E[X∣Y]m(Y)=\mathbb{E}[X\mid Y] and split the prediction error into two parts, X−h(Y)=(X−m(Y))+(m(Y)−h(Y))X-h(Y)=(X-m(Y))+(m(Y)-h(Y)). Squaring produces two squared terms and a cross term, and only the cross term requires care. The expectation of the first square is E[Var(X∣Y)]\mathbb{E}[\textrm{Var}(X\mid Y)] by the tower property. The cross term 2(X−m(Y))(m(Y)−h(Y))2(X-m(Y))(m(Y)-h(Y)) has conditional mean zero: the factor m(Y)−h(Y)m(Y)-h(Y) depends on YY alone and pulls out of the strip average, leaving E[X−m(Y)∣Y]=m(Y)−m(Y)=0\mathbb{E}[X-m(Y)\mid Y]=m(Y)-m(Y)=0. By the tower property, its overall mean is zero as well. ■\blacksquare

Look at the two terms on the right. The first does not depend on hh at all, while the second is non-negative and vanishes when h(Y)=E[X∣Y]h(Y)=\mathbb{E}[X\mid Y]. Thus the conditional mean is the optimal predictor under squared error, and no predictor can achieve a lower expected squared error than the average within-strip variance. A network trained with squared loss is therefore estimating E[target∣input]\mathbb{E}[\textrm{target}\mid\textrm{input}], which is how Section 2.1 interprets its model (written there as E[y∣x]\mathbb{E}[y\mid\mathbf x]).

Two examples make this decomposition concrete. First, return to the dart and try to predict XX from YY. Given Y=yY=y, the horizontal coordinate XX is uniform on a chord symmetric about 00, so E[X∣Y=y]=0\mathbb{E}[X\mid Y=y]=0. A uniform variable on an interval of half-width ww has variance w2/3w^2/3, which gives Var(X∣Y=y)=(1−y2)/3\textrm{Var}(X\mid Y=y)=(1-y^2)/3. By symmetry E[X2]=E[Y2]=12E[R2]=14\mathbb{E}[X^2]=\mathbb{E}[Y^2]=\tfrac12\mathbb{E}[R^2]=\tfrac14, so Eve's law yields

Var(X)=E[1−Y23]+Var(0)=1−1/43+0=14.\textrm{Var}(X)=\mathbb{E}\Bigl[\frac{1-Y^2}{3}\Bigr]+\textrm{Var}(0) =\frac{1-1/4}{3}+0=\frac14 .

All of the variance stays in the unexplained term. Knowing YY narrows the range of XX without ever shifting its center, so the best squared-error predictor of XX from YY is the constant 00, even though XX and YY are dependent.

For a second example, draw a binary label ZZ that equals 11 with probability 0.20.2 and 00 with probability 0.80.8. Given Z=1Z=1, draw XX from the normal distribution N(3,1)\mathcal N(3,1) with mean 33 and variance 11; given Z=0Z=0, draw XX from N(−1,1)\mathcal N(-1,1). This mixture produces the two-bump density of Figure 24.1.1. Its overall mean is 0.2⋅3+0.8⋅(−1)=−0.20.2\cdot3+0.8\cdot(-1)=-0.2. Within each component the variance is 11, so E[Var(X∣Z)]=1\mathbb{E}[\textrm{Var}(X\mid Z)]=1. Between the components, E[X∣Z]\mathbb{E}[X\mid Z] takes the values 33 and −1-1, whose variance is 0.2⋅0.8⋅(3−(−1))2=2.560.2\cdot0.8\cdot(3-(-1))^2=2.56. The total variance is therefore 3.563.56, and the label ZZ explains 2.56/3.56=72%2.56/3.56=72\% of it. In a sample of one million draws, the empirical within- and between-component terms will land near 11 and 2.562.56. Before running the code, ask yourself: will their sum match the sample variance only roughly, or exactly?

n = 10**6
z = rng.uniform(size=n) < 0.2                          # component label Z
x = np.where(z, rng.normal(3, 1, n), rng.normal(-1, 1, n))
w = np.array([np.mean(~z), np.mean(z)])                # P(Z=0), P(Z=1)
cond_mean = np.array([x[~z].mean(), x[z].mean()])      # E[X | Z]
within = w @ np.array([x[~z].var(), x[z].var()])       # E[Var(X | Z)]
between = w @ (cond_mean - x.mean())**2                # Var(E[X | Z])
print(f'Var(X) {x.var():.3f} = within {within:.3f} + between {between:.3f}')
Var(X) 3.562 = within 1.000 + between 2.562

Exactly. Each piece lands close to its theoretical value (11 and 2.562.56), with sampling noise in the third decimal place, yet their sum equals the sample variance in every run up to rounding in the last printed digit. Eve's law is an exact identity for the sample itself, with the empirical group fractions and group variances playing the roles of probabilities and conditional variances.

24.2.2 Covariance and Correlation#

The conditional mean describes how the average of XX moves with YY, which makes it an entire function. Often we prefer a single summary number: do XX and YY tend to be large together, or does one tend to be large when the other is small? The covariance is that number. It has two limitations that the rest of this section addresses or exposes: it carries the units of both variables, which the correlation removes, and it detects only straight-line trends, which no rescaling can fix.

24.2.2.1 Covariance#

Section 1.6 defined the covariance as the expected product of the two deviations from their means. For discrete X,YX,Y taking (xi,yj)(x_i,y_j) with probability pijp_{ij}, it is

σXY=Cov(X,Y)=∑i,j(xi−μX)(yj−μY) pij=E[XY]−E[X] E[Y],(24.2.7)\sigma_{XY} = \textrm{Cov}(X, Y) = \sum_{i, j} (x_i - \mu_X)(y_j-\mu_Y)\,p_{ij} = \mathbb{E}[XY] - \mathbb{E}[X]\,\mathbb{E}[Y], \tag{24.2.7}

where the second form follows by expanding the product, just as in the computational form of the variance. In particular, Cov(X,X)=Var(X)\textrm{Cov}(X,X)=\textrm{Var}(X). Throughout this section we assume both variances are finite; since ∣xy∣≤(x2+y2)/2|xy|\le(x^2+y^2)/2, the expectation of XYXY is then guaranteed to exist.

As a concrete example, let X∈{1,3}X\in\{1,3\} and Y∈{−1,3}Y\in\{-1,3\} with joint probabilities

P(X=1,Y=−1)=θ2,P(X=1,Y=3)=1−θ2,P(X=3,Y=−1)=1−θ2,P(X=3,Y=3)=θ2,\begin{aligned} P(X{=}1, Y{=}{-}1) &= \tfrac{\theta}{2}, &\quad P(X{=}1, Y{=}3) &= \tfrac{1-\theta}{2}, \\ P(X{=}3, Y{=}{-}1) &= \tfrac{1-\theta}{2}, &\quad P(X{=}3, Y{=}3) &= \tfrac{\theta}{2}, \end{aligned}

for a parameter θ∈[0,1]\theta\in[0,1]. We will refer to this as the four-cell example. Each variable takes its two values with probability 12\tfrac12, so μX=2\mu_X=2 and μY=1\mu_Y=1. The expectation of the product is

E[XY]=12(−θ+3(1−θ)−3(1−θ)+9θ)=4θ,\mathbb{E}[XY]=\tfrac12\bigl(-\theta+3(1-\theta)-3(1-\theta)+9\theta\bigr)=4\theta,

which gives Cov(X,Y)=4θ−2\textrm{Cov}(X,Y)=4\theta-2: it is +2+2 at θ=1\theta=1, −2-2 at θ=0\theta=0, and 00 at θ=12\theta=\tfrac12.

For continuous variables with a joint density, the sum becomes a double integral,

σXY=∬(x−μX)(y−μY) pX,Y(x,y) dx dy,(24.2.8)\sigma_{XY} = \iint (x-\mu_X)(y-\mu_Y)\,p_{X,Y}(x, y)\,dx\,dy , \tag{24.2.8}

averaging the product of deviations over the joint density. For our dart, both coordinates have mean 00, and Cov(X,Y)=E[XY]=1π∬diskxy dx dy=0\textrm{Cov}(X,Y)=\mathbb{E}[XY]=\frac1\pi\iint_{\textrm{disk}}xy\,dx\,dy=0, because the integrand is odd in xx while the disk is symmetric. Yet XX and YY are dependent, as the shrinking chords showed. Covariance looks only for a linear trend, and the dart's circular dependence has none, so zero covariance does not imply independence (Section 1.6 gives a discrete example, Y=X2Y=X^2). Figure 24.2.3 shows both facts on the disk.

Figure 24.2.3:

The dart's coordinates are dependent, yet unpredictable in mean and uncorrelated. (a) The chord at height Y=0.9Y=0.9 confines XX to ∣X∣≤0.44|X|\le0.44, while a chord near the middle is far longer, so XX depends on YY. Every chord is centered on x=0x=0 (green dots), so E[X∣Y]=0\mathbb{E}[X\mid Y]=0. (b) The product xyxy is positive on two quadrants and negative on the other two, all of equal area, so Cov(X,Y)=0\mathrm{Cov}(X,Y)=0.

Covariance also carries the units of both variables. In Figure 24.2.4, the bottom row plots the exact same draws as the top row, but with YY restated in cents instead of dollars. Every sample covariance jumps by a factor of 100100, even though none of the point clouds changes shape. Without the units, only the sign of a covariance is meaningful; the correlation coefficient below removes the units altogether.

Figure 24.2.4:

Top row: scatter clouds of (X,Y)(X,Y) pairs with covariance tuned negative, zero, and positive (left to right), YY in dollars: negative covariance tilts the cloud down-right, zero leaves it round, positive tilts it up-right. Bottom row: the identical draws with YY restated in cents. Every sample covariance is multiplied by 100100 while each panel's correlation ρ\rho (in its top corner) is unchanged: the magnitude of covariance carries units, only its sign is scale-free.

Covariance is linear in each argument. Adding a constant shifts both the variable and its mean by the same amount, so shifts drop out of the deviations, while multiplicative factors pull straight out: Cov(cX+d,Y)=c Cov(X,Y)\textrm{Cov}(cX+d,Y)=c\,\textrm{Cov}(X,Y). Likewise, the deviation of a sum is the sum of the deviations, so Cov(X+Z,Y)=Cov(X,Y)+Cov(Z,Y)\textrm{Cov}(X+Z,Y)=\textrm{Cov}(X,Y)+\textrm{Cov}(Z,Y) by linearity of expectation, and the same rules hold in the second slot. Moreover, independent variables always have zero covariance: whenever the joint density factorizes, the double integral for E[XY]\mathbb{E}[XY] splits into E[X] E[Y]\mathbb{E}[X]\,\mathbb{E}[Y].

Covariance also completes the rule for the variance of a sum. Write X~=X−μX\tilde X=X-\mu_X and Y~=Y−μY\tilde Y=Y-\mu_Y. By linearity, X+YX+Y has mean μX+μY\mu_X+\mu_Y and therefore deviation X~+Y~\tilde X+\tilde Y. Expanding E[(X~+Y~)2]=E[X~2]+2 E[X~Y~]+E[Y~2]\mathbb{E}[(\tilde X+\tilde Y)^2]=\mathbb{E}[\tilde X^2]+2\,\mathbb{E}[\tilde X\tilde Y]+\mathbb{E}[\tilde Y^2] yields

Var(X+Y)=Var(X)+Var(Y)+2 Cov(X,Y).(24.2.9)\textrm{Var}(X+Y) = \textrm{Var}(X) + \textrm{Var}(Y) + 2\,\textrm{Cov}(X, Y). \tag{24.2.9}

When XX and YY are independent, the covariance vanishes and the variances simply add.

The most important consequence of this rule is what happens when we average many draws. Expanding the square of a sum of nn deviations in the same way gives Var(∑iXi)=∑i∑jCov(Xi,Xj)\textrm{Var}(\sum_i X_i)=\sum_i\sum_j\textrm{Cov}(X_i,X_j). Suppose X1,…,XnX_1,\ldots,X_n are independent with common variance σ2\sigma^2. Every cross term vanishes, so the sum has variance nσ2n\sigma^2, and scaling by c=1/nc=1/n divides that variance by n2n^2. The average Xˉn=1n∑i=1nXi\bar X_n=\frac1n\sum_{i=1}^n X_i therefore has variance

Var(Xˉn)=1n2⋅nσ2=σ2n.(24.2.10)\textrm{Var}(\bar X_n)=\frac{1}{n^2}\cdot n\sigma^2=\frac{\sigma^2}{n}. \tag{24.2.10}

Averaging nn independent draws divides the variance by nn and the standard deviation by n\sqrt n: to halve the typical error, you need four times as many draws. This σ/n\sigma/\sqrt n scaling underpins every Monte Carlo estimate, in which an average of simulated samples stands in for an expectation (Section 24.5.1.7). For our dart, the average distance of nn independent throws has variance 1/(18n)1/(18n), so 556556 darts suffice to bring its standard deviation down to 0.010.01. Notice that the σ/n\sigma/\sqrt n rate requires a finite variance. The law of large numbers itself, which states that Xˉn\bar X_n converges to the mean, requires only a finite mean (Section 24.5). The Cauchy distribution has neither, and averages of its draws never settle down no matter how large nn becomes.

24.2.2.2 Correlation#

Whether the covariance 4θ−24\theta-2 in our four-cell example counts as large depends on the units of XX and YY. To strip away the units, we divide by the two standard deviations, which carry the exact same units. The correlation coefficient is

ρ(X,Y)=Cov(X,Y)σXσY.(24.2.11)\rho(X, Y) = \frac{\textrm{Cov}(X, Y)}{\sigma_{X}\sigma_{Y}}. \tag{24.2.11}

Section 1.6 stated that ρ\rho always lies between −1-1 and 11. Let us prove that bound and see exactly when equality holds.

Proposition (correlation bound). For any X,YX,Y with finite, nonzero variances, −1≤ρ(X,Y)≤1-1\le\rho(X,Y)\le 1. Equality holds if and only if Y=cX+dY=cX+d with probability one for constants c≠0c\ne0 and dd, with ρ=1\rho=1 when c>0c>0 and ρ=−1\rho=-1 when c<0c\lt 0.

Proof. A variance is never negative, so Var(tX+Y)≥0\textrm{Var}(tX+Y)\ge 0 for every real tt. Applying the variance-of-a-sum rule and the affine scaling rule turns this into a quadratic in tt,

Var(tX+Y)=Var(X) t2+2 Cov(X,Y) t+Var(Y)  ≥  0for every t.\textrm{Var}(tX+Y) = \textrm{Var}(X)\,t^2 + 2\,\textrm{Cov}(X,Y)\,t + \textrm{Var}(Y) \;\ge\; 0 \quad\textrm{for every } t.

A quadratic with a positive leading coefficient that never dips below zero can have at most one real root, so its discriminant must be non-positive:

(2 Cov(X,Y))2−4 Var(X) Var(Y)≤0,that isCov(X,Y)2≤Var(X) Var(Y).\bigl(2\,\textrm{Cov}(X,Y)\bigr)^2 - 4\,\textrm{Var}(X)\,\textrm{Var}(Y)\le 0, \qquad\textrm{that is}\qquad \textrm{Cov}(X,Y)^2 \le \textrm{Var}(X)\,\textrm{Var}(Y).

Dividing both sides by σX2σY2\sigma_X^2\sigma_Y^2 gives ρ2≤1\rho^2\le 1. If ρ2=1\rho^2=1, the discriminant vanishes and the quadratic has a double root t⋆t^\star satisfying Var(t⋆X+Y)=0\textrm{Var}(t^\star X+Y)=0. A random variable with zero variance is constant with probability one, so Y=−t⋆X+dY=-t^\star X+d with probability one, and t⋆≠0t^\star\ne0 because Var(Y)>0\textrm{Var}(Y)>0. Conversely, if Y=cX+dY=cX+d with c≠0c\ne0, then Cov(X,Y)=c Var(X)\textrm{Cov}(X,Y)=c\,\textrm{Var}(X) and σY=∣c∣σX\sigma_Y=|c|\sigma_X, giving ρ=c/∣c∣=±1\rho=c/|c|=\pm1. ■\blacksquare

The correlation measures how tightly XX and YY hug a straight line, together with the sign of that line's slope, but it ignores the magnitude of the slope: Y=0.5XY=0.5X and Y=2XY=2X both have ρ=1\rho=1. In the four-cell example, σX=1\sigma_X=1 and σY=2\sigma_Y=2, so ρ=(4θ−2)/2=2θ−1\rho=(4\theta-2)/2=2\theta-1, sweeping from −1-1 to 11 as θ\theta goes from 00 to 11. Figure 24.2.5 highlights two blind spots of ρ\rho: two point clouds with the same correlation but different slopes, and a cloud lying on a parabola whose correlation is zero.

Figure 24.2.5:

Correlation measures the tightness and sign of a linear relation, not its slope: (a) and (b) have the same ρ≈0.9\rho\approx0.9 at slopes 0.50.5 and 22. It also misses a nonlinear relation: in (c) YY is a function of XX and ρ≈0\rho\approx0.

Notice that the proof above is the classic proof of the Cauchy--Schwarz inequality ∣u⊤v∣≤∥u∥ ∥v∥|\mathbf u^\top\mathbf v|\le\|\mathbf u\|\,\|\mathbf v\|, and this is no coincidence: correlation is literally a cosine. On the space of mean-zero random variables with finite variance, the expected product acts as an inner product (treating two variables as identical when they agree with probability one). For the centered variables X~\tilde X and Y~\tilde Y, this inner product is ⟨X~,Y~⟩=E[X~Y~]=Cov(X,Y)\langle \tilde X,\tilde Y\rangle=\mathbb{E}[\tilde X\tilde Y]=\textrm{Cov}(X,Y), the induced length is the standard deviation ∥X~∥=E[X~2]=σX\|\tilde X\|=\sqrt{\mathbb{E}[\tilde X^2]}=\sigma_X, and the correlation is the cosine ⟨X~,Y~⟩/(∥X~∥ ∥Y~∥)\langle \tilde X,\tilde Y\rangle/(\|\tilde X\|\,\|\tilde Y\|). Geometrically, uncorrelated variables are orthogonal, and ρ=±1\rho=\pm1 means they are parallel.

24.2.2.3 The Covariance Matrix#

When we track nn variables at once, there is a covariance for every pair, and the natural way to organize them is in a matrix. For a random vector X=(X1,…,Xn)⊤\mathbf X=(X_1,\ldots,X_n)^\top with mean μ\boldsymbol\mu, the covariance matrix is the expected outer product of the deviation with itself,

Σ=E[(X−μ)(X−μ)⊤],Σij=Cov(Xi,Xj).(24.2.12)\boldsymbol\Sigma=\mathbb{E}\bigl[(\mathbf X-\boldsymbol\mu)(\mathbf X-\boldsymbol\mu)^\top\bigr], \qquad \Sigma_{ij}=\textrm{Cov}(X_i,X_j). \tag{24.2.12}

Its diagonal holds the individual variances, while the off-diagonal entries hold the pairwise covariances. Because Cov(Xi,Xj)=Cov(Xj,Xi)\textrm{Cov}(X_i,X_j)=\textrm{Cov}(X_j,X_i), the matrix is symmetric. It is also positive semidefinite: for any fixed vector a\mathbf a, the scalar projection a⊤X=∑iaiXi\mathbf a^\top\mathbf X=\sum_i a_iX_i has deviation a⊤(X−μ)\mathbf a^\top(\mathbf X-\boldsymbol\mu), so

Var(a⊤X)=E[a⊤(X−μ)(X−μ)⊤a]=a⊤Σ a  ≥  0.\textrm{Var}(\mathbf a^\top\mathbf X) = \mathbb{E}\bigl[\mathbf a^\top(\mathbf X-\boldsymbol\mu)(\mathbf X-\boldsymbol\mu)^\top\mathbf a\bigr] = \mathbf a^\top \boldsymbol\Sigma\,\mathbf a \;\ge\; 0 .

In words, the quadratic form a⊤Σ a\mathbf a^\top\boldsymbol\Sigma\,\mathbf a is simply the variance of the data projected onto the direction a\mathbf a, and a variance can never be negative. For the dart, Σ=diag⁡(14,14)\boldsymbol\Sigma=\operatorname{diag}(\tfrac14,\tfrac14): its coordinates are uncorrelated and equally spread. Later in the book, the eigenvectors of Σ\boldsymbol\Sigma appear as the directions of principal component analysis (Section 21.5) and as the axes of the multivariate Gaussian's elliptical contours (Section 24.3).

24.2.3 Transformations of Random Variables#

Machine learning transforms random variables constantly: an activation function acts on a pre-activation, a sampler reshapes uniform noise, and a normalizing flow warps a simple Gaussian into a complex data distribution. If XX has a known density and we set Y=g(X)Y=g(X), what is the density of YY?

24.2.3.1 The One-Dimensional Rule#

The first guess you might try, pY(y)=pX(g−1(y))p_Y(y)=p_X(g^{-1}(y)), is wrong, and our dart already shows why. Its distance can be generated as R=UR=\sqrt U with UU uniform on [0,1][0,1], yet this map turns the flat density of UU into the slanted density 2r2r. The reason is that probability mass, not density height, is conserved under a transformation. A narrow interval of width Δx\Delta x around xx carries probability about pX(x) Δxp_X(x)\,\Delta x, and gg sends it to an interval of width about Δy=∣g′(x)∣ Δx\Delta y=|g'(x)|\,\Delta x around y=g(x)y=g(x), which must carry the same probability:

pY(y) ∣g′(x)∣ Δx≈pX(x) Δx.p_Y(y)\,|g'(x)|\,\Delta x\approx p_X(x)\,\Delta x .

Wherever gg stretches the line, the same probability is spread over a wider interval, so the density must thin out by the stretch factor ∣g′(x)∣|g'(x)|; wherever gg compresses the line, the density must rise. Figure 24.2.6 illustrates these two equal-area strips for Y=eXY=e^X.

Figure 24.2.6:

Change of variables. An interval of width Δx\Delta x under pXp_X (bottom) is mapped by gg to an interval of width Δy=g′(x) Δx\Delta y=g'(x)\,\Delta x under pYp_Y (left). The two shaded areas are the same probability, so where gg stretches (Δy>Δx\Delta y>\Delta x) the density pYp_Y must be lower by the factor ∣g′(x)∣|g'(x)|. Here X∼N(0,1)X\sim\mathcal N(0,1) and Y=eXY=e^X.

Proposition (change of variables in one dimension). Let XX have a density pXp_X that is continuous on an open interval II with P(X∈I)=1P(X\in I)=1, and let g:I→Rg:I\to\mathbb{R} be continuously differentiable with g′≠0g'\ne0 on II, so that gg is strictly monotone and one-to-one. Then Y=g(X)Y=g(X) has the density

pY(y)=pX ⁣(g−1(y)) ∣dg−1dy(y)∣(24.2.13)p_Y(y) = p_X\!\big(g^{-1}(y)\big)\,\left|\frac{d g^{-1}}{dy}(y)\right| \tag{24.2.13}

on the interval g(I)g(I), and 00 outside it.

Proof. Suppose first that gg is increasing. Then g(X)≤yg(X)\le y holds precisely when X≤g−1(y)X\le g^{-1}(y), so the c.d.f.s satisfy FY(y)=FX(g−1(y))F_Y(y)=F_X(g^{-1}(y)) for y∈g(I)y\in g(I). Differentiating via the chain rule and FX′=pXF_X' = p_X (Section 24.1) gives pY(y)=pX(g−1(y)) dg−1dy(y)p_Y(y)=p_X(g^{-1}(y))\,\frac{dg^{-1}}{dy}(y). If gg is decreasing instead, then g(X)≤yg(X)\le y holds when X≥g−1(y)X\ge g^{-1}(y), so FY(y)=1−FX(g−1(y))F_Y(y)=1-F_X(g^{-1}(y)). Its derivative introduces a minus sign, which cancels the negative sign of dg−1/dydg^{-1}/dy; taking the absolute value covers both cases at once. In either case, FYF_Y is continuously differentiable on g(I)g(I), which carries all of the probability, so by the fundamental theorem of calculus its derivative is a density of YY. ■\blacksquare

Read in words, the new density at yy is the old density evaluated at the point that maps to yy, multiplied by the local compression factor of the inverse map. Since dg−1/dy=1/g′(x)dg^{-1}/dy=1/g'(x) at x=g−1(y)x=g^{-1}(y), this is the exact same 1/∣g′(x)∣1/|g'(x)| factor we obtained from the stretching argument.

Inverse-transform sampling is a change of variables, and the rule immediately recovers the dart's distance density from its sampler. Take X=UX=U uniform on I=(0,1)I=(0,1) and g(u)=ug(u)=\sqrt u, so g−1(r)=r2g^{-1}(r)=r^2 and ∣dg−1/dr∣=2r|dg^{-1}/dr|=2r. Equation (24.2.13) gives pR(r)=1⋅2rp_R(r)=1\cdot 2r, the density of the dart's distance.

When gg is not one-to-one, several input points can map to the same output yy, and their probability contributions simply add:

pY(y)=∑x: g(x)=ypX(x)∣g′(x)∣,p_Y(y)=\sum_{x:\,g(x)=y}\frac{p_X(x)}{|g'(x)|},

for values yy with finitely many preimages, each satisfying g′(x)≠0g'(x)\ne0. For Y=X2Y=X^2 and y>0y>0, the two preimages ±y\pm\sqrt y both have ∣g′∣=2y|g'|=2\sqrt y, so pY(y)=[pX(y)+pX(−y)]/(2y)p_Y(y)=[p_X(\sqrt y)+p_X(-\sqrt y)]/(2\sqrt y). The hypothesis g′≠0g'\ne0 really matters. The ReLU activation has g′=0g'=0 on the entire negative half-line (−∞,0)(-\infty,0), collapsing all of that mass onto the single point 00 and producing a point atom rather than a pure density (Exercise 2).

As a worked example, let X∼N(0,1)X\sim\mathcal N(0,1) have the standard normal density pX(x)=e−x2/2/2πp_X(x)=e^{-x^2/2}/\sqrt{2\pi}, and set Y=eXY=e^X. Here g−1(y)=log⁡yg^{-1}(y)=\log y and ∣dg−1/dy∣=1/y|dg^{-1}/dy|=1/y for y>0y>0, so the change-of-variables rule produces the log-normal density

pY(y)=1y2π exp⁡ ⁣(−12(log⁡y)2),y>0.p_Y(y) = \frac{1}{y\sqrt{2\pi}}\,\exp\!\Big(-\tfrac12(\log y)^2\Big), \qquad y>0.

The leading factor 1/y1/y is the change-of-variables correction. Setting the derivative of log⁡pY(y)=−log⁡y−12(log⁡y)2+const\log p_Y(y)=-\log y-\tfrac12(\log y)^2+\textrm{const} to zero gives log⁡y=−1\log y=-1, so the true density peaks at y=e−1≈0.368y=e^{-1}\approx0.368. By contrast, the naive guess pX(log⁡y)p_X(\log y) peaks at y=1y=1, and it is not even a valid density: substituting y=exy=e^x, its total area is ∫pX(x) ex dx=E[eX]=e1/2≈1.65\int p_X(x)\,e^x\,dx=\mathbb{E}[e^X]=e^{1/2}\approx1.65 (completing the square gives x−x2/2=12−12(x−1)2x-x^2/2=\tfrac12-\tfrac12(x-1)^2).

The same calculation gives all moments E[Yk]=E[ekX]=ek2/2\mathbb{E}[Y^k]=\mathbb{E}[e^{kX}]=e^{k^2/2}, every one of them finite. Even so, the upper tail P(Y>t)=P(X>log⁡t)P(Y>t)=P(X>\log t) decays more slowly than any exponential in tt. The log-normal distribution is therefore heavy-tailed, yet unlike the Cauchy distribution it still has finite moments of every order.

Let us plot a histogram of 10510^5 samples of eXe^X alongside both candidate curves. We already know the naive curve encloses 0.650.65 too much area; before looking at the figure, try guessing where that excess sits.

y = np.exp(rng.standard_normal(10**5))                 # Y = e^X
edges = np.linspace(0, 5, 101)
mids = (edges[:-1] + edges[1:]) / 2
hist = np.histogram(y, edges)[0] / (len(y) * (edges[1] - edges[0]))
p_X = lambda x: np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)
d2l.plot(mids, [hist, p_X(np.log(mids)) / mids, p_X(np.log(mids))],
         'y', 'p(y)', figsize=(5, 3),
         legend=['histogram of exp(X)', 'log-normal', 'naive p_X(log y)'])

The histogram tracks the log-normal density closely up to sampling noise, with its peak well to the left of y=1y=1, near e−1e^{-1}. The naive curve puts the peak in the wrong place: because it equals the true density multiplied by yy, it falls below the data for y<1y\lt 1 and rises above it for y>1y>1, by a factor that keeps growing into the tail.

24.2.3.2 The Multivariate Rule#

In several dimensions, a transformation stretches areas and volumes rather than lengths, so the stretch factor becomes a determinant. Start with the simplest case, a linear map Y=AX\mathbf Y=\mathbf A\mathbf X with A=diag⁡(2,3)\mathbf A=\operatorname{diag}(2,3). This map turns a unit square into a 2×32\times3 rectangle of area 6=det⁡A6=\det\mathbf A. Because the rectangle must carry the same probability as the original square, the density of Y\mathbf Y must be one-sixth the density of X\mathbf X at the corresponding point: pY(y)=pX(A−1y)/6p_{\mathbf Y}(\mathbf y)=p_{\mathbf X}(\mathbf A^{-1}\mathbf y)/6.

For a nonlinear map, the local stretch varies from point to point, and the change-of-variables theorem for multiple integrals accounts for it (Section 22.6). Let gg be a continuously differentiable bijection between two regions of Rn\mathbb{R}^n with a continuously differentiable inverse, and write Jg−1J_{g^{-1}} for the Jacobian matrix of partial derivatives of the inverse. Locally, g−1g^{-1} scales volume by ∣det⁡Jg−1∣|\det J_{g^{-1}}|, so substituting x=g−1(y)\mathbf x=g^{-1}(\mathbf y) in an integral over the preimage of a region D\mathcal D gives

∫g−1(D)f(x) dx=∫Df(g−1(y)) ∣det⁡Jg−1(y)∣ dy.\int_{g^{-1}(\mathcal D)} f(\mathbf x)\,d\mathbf x=\int_{\mathcal D} f\bigl(g^{-1}(\mathbf y)\bigr)\,\bigl|\det J_{g^{-1}}(\mathbf y)\bigr|\,d\mathbf y .

Now let Y=g(X)\mathbf Y=g(\mathbf X). The event Y∈D\mathbf Y\in\mathcal D is the same as the event X∈g−1(D)\mathbf X\in g^{-1}(\mathcal D), so applying the theorem with f=pXf=p_{\mathbf X} yields

P(Y∈D)=∫g−1(D)pX(x) dx=∫DpX(g−1(y)) ∣det⁡Jg−1(y)∣ dy.P(\mathbf Y\in \mathcal D)=\int_{g^{-1}(\mathcal D)}p_{\mathbf X}(\mathbf x)\,d\mathbf x =\int_{\mathcal D} p_{\mathbf X}\bigl(g^{-1}(\mathbf y)\bigr)\,\bigl|\det J_{g^{-1}}(\mathbf y)\bigr|\,d\mathbf y .

The integrand on the right is therefore the density of Y\mathbf Y:

pY(y)=pX ⁣(g−1(y)) ∣det⁡Jg−1(y)∣,log⁡pY(y)=log⁡pX(x)−log⁡∣det⁡Jg(x)∣(equivalently, at x=g−1(y)).(24.2.14)\begin{aligned} p_{\mathbf Y}(\mathbf y) &= p_{\mathbf X}\!\big(g^{-1}(\mathbf y)\big)\,\big|\det J_{g^{-1}}(\mathbf y)\big|, \\ \log p_{\mathbf Y}(\mathbf y) &= \log p_{\mathbf X}(\mathbf x) - \log\big|\det J_{g}(\mathbf x)\big| \\ &\quad\textrm{(equivalently, at }\mathbf x = g^{-1}(\mathbf y)\textrm{)}. \end{aligned} \tag{24.2.14}

The second line uses Jg−1(y)=Jg(x)−1J_{g^{-1}}(\mathbf y)=J_g(\mathbf x)^{-1}. Passing a sample through gg simply subtracts the log of the local volume stretch from its log-density. Because log⁡∣det⁡(J2J1)∣=log⁡∣det⁡J1∣+log⁡∣det⁡J2∣\log|\det(J_2 J_1)| = \log|\det J_1| + \log|\det J_2|, a composition of maps subtracts the sum of their log-determinants. This is the exact mechanism by which normalizing flows compute exact likelihoods: they stack invertible layers whose log-determinants are cheap to evaluate (Rezende and Mohamed, 2015), and Section 26.3.3 builds one whose layers are the steps of a differential equation. Exercise 5 implements a coupling layer from scratch.

Our dart provides one last illustration. Describe its position in polar coordinates, the distance RR and the angle Θ\Theta, via (x,y)=(rcos⁡θ,rsin⁡θ)(x,y)=(r\cos\theta,r\sin\theta). The Jacobian determinant of this map from (r,θ)(r,\theta) to (x,y)(x,y) is cos⁡θ⋅rcos⁡θ−(−rsin⁡θ)sin⁡θ=r\cos\theta\cdot r\cos\theta-(-r\sin\theta)\sin\theta=r, so the multivariate rule yields

pR,Θ(r,θ)=1π⋅r=2r⋅12π,0≤r≤1, 0≤θ<2π.p_{R,\Theta}(r,\theta)=\frac1\pi\cdot r=2r\cdot\frac{1}{2\pi}, \qquad 0\le r\le1,\ 0\le\theta\lt 2\pi .

The joint density factorizes cleanly. The angle Θ\Theta is uniform on [0,2π)[0,2\pi), the distance RR recovers the density 2r2r once more (now straight from a Jacobian), and the two variables are independent. In Cartesian coordinates, the dart's XX and YY were dependent; in the right coordinate system, the exact same dart is described by two independent variables.

This section leaves one central question about averages open. We now know that the average of nn independent draws has variance σ2/n\sigma^2/n (24.2.10), but we do not yet know its distribution. Chebyshev's inequality (Section 24.1) turns that variance into a bound of σ2/(nϵ2)\sigma^2/(n\epsilon^2) on the probability that the average errs by ϵ\epsilon or more, yet for bounded or Gaussian draws this bound is far too pessimistic: the true error probability drops exponentially fast in nn. We will determine which distribution an average approaches in Section 24.3.2.3, and establish the exponential decay rate in Section 24.9. Before tackling either, however, we need a richer catalog of distributions than the dart alone.

24.2.4 Summary#

Marginal densities come from integrating out unneeded variables, and conditional densities come from slicing the joint density along a thin strip and renormalizing. The conditional mean is the optimal squared-error predictor, and the law of total variance splits a variable's variance into the part that the conditioning variable explains and the part it cannot. Covariance and correlation measure linear association rather than general dependence, and averaging nn independent draws with finite variance reduces the variance to σ2/n\sigma^2/n. Under a smooth invertible map, a density is divided by the local volume stretch, given by the absolute Jacobian determinant. Our dart brings all of these ideas together: its Cartesian coordinates are dependent yet uncorrelated, while in polar coordinates they become two independent variables.

24.2.5 Exercises#

  1. Uncorrelated but dependent. Whitening, for example with the principal components of Section 21.5, makes coordinates uncorrelated. The following pair has Gaussian coordinates and zero covariance. Let X∼N(0,1)X \sim \mathcal{N}(0, 1), let SS be a random sign independent of XX with P(S=1)=P(S=−1)=12P(S = 1) = P(S = -1) = \tfrac12, and let Y=SXY = SX.

    1. Show that Y∼N(0,1)Y \sim \mathcal{N}(0, 1) by computing its c.d.f., and that Cov(X,Y)=0\textrm{Cov}(X, Y) = 0.
    2. Compare P(∣X∣≤1,∣Y∣≤1)P(|X| \le 1, |Y| \le 1) with P(∣X∣≤1) P(∣Y∣≤1)P(|X| \le 1)\,P(|Y| \le 1). Are XX and YY independent?
    3. Show that X+YX + Y has an atom at 00, so that X+YX + Y is not Gaussian. With probability one the point (X,Y)(X, Y) lies on one of the two lines y=±xy = \pm x, and a double integral over a line is zero, because a line has no area. Conclude that the pair (X,Y)(X, Y) has no joint density, although each coordinate has one.
  2. Averaging correlated estimates. The text derives Var(Xˉn)=σ2/n\textrm{Var}(\bar X_n) = \sigma^2/n for independent draws. Averages of dependent estimates behave differently.

    1. Let Y1,…,YnY_1, \ldots, Y_n each have variance σ2\sigma^2, with correlation ρ\rho between every pair, as the predictions of nn ensemble members trained on the same data might. Show that
Var(1n∑i=1nYi)=σ2(ρ+1−ρn).(24.2.15)\textrm{Var}\Bigl(\frac1n\sum_{i=1}^n Y_i\Bigr) = \sigma^2\Bigl(\rho + \frac{1-\rho}{n}\Bigr). \tag{24.2.15}

What does averaging achieve as n→∞n \to \infty?

  1. Use a⊤Σ a≥0\mathbf{a}^\top \boldsymbol\Sigma\, \mathbf{a} \ge 0 for the covariance matrix Σ\boldsymbol\Sigma of Y1,…,YnY_1, \ldots, Y_n to show that ρ≥−1/(n−1)\rho \ge -1/(n-1). Give variables that attain this bound.
  1. [code] Sigmoid of a Gaussian. Let X∼N(0,s2)X \sim \mathcal{N}(0, s^2) be the pre-activation of a sigmoid unit, and let Y=sigmoid⁡(X)Y = \operatorname{sigmoid}(X), whose inverse is logit⁡(y)=log⁡(y/(1−y))\operatorname{logit}(y) = \log\bigl(y/(1-y)\bigr).

    1. Use (24.2.13) to find the density pYp_Y on (0,1)(0, 1).
    2. For which ss is y=12y = \tfrac12 a local minimum of pYp_Y? Writing log⁡pY\log p_Y as a function of z=logit⁡(y)z = \operatorname{logit}(y) simplifies the computation.
    3. Modify the #random-variables-change-of-variables cell to compare a histogram of YY with pYp_Y for s∈{1,2,3}s \in \{1, \sqrt{2}, 3\}. What does the histogram at s=3s = 3 imply for the derivative sigmoid⁡′(X)=Y(1−Y)\operatorname{sigmoid}'(X) = Y(1 - Y), through which backpropagation passes the gradient of these units?
  2. Explained variance. ● A regression model hh predicts a target XX from an input YY. The fraction of the variance that it explains is R2=1−E[(X−h(Y))2]/Var(X)R^2 = 1 - \mathbb{E}\bigl[(X - h(Y))^2\bigr]/\textrm{Var}(X).

    1. Use (24.2.6) and the law of total variance (24.2.5) to show that every predictor has R2≤Var(E[X∣Y])/Var(X)R^2 \le \textrm{Var}\bigl(\mathbb{E}[X \mid Y]\bigr)/\textrm{Var}(X). Evaluate this ceiling for the two-component mixture of the text, predicting XX from the label ZZ, and for the dart, predicting XX from YY.
    2. Given the input, the target is −1-1 or +1+1 with probability 12\tfrac12 each. Which prediction minimizes the expected squared error, and how often does the target take that value? Which predictions minimize the expected absolute error E[∣X−h(Y)∣]\mathbb{E}\bigl[|X - h(Y)|\bigr]?
  3. [code] Affine coupling layer and Box--Muller. ● Normalizing flows stack invertible maps whose log-determinants in (24.2.14) are cheap to compute. The affine coupling layer of RealNVP (Dinh et al., 2017) maps x∈R2\mathbf{x} \in \mathbb{R}^2 to

y1=x1,y2=x2 es(x1)+t(x1),(24.2.16)y_1 = x_1, \qquad y_2 = x_2\, e^{s(x_1)} + t(x_1), \tag{24.2.16}

where ss and tt are arbitrary functions, for example small neural networks.

  1. Write down the inverse map and the Jacobian Jg(x)J_g(\mathbf{x}). Show that log⁡∣det⁡Jg(x)∣=s(x1)\log|\det J_g(\mathbf{x})| = s(x_1), however complicated ss and tt are.
  2. Let X1X_1 and X2X_2 be independent standard normal variables, and take s(x1)=tanh⁡(x1)s(x_1) = \tanh(x_1) and t(x1)=x12/2t(x_1) = x_1^2/2. Use (24.2.14) to write log⁡pY(y)\log p_{\mathbf{Y}}(\mathbf{y}) in closed form. With NumPy, evaluate pYp_{\mathbf{Y}} on a grid over [−6,6]×[−12,24][-6, 6] \times [-12, 24] with spacing 0.020.02 and check that its Riemann sum is close to 11. Check the log-determinant against the determinant of a finite-difference Jacobian at a few random points.
  3. The first coordinate passes through the layer unchanged. What is the distribution of Y1Y_1, whatever ss and tt are? How must a second coupling layer be arranged so that the composition can change both marginals, and what is the log-determinant of the composition?
  4. Flows can also run from uniform noise to Gaussians. Let U1,U2U_1, U_2 be independent and uniform on (0,1)(0, 1), and set R=−2log⁡U1R = \sqrt{-2\log U_1}, Θ=2πU2\Theta = 2\pi U_2, and (Z1,Z2)=(Rcos⁡Θ,Rsin⁡Θ)(Z_1, Z_2) = (R\cos\Theta, R\sin\Theta). Find the density of RR with the one-dimensional rule, then the joint density of (R,Θ)(R, \Theta), and change to Cartesian coordinates with the polar Jacobian of the text to show that Z1Z_1 and Z2Z_2 are independent standard normal variables. This is the Box--Muller method. Check with 10510^5 samples that the sample covariance matrix of (Z1,Z2)(Z_1, Z_2) is close to the identity.

Discussions