24.2 Joint Distributions and Transformations
In Section 24.1, we reduced our dart on a board of radius to a single number: its distance from the center, which has density . A dart actually lands at a point, however, with both a horizontal coordinate and a vertical coordinate . 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 , then must lie within of the center line, so observing certainly tells us something about . Yet, surprisingly, we will find that our best single guess for is still no matter what 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 from a uniform variable , and taking the square root turns a flat density into the linear density . 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 of a pair gives the probability of landing in a small square of side at as roughly its area times the density,
As in one dimension, tiling a region of the plane with such squares leads to the property we take as the formal definition: , and , so that the total volume under the joint density over the whole plane equals . For variables, the same definition holds with -dimensional boxes and -fold integrals.
For our dart, every part of the unit disk is equally likely and the board has area , so the joint density is inside the disk and outside. Notice that even though this density is flat on the disk, it cannot be written as a function of times a function of : 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 has probability about . Slicing that strip into small squares along and adding their probabilities gives
Canceling one factor of and recognizing the remaining sum as a Riemann sum in , we obtain
In words, the marginal density at is the joint density integrated up the vertical strip at , as illustrated in Figure 24.2.1: we simply integrate out the variable we do not need. For the dart, the vertical strip at crosses the board from to , giving
which traces out a semicircle. As a quick check, is the area of half the unit disk, , so indeed integrates to . 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.
A continuous joint density shown by its contours, with one vertical strip at highlighted. Integrating the joint density up that strip, over all , gives the height of the marginal density plotted along the -axis below. Sweeping the strip across traces out the whole marginal.
24.2.1.2 Conditional Densities and Independence#
Once we observe that , how should our density for change? For discrete variables, the answer is simply . With continuous densities, however, that formula divides zero by zero because . The way out is the same limiting argument that defined the density in the first place: we condition on a thin horizontal strip , 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
Inside the strip, the probability of a short -interval is its length times . That ratio is the probability per unit length of given , so we define the conditional density as
For every fixed with , this is a valid density in : it is non-negative, and by the marginal rule (24.2.1) it integrates to . Geometrically, we slice the joint density along the horizontal line and rescale that cross-section to unit area. For the dart, the horizontal line cuts across the board on the chord , so
Given , the horizontal position is uniform along the chord at height . Because that chord shrinks as grows, observing changes the distribution of .
Rearranging (24.2.2) gives the chain rule . Writing the joint density both ways, , and solving for yields Bayes' rule for densities,
Just as Bayes' theorem did for discrete variables in Section 1.6, this identity turns a model of how is generated from into a distribution over after seeing .
In the special case where observing tells us nothing new about , so that whenever , we call the two variables independent and write . By the chain rule, independence is equivalent to saying that the joint density factorizes, (up to sets of probability zero): multiply by to go one way and divide by it to go the other.
Intuitively, independence means that the conditional density of is the same function of , with the same location and the same shape, at every height . Consider the joint density on the unit square . Its marginal is , which gives regardless of , so . The dart is the opposite case: its conditional density is uniform at every , yet it lives on a chord whose length depends on .
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.
Conditioning as slicing. Left: a joint density with three horizontal slices at . Right: each slice renormalized to unit area is the conditional density . Top: a correlated pair; the three conditionals have the same shape but shifted centers, so the conditional depends on 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 , the pair has joint density at , and integrating out via (24.2.1) leaves the convolution .
24.2.1.3 Conditional Expectation#
A regression model predicts a target from an input. To stay consistent with the previous subsection, we keep as the target and as the observed input (whereas the main text writes the pair the other way around). Training with squared loss searches for a function that makes as small as possible. Which function is best? Within any thin strip , the model must predict a single number for an entire spread of possible targets. For any random variable , the constant closest to it in mean squared distance is its mean , since expanding the square around gives . That suggests predicting the average of inside each strip. Accordingly, the conditional expectation of given is the mean of the conditional density,
It is simply the average of among all outcomes with . As varies, traces out a function of ; evaluated at the random variable , it becomes a random variable that depends on alone. The same strip average defines for any function . Because a factor is constant within each strip, it pulls straight out of the conditional expectation:
Similarly, the spread of within a strip is the conditional variance , 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 have a joint density, and let have finite variance (for discrete pairs, the same identities hold with integrals replaced by sums). Then
Proof. For the first identity, known as the tower property, write out the inner expectation and apply the chain rule to reassemble the strips into the joint density:
Values of with , where the conditional density is undefined, contribute to neither side because lands there with probability zero. The same computation with in place of gives . For the second identity, expand both terms on the right. Applying the tower property to gives
Applying (Section 24.1) to the random variable , whose mean is by the tower property, gives
Adding the two lines, the middle term cancels and leaves .
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 into two pieces: the average variance within each strip, which knowing can never remove, and the variance of the strip averages themselves, which is the portion that 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 have finite variance, and let be any function with . Then
Proof. Write and split the prediction error into two parts, . Squaring produces two squared terms and a cross term, and only the cross term requires care. The expectation of the first square is by the tower property. The cross term has conditional mean zero: the factor depends on alone and pulls out of the strip average, leaving . By the tower property, its overall mean is zero as well.
Look at the two terms on the right. The first does not depend on at all, while the second is non-negative and vanishes when . 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 , which is how Section 2.1 interprets its model (written there as ).
Two examples make this decomposition concrete. First, return to the dart and try to predict from . Given , the horizontal coordinate is uniform on a chord symmetric about , so . A uniform variable on an interval of half-width has variance , which gives . By symmetry , so Eve's law yields
All of the variance stays in the unexplained term. Knowing narrows the range of without ever shifting its center, so the best squared-error predictor of from is the constant , even though and are dependent.
For a second example, draw a binary label that equals with probability and with probability . Given , draw from the normal distribution with mean and variance ; given , draw from . This mixture produces the two-bump density of Figure 24.1.1. Its overall mean is . Within each component the variance is , so . Between the components, takes the values and , whose variance is . The total variance is therefore , and the label explains of it. In a sample of one million draws, the empirical within- and between-component terms will land near and . 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 ( and ), 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 moves with , which makes it an entire function. Often we prefer a single summary number: do and 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 taking with probability , it is
where the second form follows by expanding the product, just as in the computational form of the variance. In particular, . Throughout this section we assume both variances are finite; since , the expectation of is then guaranteed to exist.
As a concrete example, let and with joint probabilities
for a parameter . We will refer to this as the four-cell example. Each variable takes its two values with probability , so and . The expectation of the product is
which gives : it is at , at , and at .
For continuous variables with a joint density, the sum becomes a double integral,
averaging the product of deviations over the joint density. For our dart, both coordinates have mean , and , because the integrand is odd in while the disk is symmetric. Yet and 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, ). Figure 24.2.3 shows both facts on the disk.
The dart's coordinates are dependent, yet unpredictable in mean and uncorrelated. (a) The chord at height confines to , while a chord near the middle is far longer, so depends on . Every chord is centered on (green dots), so . (b) The product is positive on two quadrants and negative on the other two, all of equal area, so .
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 restated in cents instead of dollars. Every sample covariance jumps by a factor of , 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.
Top row: scatter clouds of pairs with covariance tuned negative, zero, and positive (left to right), in dollars: negative covariance tilts the cloud down-right, zero leaves it round, positive tilts it up-right. Bottom row: the identical draws with restated in cents. Every sample covariance is multiplied by while each panel's correlation (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: . Likewise, the deviation of a sum is the sum of the deviations, so 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 splits into .
Covariance also completes the rule for the variance of a sum. Write and . By linearity, has mean and therefore deviation . Expanding yields
When and 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 deviations in the same way gives . Suppose are independent with common variance . Every cross term vanishes, so the sum has variance , and scaling by divides that variance by . The average therefore has variance
Averaging independent draws divides the variance by and the standard deviation by : to halve the typical error, you need four times as many draws. This 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 independent throws has variance , so darts suffice to bring its standard deviation down to . Notice that the rate requires a finite variance. The law of large numbers itself, which states that 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 becomes.
24.2.2.2 Correlation#
Whether the covariance in our four-cell example counts as large depends on the units of and . To strip away the units, we divide by the two standard deviations, which carry the exact same units. The correlation coefficient is
Section 1.6 stated that always lies between and . Let us prove that bound and see exactly when equality holds.
Proposition (correlation bound). For any with finite, nonzero variances, . Equality holds if and only if with probability one for constants and , with when and when .
Proof. A variance is never negative, so for every real . Applying the variance-of-a-sum rule and the affine scaling rule turns this into a quadratic in ,
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:
Dividing both sides by gives . If , the discriminant vanishes and the quadratic has a double root satisfying . A random variable with zero variance is constant with probability one, so with probability one, and because . Conversely, if with , then and , giving .
The correlation measures how tightly and hug a straight line, together with the sign of that line's slope, but it ignores the magnitude of the slope: and both have . In the four-cell example, and , so , sweeping from to as goes from to . Figure 24.2.5 highlights two blind spots of : two point clouds with the same correlation but different slopes, and a cloud lying on a parabola whose correlation is zero.
Correlation measures the tightness and sign of a linear relation, not its slope: (a) and (b) have the same at slopes and . It also misses a nonlinear relation: in (c) is a function of and .
Notice that the proof above is the classic proof of the Cauchy--Schwarz inequality , 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 and , this inner product is , the induced length is the standard deviation , and the correlation is the cosine . Geometrically, uncorrelated variables are orthogonal, and means they are parallel.
24.2.2.3 The Covariance Matrix#
When we track 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 with mean , the covariance matrix is the expected outer product of the deviation with itself,
Its diagonal holds the individual variances, while the off-diagonal entries hold the pairwise covariances. Because , the matrix is symmetric. It is also positive semidefinite: for any fixed vector , the scalar projection has deviation , so
In words, the quadratic form is simply the variance of the data projected onto the direction , and a variance can never be negative. For the dart, : its coordinates are uncorrelated and equally spread. Later in the book, the eigenvectors of 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 has a known density and we set , what is the density of ?
24.2.3.1 The One-Dimensional Rule#
The first guess you might try, , is wrong, and our dart already shows why. Its distance can be generated as with uniform on , yet this map turns the flat density of into the slanted density . The reason is that probability mass, not density height, is conserved under a transformation. A narrow interval of width around carries probability about , and sends it to an interval of width about around , which must carry the same probability:
Wherever stretches the line, the same probability is spread over a wider interval, so the density must thin out by the stretch factor ; wherever compresses the line, the density must rise. Figure 24.2.6 illustrates these two equal-area strips for .
Change of variables. An interval of width under (bottom) is mapped by to an interval of width under (left). The two shaded areas are the same probability, so where stretches () the density must be lower by the factor . Here and .
Proposition (change of variables in one dimension). Let have a density that is continuous on an open interval with , and let be continuously differentiable with on , so that is strictly monotone and one-to-one. Then has the density
on the interval , and outside it.
Proof. Suppose first that is increasing. Then holds precisely when , so the c.d.f.s satisfy for . Differentiating via the chain rule and (Section 24.1) gives . If is decreasing instead, then holds when , so . Its derivative introduces a minus sign, which cancels the negative sign of ; taking the absolute value covers both cases at once. In either case, is continuously differentiable on , which carries all of the probability, so by the fundamental theorem of calculus its derivative is a density of .
Read in words, the new density at is the old density evaluated at the point that maps to , multiplied by the local compression factor of the inverse map. Since at , this is the exact same 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 uniform on and , so and . Equation (24.2.13) gives , the density of the dart's distance.
When is not one-to-one, several input points can map to the same output , and their probability contributions simply add:
for values with finitely many preimages, each satisfying . For and , the two preimages both have , so . The hypothesis really matters. The ReLU activation has on the entire negative half-line , collapsing all of that mass onto the single point and producing a point atom rather than a pure density (Exercise 2).
As a worked example, let have the standard normal density , and set . Here and for , so the change-of-variables rule produces the log-normal density
The leading factor is the change-of-variables correction. Setting the derivative of to zero gives , so the true density peaks at . By contrast, the naive guess peaks at , and it is not even a valid density: substituting , its total area is (completing the square gives ).
The same calculation gives all moments , every one of them finite. Even so, the upper tail decays more slowly than any exponential in . 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 samples of alongside both candidate curves. We already know the naive curve encloses 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 , near . The naive curve puts the peak in the wrong place: because it equals the true density multiplied by , it falls below the data for and rises above it for , 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 with . This map turns a unit square into a rectangle of area . Because the rectangle must carry the same probability as the original square, the density of must be one-sixth the density of at the corresponding point: .
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 be a continuously differentiable bijection between two regions of with a continuously differentiable inverse, and write for the Jacobian matrix of partial derivatives of the inverse. Locally, scales volume by , so substituting in an integral over the preimage of a region gives
Now let . The event is the same as the event , so applying the theorem with yields
The integrand on the right is therefore the density of :
The second line uses . Passing a sample through simply subtracts the log of the local volume stretch from its log-density. Because , 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 and the angle , via . The Jacobian determinant of this map from to is , so the multivariate rule yields
The joint density factorizes cleanly. The angle is uniform on , the distance recovers the density once more (now straight from a Jacobian), and the two variables are independent. In Cartesian coordinates, the dart's and 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 independent draws has variance (24.2.10), but we do not yet know its distribution. Chebyshev's inequality (Section 24.1) turns that variance into a bound of on the probability that the average errs by or more, yet for bounded or Gaussian draws this bound is far too pessimistic: the true error probability drops exponentially fast in . 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 independent draws with finite variance reduces the variance to . 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#
-
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 , let be a random sign independent of with , and let .
- Show that by computing its c.d.f., and that .
- Compare with . Are and independent?
- Show that has an atom at , so that is not Gaussian. With probability one the point lies on one of the two lines , and a double integral over a line is zero, because a line has no area. Conclude that the pair has no joint density, although each coordinate has one.
-
Averaging correlated estimates. The text derives for independent draws. Averages of dependent estimates behave differently.
- Let each have variance , with correlation between every pair, as the predictions of ensemble members trained on the same data might. Show that
What does averaging achieve as ?
- Use for the covariance matrix of to show that . Give variables that attain this bound.
-
[code] Sigmoid of a Gaussian. Let be the pre-activation of a sigmoid unit, and let , whose inverse is .
- Use (24.2.13) to find the density on .
- For which is a local minimum of ? Writing as a function of simplifies the computation.
- Modify the
#random-variables-change-of-variablescell to compare a histogram of with for . What does the histogram at imply for the derivative , through which backpropagation passes the gradient of these units?
-
Explained variance. ● A regression model predicts a target from an input . The fraction of the variance that it explains is .
- Use (24.2.6) and the law of total variance (24.2.5) to show that every predictor has . Evaluate this ceiling for the two-component mixture of the text, predicting from the label , and for the dart, predicting from .
- Given the input, the target is or with probability each. Which prediction minimizes the expected squared error, and how often does the target take that value? Which predictions minimize the expected absolute error ?
-
[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 to
where and are arbitrary functions, for example small neural networks.
- Write down the inverse map and the Jacobian . Show that , however complicated and are.
- Let and be independent standard normal variables, and take and . Use (24.2.14) to write in closed form. With NumPy, evaluate on a grid over with spacing and check that its Riemann sum is close to . Check the log-determinant against the determinant of a finite-difference Jacobian at a few random points.
- The first coordinate passes through the layer unchanged. What is the distribution of , whatever and 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?
- Flows can also run from uniform noise to Gaussians. Let be independent and uniform on , and set , , and . Find the density of with the one-dimensional rule, then the joint density of , and change to Cartesian coordinates with the polar Jacobian of the text to show that and are independent standard normal variables. This is the Box--Muller method. Check with samples that the sample covariance matrix of is close to the identity.