SStatistics, Built

Stage I · Bachelor's: Foundations

Part 5 of 65

Many Variables at Once

Bachelor'sstarts at this level51 min of film16 chaptersprerequisites: Part 3, Part 4

What does knowing one thing tell you about another?

In 1886 Francis Galton tabulates 928 adult children of 205 families against their mid-parents, smooths the counts and sees nested ellipses; the children's averages lie on a line of slope about two-thirds, which he calls regression towards mediocrity. The part reads a joint distribution three ways and builds a Gaussian slicer that cuts a density and renormalizes the slice. Uncorrelated is shown not to be independent. The conditional mean is proved to be the best predictor, a projection, and Eve's law splits variance into within and between. The multivariate normal is an affine image of independent normals, and its conditionals have linear means and Schur-complement variances: regression is born. Regression to the mean then turns out to be no force at all, since it runs backwards and leaves the population's spread unchanged. Three lines pass through one ellipse; copulas, Polya's urn, de Finetti's theorem, measures of dependence and the simplex close the part.

What you need. Multivariable calculus (double integrals, Jacobians) and the matrix language of Part 4.

Hook
Galton's ellipses, 1886
Mathematics
conditional expectation as projection, Eve's law, the multivariate normal, conditioning, regression to the mean, copulas, exchangeability
Built
a Gaussian slicer; Pólya's urn

What you will be able to do

Bachelor's

  • Compute marginal and conditional distributions from a joint table, and say why a zero correlation does not prove independence.
  • Compute the regression line from two means, two SDs and r, and predict how far an extreme group will fall back on a second measurement.
  • Explain why regression to the mean is not a force, using the fact that it runs in both directions.

Master's

  • Prove that E[Y | X] minimizes mean squared error, and derive Eve's law from the tower property.
  • Derive the conditional distribution of a multivariate normal by decorrelation, and read conditional independence from a zero of the precision matrix.
  • Compute the density of a transformed vector with its Jacobian.

PhD

  • State de Finetti's theorem for infinite exchangeable 0-1 sequences, and give the finite urn that shows why the sequence must be infinite.
  • Explain what the L2 projection picture of E[Y | X] still needs to be rigorous (Part 44).

Practice

  • Diagnose regression to the mean in a before-and-after comparison of a group selected for being extreme.
  • Choose a copula by its tail dependence, not only by its correlation, and say what the Gaussian copula assumed in 2008.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 26 min · Master's 47 min · PhD 51 min · Practice 30 min.

  1. 0Galton's ellipsesBachelor's3 min
  2. 1Joint, marginal, conditionalBachelor's4 min
  3. 2DependenceBachelor's3 min
  4. 3Conditional expectationBachelor's4 min
  5. 4Eve's lawBachelor's4 min
  6. 5The multivariate normalMaster's3 min
  7. 6Conditioning a GaussianMaster's4 min
  8. 7Regression to the meanBachelor's4 min
  9. 8Three lines through one ellipseBachelor's3 min
  10. 9Change of variablesMaster's2 min
  11. 10Latent variablesMaster's3 min
  12. 11CopulasPractice3 min
  13. 12ExchangeabilityPhD3 min
  14. 13Measuring dependenceMaster's3 min
  15. 14The simplexMaster's3 min
  16. Recap, problems, and the road aheadAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Galton's ellipsesBachelor's3 min

In the 1880s Francis Galton, Charles Darwin's half-cousin, collected the heights of families. He gathered records of two hundred and five families, nine hundred and twenty-eight adult children and their parents, and in 1886 published what he found, in a paper with a striking title: regression towards mediocrity in hereditary stature. To put men and women on one scale he multiplied every woman's height by one point oh eight, and summarized each pair of parents by their average, the mid-parent. Galton was also the founder of eugenics, the attempt to improve the human race by controlling who has children. The statistics he invented outlived those aims, which this series does not share; but the record should say both.

Here is Galton's table, exactly as he grouped it. Each row is a mid-parent height, in inches; each column a child's adult height; each cell the number of children. Tall parents, near the top, tend to have tall children, toward the right; short parents short children. But the counts are spread widely: a table of tendencies, not of rules. Galton stared at it for a long time before he saw its shape.

Galton smoothed the table, replacing each count by the average of a block of four, and then drew lines through cells with equal counts. The contours were approximately elliptical. A fitted Gaussian has ellipses with the same centre and the same shape, nested inside one another. He took them to a mathematician, J. D. Hamilton Dickson, who confirmed that they're exactly what a bivariate normal law predicts. They're the ellipses of Part 4's spectral theorem, used as a model of a table of heights, rather than exact contours of its noisy counts.

Then Galton asked the question of this part. For each mid-parent height, what is the average height of the children? If children simply resembled their parents, the averages would lie on the diagonal. They don't. They lie on a flatter line, with slope about , which Galton called two thirds. Children of tall parents are tall, but less extreme than their parents; children of short parents are short, but less so. Galton called it regression towards mediocrity. He thought he'd discovered a law of heredity. In fact he'd discovered a fact about every ellipse, and by the end of this part we'll see why it must happen, and why it fools people still.

What it does: Galton's 1886 table, counted and smoothed into nested ellipses; "regression towards mediocrity"; the objectives.; Numbers (computed): 928 children, 205 families; r = 0.459; slope 0.646 (Galton's "two-thirds")

1Joint, marginal, conditionalBachelor's4 min

With two variables there are three different distributions in one table. Group Galton's children into four bands of mid-parent height and four of child height, and divide by nine hundred and twenty-eight: the joint distribution, the chance of each combination. Add along each row and you get the marginal distribution of the mid-parent's height, ignoring the child. Add down each column and you get the marginal for the child. Now take just the tallest parents' row and divide it by its total: the conditional distribution of the child's height, given the tallest parents. It's Part 2's conditioning, keep a slice and renormalize, applied to a table.

For continuous variables the table becomes a surface. Here's a fitted model of the joint density of mid-parent height and a son's height in the World, as a bivariate normal: the height of the surface over each point is the density there, and the volume underneath is one. Turn it around. It's a ridge, running diagonally, because tall parents go with tall sons; seen from above, its contour lines are Galton's ellipses.

This is the build of the part: the Gaussian slicer. Fix the mid-parent height at a hundred and seventy-eight centimetres and cut the surface there. The cut is a curve, f of x and y with x held fixed, but it isn't a density: its area is the marginal density of x, not one. Divide by that area, and the slice is rescaled into the conditional density of the son's height, given the parents. Do it at a hundred and seventy, and at a hundred and sixty-two. Three slices, three conditional distributions, and the computed means and standard deviations can be compared with the nearby families in the World; the Gaussian is an approximation. Notice two things: every slice of a Gaussian is a Gaussian, and they all have the same width. Only the centre moves as x changes, and it moves along a straight line. That straight line is the birth of regression, and chapter six proves it.

Two facts follow at once. The joint density can be sliced either way: as the marginal of x times the conditional of y given x, or the other way round. Equate them and you have Bayes' theorem for densities, the engine of Part 15. And two variables are independent exactly when the joint density factors into its marginals, which means every renormalized slice is the same: knowing x tells you nothing about y.

Here's a joint distribution we can compute exactly. Roll two dice, and record the larger and the smaller. The table counts the thirty-six equally likely rolls. The diagonal has one way each, a double; above it, two ways each, since either die can be the larger; below it, nothing, since the minimum can't exceed the maximum. The row sums give the marginal of the maximum: two k minus one out of thirty-six, climbing toward six. The column sums give the minimum's, the mirror image. The means add to seven, as they must, since the maximum plus the minimum is the total. The covariance comes out to exactly thirty-five over thirty-six, squared, and the correlation to thirty-five over seventy-three, almost a half. The empty triangle is dependence you can see: knowing the maximum is two rules out most of the table.

What it does: Galton's table in four bands: joint cells, row and column sums, a conditional row; the joint density as a surface; slicing it with the Gaussian slicer; Bayes for densities; the exact joint table of the max and min of two dice.; Numbers (computed): slices at 162/170/178 cm: conditional means 170.4/176.3/182.3, SD 6.06; Cov(max, min) = (35/36)², corr = 35/73

2DependenceBachelor's3 min

Correlation measures one kind of dependence: how well a straight line fits. Here y is x squared, plus independent noise: its mean is determined by x. The population correlation is zero, because the parabola's two arms cancel. A noisy ring: knowing x restricts y to two narrow bands, yet the population correlation is zero. And here y is x times a random sign. With an independent fair sign, each variable is standard normal, the correlation is zero, but the size of y is exactly the size of x: if x is beyond one and a half, so is y, every time. For finite, positive variances, independence implies zero correlation. Zero correlation implies nothing of the kind.

Covariance is what correlation is built from. The expected product of the two deviations from the means, or the mean of the product minus the product of the means. For a vector of variables, all the covariances form a matrix, and it's positive semidefinite, by Part 4's argument: every linear combination has a variance, and variances aren't negative. And covariance is bounded by the product of the standard deviations: Cauchy–Schwarz again. That's not a coincidence. Random variables with finite variance form an inner-product space, with the expected product as the inner product. Covariance is an inner product, correlation a cosine, and in the next chapter conditional expectation will be a projection.

Correlation matters most when we average. The variance of a sum is the sum of the variances plus all the covariances. For n variables with equal variance and equal correlation rho, the variance of their average is sigma squared over n, times one plus n minus one times rho. With no correlation it falls like one over n, the sigma over root n of Part 1. With correlation it doesn't fall to zero; it levels off at rho sigma squared. Averaging kills independent noise but not shared noise. That's why diversifying across correlated stocks has limits, and why a hundred measurements made with the same biased instrument are worth little more than one.

Independence has one more subtlety once there are three variables. Flip two fair coins, X and Y, and let Z be one when they differ and zero when they agree: the exclusive or. Four equally likely rows. Look at any two of the three. X and Z: each of the four combinations has probability a quarter, the product of the marginals. So every pair is independent. But all three together are not: X and Y both one forces Z to be zero, so the triple of ones has probability zero, not an eighth. Any two determine the third. This is Sergei Bernstein's example: pairwise independence does not imply mutual independence, which is why mutual independence is what we assume of a sample, and why checking pairs is never enough.

What it does: A gallery of uncorrelated-but-dependent shapes (Y = X², the ring, the random-sign pair); covariance as a bilinear form; the variance of an average of equicorrelated variables (diversification); Bernstein's pairwise-but-not-mutually independent coins.; Numbers (computed): r ≈ 0.000, −0.006, −0.007; Var(X̄)/σ² → ρ

3Conditional expectationBachelor's4 min

Suppose we must predict a variable Y from another, X, and we're judged by mean squared error. What's the best possible prediction? Here are the World's adults: age across, the logarithm of income up. Ignoring age, the best constant is the mean. The best straight line in age barely helps: in the World, incomes rise through the early career, level off, and drop at retirement, at sixty-seven, and a line can't follow that. The best prediction of any kind is the conditional mean: for each age, the average log income of adults of that age. It follows the career curve, step and all, and its mean squared error, , is the smallest any function of age can achieve.

Assume Y and the competing predictor have finite second moments. The proof is Part 1's Pythagoras, one level up. Write m of X for the conditional mean, and compare any other predictor g of X. Add and subtract m. Expand the square: three terms. The cross term vanishes: condition on X, and the error Y minus m of X averages to zero for every value of X, whatever function of X it's multiplied by. So any predictor's error is the conditional mean's error plus something nonnegative. The conditional mean is the best predictor, uniquely up to events of probability zero.

One property of conditional expectation is used more than any other. The average of the conditional means is the overall mean: the tower property, or the law of total expectation. For a discrete X it's Part 2's law of total probability, applied to means. Average the World's age-by-age mean incomes, weighting each age by how many adults have it, and you recover the overall mean exactly. We'll lean on this in every part that conditions.

And here's the picture behind the proof. In the inner-product space of random variables, the functions of X form a subspace, drawn as a plane. Y is a vector off the plane. The best predictor of Y from X is the closest point of the plane: the orthogonal projection. That's the conditional expectation. The prediction error stands at right angles to the plane, which is exactly the vanishing cross term. Regression in Part 12 projects onto the smaller subspace of linear functions; conditional expectation projects onto all functions. Part 44 builds this properly, with measure theory.

The conditional mean is the best predictor for squared error. Change the loss and the answer changes, just as in Part 1. For absolute error, the best predictor is the conditional median: for each value of x, the median of y among those cases. For the asymmetric tilted loss, it's a conditional quantile, which is quantile regression. Here are the World's incomes in thousands, not their logarithms. Incomes are skewed to the right, so at every age the conditional mean, pulled up by the high earners, sits above the conditional median. Both follow the career curve and the drop at retirement. Which one is the right prediction depends entirely on how you'll be scored. Part 21 computes conditional quantiles by linear programming.

What it does: The World's log incomes by age: the best constant, the best line, the conditional mean; the proof that E[Y | X] minimizes mean squared error; the tower property; E[Y | X] as an orthogonal projection in L²; the conditional median under absolute loss and conditional quantiles.; Numbers (computed): MSE 0.408 / 0.405 / 0.360; R² 0.007 for the line vs 0.119 for E[Y | X]

4Eve's lawBachelor's4 min

For a variable with finite second moment, the projection picture gives another law for free. Split Y's deviation from its mean into the prediction error and the prediction's own deviation. The two pieces are perpendicular, so their squared lengths add. By the tower property, that says the variance of Y is the expected conditional variance plus the variance of the conditional mean. Noise within groups, plus variation between them. Blitzstein and Hwang's textbook calls it Eve's law, for E V plus V E; it's also called the law of total variance, and Part 3 met it as the variance of a mixture.

Galton's table splits cleanly. The children's heights vary with a variance of about square inches. Most of it, , is spread within each mid-parent-height row: children differ even at the same parental height. Only is between rows, the part that parents' heights account for. The ratio, the share of variance explained, is . It's the honest version of R squared, and because Galton's row means lie close to a straight line, it almost equals the squared correlation.

In the World it works the same way. Group the log incomes by age band: within plus between. Age explains about ten percent of the variance, the career curve. Region explains essentially none, which is correct, because the World was built with no regional income effect. Within plus between is the skeleton of the analysis of variance in Part 13, and of the random-effects models of Part 25, where the between part is itself a parameter to estimate.

Eve's law also exposes a common mistake. The share of variance explained by the conditional mean has a name, Karl Pearson's correlation ratio, eta squared. For the World's log incomes, the squared correlation with age is , almost nothing, but eta squared is : age explains about sixteen times as much as the straight line can. The squared correlation measures how well the best line does; eta squared, how well the best function does. They agree only when the conditional mean is linear, as it is for the bivariate normal. A small r squared does not mean a weak relationship.

Eve's law says conditioning reduces variance. Be careful what that means. Let X be a rare switch, on one time in ten, and let Y be zero when the switch is off and a wide normal, standard deviation ten, when it's on. The variance of Y is ten. Now learn that the switch is on. The conditional variance is a hundred, ten times larger: this piece of information made us less certain. Eve's law only promises the average: the expected conditional variance is at most the variance. Information reduces uncertainty on average, not in every case, a fact Part 15 meets again when a single surprising observation widens a posterior.

What it does: Var Y = E Var(Y | X) + Var E[Y | X], derived; Galton's children; the World's incomes by age; Pearson's correlation ratio η² against r²; a rare switch that makes the conditional variance larger.; Numbers (computed): Galton 6.33 = 4.93 + 1.40 (η² 0.221 vs r² 0.210); log income 0.408 = 0.367 + 0.041

5The multivariate normalMaster's3 min

Galton's ellipses belong to one distribution, and it has a simple definition. Start with independent standard normals: a round cloud. Multiply by a matrix A and add a vector mu. The cloud stretches, turns and moves, and its circles become ellipses. That's the multivariate normal: any affine image of independent standard normals. Its covariance is A A transpose, by Part 4's rule, and the sample covariance of the simulated points agrees. When Sigma is positive definite, its density follows from the change of variables: the inverse of Sigma in the exponent, and the square root of its determinant, the Jacobian, in front.

From the definition, everything follows. An affine image of a multivariate normal is again multivariate normal, with covariance B Sigma B transpose. So the marginals are normal: pick out coordinates with a matrix of zeros and ones. Every linear combination is normal. And the contours of the density are the ellipsoids of the spectral theorem. In fact the third property characterizes it: a vector is multivariate normal exactly when every linear combination of its coordinates is normal, a consequence of the Cramér–Wold device that Part 6 will use.

There's one trap. Remember the random-sign pair from chapter two: X standard normal, Y equal to X times a random sign. Y is standard normal too, and they're uncorrelated. But they're dependent, since the size of Y is the size of X. And the pair isn't jointly normal: X plus Y is exactly zero half the time, while its variance is positive, which rules out even a degenerate normal law. Two normals need not be jointly normal. When they are, the special property holds: uncorrelated means independent, because a diagonal covariance makes the density factor.

How would you check that data are multivariate normal? Whiten them: the squared Mahalanobis distance of a multivariate normal vector is the squared length of the underlying standard normal, so it's chi-squared with p degrees of freedom. With known mean and covariance, sort the squared distances and plot them against chi-squared quantiles: Part 1's QQ plot, now checking radial fit in p dimensions at once. For four thousand simulated three-dimensional normal vectors, the points lie near the diagonal. This diagnostic alone cannot establish joint normality: directions matter too. Fitting the mean and covariance also changes the finite-sample reference. Curvature can flag tail mismatch or outliers, which Part 30 hunts.

What it does: AZ + μ moving a round cloud into an ellipse; the density from the change of variables; affine images, marginals, Cramér–Wold; two normals that are not jointly normal; squared Mahalanobis distances against χ²₃ as a radial diagnostic (insufficient to establish joint normality).; Numbers (computed): sample covariance matches AAᵀ; 4,000 draws on the χ²₃ diagonal

6Conditioning a GaussianMaster's4 min

The slicer showed every slice of a Gaussian is a Gaussian of the same width, centred on a straight line. Here's the theorem. Split a multivariate normal vector with positive definite covariance into two blocks. Given the first block, the second is normal again. Its mean is linear in the observed value: the prior mean, plus a matrix times the surprise. And its covariance is the Schur complement from Part 4's chapter on block matrices, which doesn't depend on the observed value at all.

The proof is a single trick. Subtract from X two the part that's linearly predictable from X one, and call the remainder W. W is uncorrelated with X one, and since they're jointly normal, chapter five says W is independent of X one. So X two is an independent normal W plus a linear function of X one. Given X one, only W is random: X two is normal, centred at the linear function. And its covariance is W's, the Schur complement.

With just two variables, the theorem is the regression line. The conditional mean of Y given x is mu Y plus rho times the ratio of standard deviations, times the deviation of x: a straight line with slope rho sigma Y over sigma X. The conditional variance is sigma Y squared times one minus rho squared: a fraction rho squared of the variance is explained. And in standard units, the prediction is simply rho times the standardized x. Since rho is between minus one and one, its magnitude is no larger than the standardized x, and is strictly smaller away from zero when the absolute correlation is below one. That one line is regression to the mean.

Put Galton's numbers in. The mid-parents average sixty-eight point three inches with standard deviation ; the children sixty-eight point one with ; the correlation is . The slope is r times the ratio of standard deviations: , Galton's two-thirds, now derived rather than observed. Around the line, children still scatter with a standard deviation of inches. The slope is bigger than r because children vary more than mid-parents do: a mid-parent is an average of two people, and averages vary less, as Part 6 will make precise.

The conditioning formula hides a beautiful fact about the inverse of the covariance matrix. Build a chain: Y is X times point eight plus noise; Z is Y times point seven plus noise. Z depends on X only through Y. In the correlation matrix, every entry is non-zero: X and Z are correlated, , through Y. Now invert it. The inverse, called the precision matrix, has an exact zero linking X and Z. That's the rule for a multivariate normal with positive definite covariance: a zero in the precision matrix means the two variables are independent given all the others, and the scaled entry, with a minus sign, is their partial correlation. Correlation shows every path of dependence; the precision matrix shows only the direct links. Arthur Dempster built covariance selection on this in 1972, and Part 31's graphical models draw the network straight from the zeros.

What it does: The conditioning theorem (Schur complement) and its proof by decorrelation; the two-variable case is the regression line; Galton's numbers; the precision matrix of a chain X → Y → Z, whose zero means conditional independence.; Numbers (computed): conditional SD √(1 − r²)·s_y; corr(X, Z) = 0.56 but K₁₃ = 0

7Regression to the meanBachelor's4 min

Regression to the mean appears in the World too. Take the tallest tenth of mid-parents: on average centimetres above the mean. Their sons are tall, but only centimetres above average. The ratio is close to the regression slope. Does that mean the population is converging to the average, generation by generation? No: the World's sons are just as spread out as their fathers. Galton was puzzled by exactly this. The resolution is that regression is not a force; it's a property of a conditional mean when the correlation is imperfect.

The clearest proof that it isn't a force: it runs backwards. In Galton's data, take the tallest children instead. Their parents were tall too, but less extreme: the parents regress toward their generation's mean. If regression were a biological force pulling families toward the average, it couldn't act backwards in time. It's simply what happens for a bivariate Gaussian: select on one being extreme in standard units, and the other will on average be less so. It's the shape of the ellipse.

Galton's own puzzle was this: if children regress toward the mean, why doesn't the population become more uniform every generation? Eve's law answers it. A child's height is the predictable part, the slope times the parents' deviation, plus a residual. Their variances add. In Galton's data, the predictable part has shrunk to a variance of about one point three, but the residual adds five, and together they give back the children's full variance. Regression pulls the predictable part toward the mean, and fresh, unpredictable variation spreads it out again: there is no necessary shrinking of the population spread. The table itself is not evidence about many generations.

Regression to the mean fools people constantly. Suppose a test score is skill plus luck, in equal measure. Ten thousand people take two tests; their scores correlate at about a half. The top tenth on the first test averaged standard deviations above the mean. On the second test they fall to about . The bottom tenth improve by the same amount. Nobody changed; the luck that put them in the extreme group didn't repeat. That's the sophomore slump, the magazine-cover jinx, and the false success of any treatment given to the people who did worst, who would have improved anyway. Part 35's randomized controls exist partly to defeat it.

Daniel Kahneman told a story about this. Lecturing to flight instructors in the Israeli Air Force, he said praise works better than punishment. An instructor objected: whenever he praised a cadet for an exceptionally smooth landing, the next one was worse; whenever he shouted at a cadet for a bad one, the next was better. He was seeing regression to the mean. Exceptional performances are partly luck, and are usually followed by more ordinary ones, whatever the instructor says. The moral reaches through the whole degree: to learn whether something works, you must compare with what would have happened anyway.

What it does: The World's tallest tenth of mid-parents and their sons; both directions; Galton's stable variance via Eve's law; skill + luck test–retest; Kahneman's flight instructors.; Numbers (computed): +8.76 → +6.60 cm; 6.33 = 1.33 + 5.00; top tenth about 1.71 → 0.83 SD, bottom about −1.74 → −0.86

8Three lines through one ellipseBachelor's3 min

There isn't one line through a cloud of points; there are three, and confusing them causes real mistakes. The regression of child on mid-parent, the conditional mean, has slope . It passes through the points where the ellipse's tangent is vertical: for each x, the middle of the vertical slice. The regression of mid-parent on child, predicting parents from children, is a different line, much steeper when drawn on the same axes. It passes through the horizontal tangent points. And between them lies the major axis of the ellipse, the direction of greatest spread: Part 4's first principal component. Galton noticed in 1889 that regression runs both ways, from parents to children and from children back to parents.

Why three? Because they answer three questions. The regression of y on x minimizes the squared vertical distances from the points: the best way to predict y from x. The regression of x on y minimizes the squared horizontal ones: the best way to predict x from y. The major axis minimizes squared perpendicular distances, treating the two variables symmetrically. Only for a perfect correlation do the three agree. To predict, use the regression of the variable you're predicting. When both variables are measured with error and you want the underlying relationship, neither regression is right; that's the errors-in-variables problem of Part 23.

Here's what goes wrong when x is measured with error. In blue, y against the true x, with slope one. Now we don't see x, only x plus independent noise of the same size. The cloud spreads sideways, and the fitted slope falls to about a half. The reason is one line: noise in x leaves the covariance with y unchanged but inflates the variance of x, so the slope is multiplied by the reliability ratio, the share of x's variance that's real. Here it's a half. This is regression dilution: errors in the predictor bias the slope toward zero, and it's the same arithmetic as regression to the mean. Charles Spearman saw it in 1904 and proposed correcting a correlation for the unreliability of both measurements.

What it does: Y on X, X on Y and the major axis on Galton's ellipse; what each minimizes; errors in variables and Spearman's attenuation.; Numbers (computed): slopes 0.646, 1/0.326, 2.02; slope 1.01 → 0.49 with reliability ½

9Change of variablesMaster's2 min

Part 3 changed variables in one dimension and previewed the Jacobian. Here's the full picture. A transformation g maps a tiny square of area d A to a tiny parallelogram whose area is the absolute determinant of the Jacobian matrix times d A. Probability is conserved, so the density must shrink where areas grow: for a smooth one-to-one map with nonzero determinant, the new density is the old one at the preimage, times the absolute Jacobian determinant of the inverse. For multiple preimages we sum their contributions.

The distribution of a sum is a change of variables in disguise. Map the pair of uniforms to their sum and the first one: a shear, which keeps areas, so the Jacobian is one. Integrate out the extra coordinate, and the density of the sum is the convolution of the two densities, Part 2's polynomial multiplication, for continuous variables. For two uniforms it's a triangle, peaking at one: forty thousand simulated sums approximate it.

One more, with a famous answer. Take the ratio of two independent standard normals. Map the pair to the ratio and the denominator; now the Jacobian is the absolute value of the denominator. Integrate it out, and the ratio has density one over pi times one plus r squared: the Cauchy, Part 3's lighthouse, met from a different direction. A ratio of two perfectly ordinary variables has no mean at all, which is one reason ratios are dangerous statistics.

Polar coordinates give one more classic. How far from the centre does a two-dimensional standard normal point land? Change to polar coordinates; the area element is r d r d theta, so the Jacobian is r. Integrate out the angle and the distance has density r times e to the minus r squared over two: the Rayleigh distribution, with mean root pi over two. Note that it's zero at the centre, even though the density of points is highest there: there's very little room near the centre. In three dimensions the same calculation gives Maxwell's distribution of molecular speeds.

What it does: The density of a transformed vector and its Jacobian; the sum of two uniforms by convolution (a triangle); the ratio of two normals (Cauchy); polar coordinates and the Rayleigh distribution.; Numbers (computed): E R = √(π/2) = 1.2533 vs simulated 1.2567

10Latent variablesMaster's3 min

Some variables shape the data without appearing in it. Here are the heights of all the World's adults. The histogram is a blend of two normal curves, one for men and one for women, each weighted by about a half. Their mixture, gold, matches the histogram. The overall standard deviation, over nine centimetres, is larger than either group's, because it includes the gap between the groups: Eve's law again. If the data didn't record sex, it would be a latent variable: present in the process, absent from the table.

In symbols, a latent class Z with probabilities pi k, and given the class a density for x. Marginalize the class away: sum over it, weighting by its probabilities. With two normal components it's the two-component mixture. Karl Pearson fitted one in 1894 to Raphael Weldon's measurements of crabs from the Bay of Naples, suspecting two subspecies, solving a ninth-degree polynomial by hand to match the moments. Today mixtures are fitted by the EM algorithm of Part 22, and the latent variables of factor analysis and topic models grow from this one formula.

Going the other way, the data tell us about the latent class. Given only a height, the chance that the person is a man is Bayes' theorem: the man's component at that height, over the total. It rises smoothly from near zero for short adults to near one for tall ones, crossing a half at about centimetres. These posterior class probabilities are the expectation step of the EM algorithm.

Latent variables explain a paradox from Part 1. In the World's clinic, the treated recovered less often overall, yet more often within each level of severity. Marginalizing over severity mixes the severe and the mild. For the treated, the overall rate is a mixture weighted mostly toward the severe, sixty-three percent of them, because doctors treat the sicker patients; for the untreated, a mixture weighted toward the mild. Different weights on very different groups reverse the comparison. Simpson's paradox is a latent variable that the treatment depends on, and Part 36 shows when we can adjust for it.

What it does: The World's adult heights as a mixture of men and women; marginalizing a latent class; Pearson's crabs (1894); the posterior class probability (the E step of EM); Simpson's paradox in Part 1's clinic as a latent variable.; Numbers (computed): men 176.0 ± 7.1, women 163.0 ± 6.4, all SD 9.37; clinic: treated 0.624 vs 0.737 overall, but higher within each severity

11CopulasPractice3 min

A joint distribution mixes two things: the shape of each variable on its own, and the way they move together. Copulas pull them apart. Pass each variable through its own CDF. With continuous margins each becomes uniform: Part 3's probability integral transform. What's left is a joint distribution on the unit square, with uniform margins: the copula. Abe Sklar proved in 1959 that every joint distribution is its copula applied to its margins, so you can choose the margins and the dependence separately. The copula is unique for continuous margins; discrete margins need extra care, and the raw CDF transform need not be uniform. The copula depends only on ranks, which is why the rank correlations of chapter thirteen are properties of it.

Same strength of dependence, different shapes. Three copulas, each with a Kendall rank correlation of one half. The Gaussian copula is symmetric. The Clayton copula clusters tightly in the lower-left corner: when one variable is very low, the other does with high probability too. The Gumbel copula does the same in the upper-right. Measure the tails directly: given that one variable is in its bottom five percent, how often is the other? For the Gaussian about ; for Clayton . And as the threshold goes further out, the Gaussian's tail dependence goes to zero, while Clayton's stays positive. The same correlation can hide very different behaviour in a crisis.

Sklar's theorem is also a recipe for simulation. Draw pairs from a bivariate normal with correlation point seven. Pass each coordinate through the normal CDF. Now both margins are uniform, and what's left is the Gaussian copula: the dependence, stripped of the margins. Then push each uniform through the inverse CDF of any margin you like: here, an exponential and a lognormal. Kendall's tau is unchanged through every step, because each step is increasing in each coordinate. Pearson's correlation drifts. This recipe, Part 3's probability integral transform run backwards in two dimensions, is how risk models and simulation studies build joint distributions with realistic margins.

This mattered in the real world. In 2000 David Li showed how to price bundles of loans with a Gaussian copula, and it became the industry's standard tool for collateralized debt. It summarized the dependence between borrowers by a single correlation, and the Gaussian copula has zero asymptotic tail dependence when correlations are below one. That does not make finite-threshold joint defaults negligible; their probability depends on correlations and default rates. Static assumptions, calibration and how the model was used could still understate systemic risk. In the financial crisis of 2007 and 2008, defaults arrived together. Historians of finance argue about how much the formula itself was to blame, as against how it was used; but the mathematical lesson is plain. One correlation number cannot determine tail behaviour, where much risk lives in the tails.

What it does: Sklar's theorem (1959); Gaussian, Clayton and Gumbel copulas with the same Kendall's τ and different tails; sampling from a copula with any margins; Li's Gaussian copula and the crisis.; Numbers (computed): τ = 0.5; joint tail rates (lower/upper) 0.45/0.375, 0.68/0.12, 0.33/0.555; τ 0.507 survives every step

12ExchangeabilityPhD3 min

Here's the second build: Pólya's urn, a model of contagion that George Pólya and Florian Eggenberger studied in 1923. Start with one red ball and one blue. Draw one at random, look at it, and put it back together with another of the same colour. Each draw makes its own colour more likely next time: the rich get richer. Watch thirty draws, and the share of red.

Run thirty urns for a thousand draws each. Each share wanders early, then changes more slowly: after a few hundred draws, one more ball hardly changes it. But different urns approach different values, anywhere from nearly zero to nearly one. Collect the final shares of four thousand urns. They're spread evenly across the interval: the limit of Pólya's urn, starting from one ball of each colour, is uniformly distributed, a beta of one and one. Start with a red and b blue and the limit is a beta of a and b.

The draws are clearly not independent: each one changes the urn. Yet they have a beautiful symmetry. The chance of red, red, blue is a half times two thirds times a quarter: one twelfth. Red, blue, red: a half times a third times two quarters: also a twelfth. And blue, red, red: the same. Only the number of reds matters, not their order. Sequences like this are called exchangeable: any reordering has the same probability. Exchangeability is weaker than independent and identically distributed, and it's exactly the right assumption for a lot of real data.

And exchangeability has a stunning consequence. Bruno de Finetti proved in 1931 that any infinite exchangeable sequence of zeros and ones behaves as if there were an unknown probability p, drawn once from some distribution, with the observations independent given p. In symbols, the probability of any sequence is an average of independent Bernoulli probabilities over a distribution for p. For Pólya's urn, p is the urn's limiting share, and its distribution is uniform. De Finetti, a subjectivist, read this as a justification for Bayesian statistics: if your Bernoulli observations form an infinite exchangeable sequence, you must act as though there's an unknown parameter with a prior distribution. Part 15 begins there; Part 44 proves the theorem.

There's a fine print to de Finetti's theorem. Draw without replacement from an urn of two red and two blue balls. The sequence is exchangeable, since every order of the colours is equally likely, but the draws are negatively correlated: a red first makes red less likely second. No mixture of identically distributed independent Bernoulli sequences can produce negative correlation, so the theorem fails here. It needs the sequence to go on forever, or at least to be much longer than the part we see: Persi Diaconis and David Freedman showed in 1980 that the total variation error is at most about n squared over N for n draws from an exchangeable sequence of length N.

What it does: The Pólya urn machine; its limiting fractions are uniform; exchangeable sequences; de Finetti's theorem (1931); finite exchangeability without replacement and the Diaconis–Freedman bound.; Numbers (computed): RRB, RBR, BRR each 1/12; urn RRBB: P(RR) = 1/6 vs 1/4, corr −1/3

13Measuring dependenceMaster's3 min

If correlation misses so much, what should we use instead? Six shapes, five measures of dependence each. On the noisy line, they all agree there's strong dependence. On the parabola, the circle and the cross, Pearson's r and the two rank correlations are all near zero: they measure monotone trends, and these shapes have none. But distance correlation and mutual information are well above zero. On pure noise, everything is near zero, apart from a small positive bias in the estimated mutual information. No single number captures a relationship, but some are blind to more than others.

The rank correlations deserve a closer look. Charles Spearman's, from 1904, is Pearson's correlation computed on the ranks instead of the values. Maurice Kendall's, from 1938, counts pairs of points: the fraction that are in the same order on both variables, minus the fraction in opposite orders. Both depend only on ranks, so they're properties of the copula: unchanged by taking logarithms or any other increasing transformation, and hardly moved by an outlier. Part 16 uses them to build tests that avoid specifying a parametric distribution, while still requiring their sampling and null assumptions.

Here's that invariance, measured. Take eight hundred of the World's fathers and sons, and then distort the son's height through an exponential: same order, different scale. Pearson's correlation drops from to . Spearman's and Kendall's don't move at all, to the last digit. An increasing transformation preserves order, so it preserves ranks and the copula, and rank correlations measure only that.

The other two measures see any kind of dependence. Distance correlation, introduced by Gábor Székely, Maria Rizzo and Nail Bakirov in 2007, measures how far the joint characteristic function is from the product of the marginal ones, Part 3's characteristic functions put to work. With finite first moments, population distance correlation is zero exactly when the variables are independent, which correlation can't claim. Mutual information, from Claude Shannon's information theory, measures how far the joint density is from the product of its marginals, and it too is zero only under independence. The price is interpretability, noise in small samples, and, for mutual information, the need for an estimation method, such as density estimation or nearest neighbours, which Part 29 teaches.

What it does: Pearson, Spearman, Kendall, distance correlation and mutual information on six shapes; rank correlations defined; their invariance under an increasing transform, measured; dCor and MI.; Numbers (computed): Pearson 0.396 → 0.301; Spearman 0.379 and Kendall 0.259 unchanged

14The simplexMaster's3 min

Many variables are proportions that must add up to one: the shares of a vote, the frequencies of blood groups. Counts in k categories from n independent draws follow the multinomial distribution, Part 2's multinomial coefficient times the probabilities. Its counts are negatively correlated, since they must add up to n: more of one leaves fewer for the others.

To model the proportions themselves as uncertain, we need a distribution on the simplex: the triangle of all vectors of proportions adding to one. The Dirichlet distribution, named for Peter Gustav Lejeune Dirichlet, has density proportional to each proportion raised to a power alpha minus one. It's the beta distribution in more dimensions. With all alphas one, it's uniform on the triangle. With large equal alphas, it concentrates in the middle. With alphas below one, it pushes mass into the corners: most draws put nearly everything in one category. And unequal alphas pull it toward one corner, with mean alpha i over the sum of the alphas.

Where does the Dirichlet come from? There's a construction that's also how computers draw from it. Take k independent gamma variables, with positive shape parameters alpha one through alpha k and a common scale, here one. Divide each by their total. Change variables from the k gammas to the k minus one free proportions and the total. The absolute Jacobian determinant of the inverse map, from proportions and total back to gammas, is t to the k minus one, chapter nine's machinery again. And the joint density factors: a Dirichlet in the proportions times a gamma in the total. So the proportions are exactly Dirichlet, and they're independent of the total, a fact Eugene Lukacs showed in 1955 characterizes the gamma. That independence holds for this gamma construction; it is not a universal fact about vote totals and shares. With k equal to two this is the beta, as a ratio of gammas.

The Dirichlet and the multinomial fit together perfectly. Choose proportions from a Dirichlet. Draw counts from a multinomial with those proportions. Then, given the counts, the proportions are Dirichlet again, with the counts simply added to the alphas. That's called conjugacy, and Part 15 builds Bayesian inference on it. And it's Pólya's urn again: the urn with k colours adds one ball of the drawn colour each time, which is exactly this update, one observation at a time.

Proportions carry a trap that Karl Pearson spotted in 1897. Take three independent positive lognormal variables, X, Y and Z. X and Y are uncorrelated. Now divide both by Z, as you do when you form shares or per-capita rates. The ratios are strongly correlated, about point five, purely because they share a denominator. Pearson called it spurious correlation, and it haunts anything measured as a share of a whole. For genuine compositions, John Aitchison's log-ratios from 1982 are a useful framework for relative information, not a universal fix.

What it does: The multinomial and its negative covariances; the Dirichlet in four shapes; the Dirichlet as normalized gammas (and independent of their total); Dirichlet–multinomial conjugacy; Pearson's spurious correlation of ratios.; Numbers (computed): sample corr(X/Z, Y/Z) = 0.46 from independent positive lognormal X, Y, Z

Recap, problems, and the road aheadAll tracks3 min

Part five in fourteen lines. Galton's table held ellipses, and children regressed toward the mean. A joint distribution is read three ways, and conditioning slices and renormalizes. Uncorrelated is not independent. The conditional mean is the best predictor, a projection; and the law of total variance splits variance into within and between. The multivariate normal is an affine image of independent normals, and its conditionals have linear means and Schur-complement variances: regression is born. Regression to the mean is not a force but a property of imperfect correlation, and three different lines pass through every ellipse. Densities change with Jacobians; sums convolve; ratios can be Cauchy. Latent classes make mixtures. Copulas separate margins from dependence, and their tails matter. Pólya's urn is exchangeable, and de Finetti's theorem turns exchangeability into Bayes. Rank, distance and information measures see what correlation misses; and the Dirichlet lives on the simplex.

Where it comes back. Conditional expectation is the backbone of regression, causal inference and martingales. Within and between returns in the analysis of variance and random effects. Gaussian conditioning is regression, mixed models, the Kalman filter and kriging. Regression to the mean haunts every before-and-after comparison. Mixtures return with the EM algorithm and factor analysis; copulas in robust statistics; exchangeability in Bayesian statistics and in the conformal prediction of Part 34; and the Dirichlet with counts and categories.

Six problems, with full solutions in the README. Uncorrelated but dependent; a proof of Eve's law; a bivariate normal's conditional; predicting a retest; Pólya's urn's first n draws; and the sum of three uniforms. Pause here if you want to try them.

The books and papers this part follows: Blitzstein and Hwang, Anderson's classic on multivariate analysis, Nelsen and Joe on copulas, and Stigler's histories, along with the original papers from Galton to Székely, Rizzo and Bakirov.

Five parts of sixty-five, halfway through the first stage. We can now describe many variables at once. Part 1 found that every summary jiggles from sample to sample; Galton's mid-parents varied less than individuals because they're averages. Why does the average of many random things become predictable, and why does its distribution so often take the shape of a bell? Those are the laws of averages, and they're Part 6.

Where it goes next. Conditional expectation is the backbone of regression in Part 12, causal inference in Parts 35-37 and the martingales of Part 44; within and between returns as ANOVA in Part 13 and random effects in Part 25; Gaussian conditioning returns as the Kalman filter in Part 38 and kriging in Part 39; exchangeability as Bayes in Parts 15 and 26 and as conformal prediction in Part 34.

Key results

The part's results in one place, for revision.

Best predictor\(\displaystyle \mathbb E\bigl[(Y-g(X))^2\bigr]\ \ge\ \mathbb E\bigl[(Y-\mathbb E[Y\mid X])^2\bigr]\quad\allowbreak \text{for }\allowbreak \text{every }g,\qquad\allowbreak \mathbb E\bigl[\mathbb E[Y\mid X]\bigr]=\mathbb E Y\)
Eve's law\(\displaystyle \operatorname{Var}Y=\mathbb E\bigl[\operatorname{Var}(Y\mid X)\bigr]+\operatorname{Var}\bigl(\mathbb E[Y\mid X]\bigr)\)
Conditioning a Gaussian\(\displaystyle X_1\mid X_2=x_2\ \sim\ N\bigl(\mu_1+\Sigma_{12}\Sigma_{22}^{-1}(x_2-\mu_2),\ \ \Sigma_{11}-\Sigma_{12}\Sigma_{22}^{-1}\Sigma_{21}\bigr)\)
Regression to the mean\(\displaystyle \mathbb E[Y\mid X=x]=\mu_y+\rho\,\frac{\sigma_y}{\sigma_x}(x-\mu_x),\qquad\allowbreak \operatorname{Var}(Y\mid X=x)=(1-\rho^2)\,\sigma_y^2\)
Sklar's theorem\(\displaystyle F(x,y)=C\bigl(F_X(x),\,F_Y(y)\bigr),\quad\allowbreak C\text{ a }\allowbreak \text{copula, }\allowbreak \text{unique }\allowbreak \text{when }\allowbreak \text{the }\allowbreak \text{margins }\allowbreak \text{are }\allowbreak \text{continuous}\)
de Finetti, for an infinite exchangeable 0-1 sequence\(\displaystyle P(X_1=x_1,\dots,X_n=x_n)=\int_0^1\theta^{s}(1-\theta)^{n-s}\,d\mu(\theta),\qquad\allowbreak s=\sum_{i} x_i\)

Try it

Lab 5 · Slicing an ellipse: conditional means, Eve's law and regression to the mean

Recompute Galton's correlation and slope from his 1886 table, split the children's variance into within and between mid-parent rows, then slice a simulated bivariate normal with Galton's moments and compare each slice's mean and SD with the conditioning formula.

Figure produced by Lab 5: Slicing an ellipse: conditional means, Eve's law and regression to the mean
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.stats.labs 5 needs numpy, scipy, matplotlib · download lab05.py · source on GitHub
Galton: children, correlation, slope        928   r = 0.459   slope = 0.646   (Galton's two-thirds)
Eve's law on Galton's rows                  6.33 = 4.93 within + 1.40 between
correlation ratio and r squared             eta^2 = 0.221   r^2 = 0.210
slice at mid-parent 66.0: mean, SD          66.61, 2.23   formula 66.60, 2.24   (7,675 points)
slice at mid-parent 68.3: mean, SD          68.09, 2.25   formula 68.08, 2.24   (17,917 points)
slice at mid-parent 70.5: mean, SD          69.51, 2.23   formula 69.51, 2.24   (8,572 points)
World: tallest tenth of mid-parents         +8.76 cm; their sons +6.60 cm   (ratio 0.753, slope 0.746)
World: SD of the fathers and of their sons  7.08 and 7.12 cm   (no shrinking)

Slicing a Gaussian gives a normal whose mean moves along a line flatter than the diagonal and whose spread is the same in every slice: regression to the mean is the shape of the ellipse, not a force.
The code (101 lines; it asserts its own result)
"""Lab 5: Galton's table recomputed, a Gaussian sliced and renormalized, and regression to the mean in the World."""

import numpy as np

from videos.coursekit import labs
from explainer.stats import museum
from explainer.stats.world import World

TITLE = "Slicing an ellipse: conditional means, Eve's law and regression to the mean"
GOAL = ("Recompute Galton's correlation and slope from his 1886 table, split the children's variance into within and "
        "between mid-parent rows, then slice a simulated bivariate normal with Galton's moments and compare each "
        "slice's mean and SD with the conditioning formula.")
TASKS = [
    "Slice on the child's height instead and predict the mid-parent. Is the slope the reciprocal of 0.646?",
    "Set the correlation of the simulated cloud to 0.9, then to 0.1. How does the conditional SD change, and the "
    "share of the variance that lies between rows?",
    "In the World, follow the shortest tenth of mid-parents instead of the tallest. How far below average are their "
    "sons, in centimetres and as a share of the parents' deficit?",
]


def galton_points():
    """One (mid-parent, child) pair per child, in inches, from Galton's grouped table."""
    P, C, T = np.array(museum.GALTON_PARENT), np.array(museum.GALTON_CHILD), np.array(museum.GALTON_TABLE)
    return np.repeat(np.repeat(P, len(C)), T.ravel()), np.repeat(np.tile(C, len(P)), T.ravel())


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. Galton's table: correlation, slope, and Eve's law over its rows.
    x, y = galton_points()
    mx, my, S = x.mean(), y.mean(), np.cov(np.vstack([x, y]), ddof=0)
    r = S[0, 1] / np.sqrt(S[0, 0] * S[1, 1])
    slope = S[0, 1] / S[0, 0]
    rows = np.unique(x)
    wts = np.array([np.mean(x == k) for k in rows])
    row_mean = np.array([y[x == k].mean() for k in rows])
    row_var = np.array([y[x == k].var() for k in rows])
    within, between, total = (wts * row_var).sum(), (wts * (row_mean - my) ** 2).sum(), y.var()
    eta2 = between / total
    lab.row("Galton: children, correlation, slope", f"{len(x)}   r = {r:.3f}   slope = {slope:.3f}   (Galton's two-thirds)")
    lab.row("Eve's law on Galton's rows", f"{total:.2f} = {within:.2f} within + {between:.2f} between")
    lab.row("correlation ratio and r squared", f"eta^2 = {eta2:.3f}   r^2 = {r * r:.3f}")
    assert len(x) == 928 and abs(r - 0.459) < 0.001 and abs(slope - 0.646) < 0.001, "the film's numbers"
    assert np.isclose(total, within + between) and abs(within - 4.93) < 0.01 and abs(between - 1.40) < 0.01
    assert eta2 >= r * r, "the conditional mean explains at least as much as the best line"

    # 2. A bivariate normal with Galton's moments, sliced at three mid-parent heights.
    n = 400_000
    xy = rng.multivariate_normal([mx, my], S, n)
    cond_sd = np.sqrt(S[1, 1] - S[0, 1] ** 2 / S[0, 0])  # the Schur complement
    slices = []
    for x0 in (66.0, 68.3, 70.5):
        near = np.abs(xy[:, 0] - x0) < 0.1
        ys = xy[near, 1]
        cond_mean = my + slope * (x0 - mx)
        slices.append((x0, ys, cond_mean))
        lab.row(f"slice at mid-parent {x0}: mean, SD", f"{ys.mean():.2f}, {ys.std():.2f}   formula {cond_mean:.2f}, {cond_sd:.2f}   ({len(ys):,} points)")
        assert abs(ys.mean() - cond_mean) < 5 * cond_sd / np.sqrt(len(ys)) + 0.01, "the conditional mean is linear in x0"
        assert abs(ys.std() / cond_sd - 1) < 0.05, "the conditional SD does not depend on x0"
    assert cond_sd < np.sqrt(S[1, 1])

    # 3. Regression to the mean in the World: the tallest tenth of mid-parents and their sons.
    f = World().families
    son = f["son"]
    mid, child = ((f["father"] + f["mother"]) / 2)[son], f["child"][son]
    top = mid >= np.quantile(mid, 0.9)
    mid_dev, son_dev = mid[top].mean() - mid.mean(), child[top].mean() - child.mean()
    w_slope = np.cov(mid, child, ddof=0)[0, 1] / mid.var()
    lab.row("World: tallest tenth of mid-parents", f"+{mid_dev:.2f} cm; their sons +{son_dev:.2f} cm   (ratio {son_dev / mid_dev:.3f}, slope {w_slope:.3f})")
    sd_fathers, sd_sons = f["father"][son].std(), child.std()
    lab.row("World: SD of the fathers and of their sons", f"{sd_fathers:.2f} and {sd_sons:.2f} cm   (no shrinking)")
    assert 0 < son_dev < mid_dev and abs(son_dev / mid_dev - w_slope) < 0.03, "the sons fall back by the slope"
    assert abs(sd_sons / sd_fathers - 1) < 0.02, "yet the sons are as spread out as their fathers"
    lab.note = ("Slicing a Gaussian gives a normal whose mean moves along a line flatter than the diagonal and whose "
                "spread is the same in every slice: regression to the mean is the shape of the ellipse, not a force.")

    fig, ax = labs.figure(2, size=(11, 4.4))
    P, C, T = np.array(museum.GALTON_PARENT), np.array(museum.GALTON_CHILD), np.array(museum.GALTON_TABLE)
    gp, gc = np.meshgrid(P, C, indexing="ij")
    ax[0].scatter(gp[T > 0], gc[T > 0], s=6 * T[T > 0], color=labs.BLUE, alpha=0.45, label="Galton's counts (area)")
    line = np.array([63.5, 73.5])
    ax[0].plot(line, line - mx + my, color=labs.MUTED, ls="--", label="children as extreme as parents")
    ax[0].plot(line, my + slope * (line - mx), color=labs.GOLD, label=f"regression line, slope {slope:.2f}")
    ax[0].plot(rows, row_mean, "o", color=labs.RED, ms=4, label="mean child in each row")
    ax[0].set(title="Galton's table, 1886 (inches)", xlabel="mid-parent height", ylabel="adult child's height")
    ax[0].legend(loc="lower right")
    grid = np.linspace(60, 77, 300)
    for (x0, ys, cond_mean), color in zip(slices, (labs.TEAL, labs.GOLD, labs.PURPLE)):
        ax[1].hist(ys, bins=40, density=True, color=color, alpha=0.3)
        ax[1].plot(grid, np.exp(-0.5 * ((grid - cond_mean) / cond_sd) ** 2) / (cond_sd * np.sqrt(2 * np.pi)), color=color,
                   label=f"mid-parent {x0}: N({cond_mean:.1f}, {cond_sd:.2f}$^2$)")
    ax[1].plot(grid, np.exp(-0.5 * ((grid - my) / np.sqrt(S[1, 1])) ** 2) / np.sqrt(2 * np.pi * S[1, 1]), color=labs.MUTED,
               ls="--", label="all children")
    ax[1].set(title="Three slices of the fitted Gaussian, renormalized", xlabel="child's height", ylabel="density",
              ylim=(0, 0.26))
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Slice on the child's height instead and predict the mid-parent. Is the slope the reciprocal of 0.646?
  2. Set the correlation of the simulated cloud to 0.9, then to 0.1. How does the conditional SD change, and the share of the variance that lies between rows?
  3. In the World, follow the shortest tenth of mid-parents instead of the tallest. How far below average are their sons, in centimetres and as a share of the parents' deficit?

Problems, with solutions

Try each problem before opening its solution.

1. Uncorrelated but dependent. X ~ N(0, 1), Y = X².

Solution
  • Cov(X, Y) = E X³ − E X · E X² = 0 − 0 = 0, since the odd moments of a symmetric variable vanish.
  • E[Y | X] = X², because Y is a function of X.
  • E[X | Y] = 0. Given Y = y, X is ±√y with equal probability, by symmetry.
  • Y is a function of X, so they are as dependent as can be; correlation sees none of it, because the relationship is not monotone.

2. Eve's law. Assume Y has a finite second moment.

Solution

Write μ(X) = E[Y | X]. Then

  • Var Y = E(Y − EY)² = E(Y − μ(X) + μ(X) − EY)².
  • Expand. The cross term E[(Y − μ(X))(μ(X) − EY)] vanishes: condition on X, and E[Y − μ(X) | X] = 0, by the tower property.
  • The first square is E[E[(Y − μ(X))² | X]] = E Var(Y | X).
  • The second is E(μ(X) − EY)² = Var μ(X), since E μ(X) = EY.

So Var Y = E Var(Y | X) + Var E[Y | X].

3. A bivariate normal. σ_X = 2, σ_Y = 3, ρ = 0.6.

Solution
  • E[Y | X = x] = μ_Y + ρ(σ_Y/σ_X)(x − μ_X) = μ_Y + 0.9(x − μ_X).
  • Var(Y | X = x) = σ_Y²(1 − ρ²) = 9 × 0.64 = 5.76, an SD of 2.4, for every x.
  • The regression of X on Y has slope ρσ_X/σ_Y = 0.4. Drawn on the same (x, y) axes, that line has slope 1/0.4 = 2.5, steeper than the Y-on-X slope of 0.9.

4. A retest. Assume a bivariate normal model, 2 SD above the mean, test–retest correlation 0.7.

Solution

In standard units, E[Z₂ | Z₁ = 2] = ρ · 2 = 1.4. The predicted retest is 1.4 SD above the mean, with conditional SD √(1 − 0.49) = 0.71. That is regression to the mean; nobody's skill changed.

5. Pólya's urn. One red, one blue; draw, return with another of the same colour.

Solution
  • P(first n all red) = (1/2)(2/3)(3/4)⋯(n/(n + 1)) = 1/(n + 1), since the product telescopes.
  • For the uniform: if p ~ U(0, 1), then E pⁿ = ∫₀¹ pⁿ dp = 1/(n + 1).
  • More generally, any particular sequence with k reds and n − k blues has probability k!(n − k)!/(n + 1)!, which is ∫ pᵏ(1 − p)ⁿ⁻ᵏ dp. So the sequence is exchangeable, and it is a mixture of i.i.d. Bernoulli(p) with p uniform.
  • By de Finetti, the fraction of red converges to that p, so the limit is uniform on (0, 1). The moments 1/(n + 1) determine the distribution, since it lives on a bounded interval.

6. U₁ + U₂ + U₃. Find the density of \(U_1 + U_2 + U_3\) for independent uniforms on \((0, 1)\), by convolving the triangle with a uniform.

Solution

The sum of two uniforms has the triangle density t on [0, 1] and 2 − t on [1, 2]. Convolve it with U(0, 1), so that f₃(s) = ∫_{s−1}^{s} f₂(t) dt:

  • On [0, 1]: s²/2.
  • On [1, 2]: (−2s² + 6s − 3)/2, which equals 3/4 at s = 3/2.
  • On [2, 3]: (3 − s)²/2.

The pieces join smoothly, and the curve is already bell-shaped: Part 6's central limit theorem, beginning.

Notes and sources

Where it comes back

Idea Returns in
conditional expectation as projection, the tower property 12, 23, 43, 44
Eve's law 8, 18, 25, 26
the multivariate normal, conditioning, the Schur complement 12, 15, 25, 31, 39
the precision matrix, conditional independence 31, 32, 36
regression to the mean, errors in variables 12, 23, 35, 37
the Jacobian 7, 9, 22
latent variables, mixtures 22, 26, 31
copulas, rank correlation 16, 40
exchangeability, de Finetti 15, 16, 53, 57
the Dirichlet and the multinomial 14, 15, 26

Sources

  • Galton. F. Galton, "Regression towards mediocrity in hereditary stature", J. Anthropological Institute 15 (1886); Natural Inheritance (1889). Data: J. A. Hanley, "'Transmuting' women into men: Galton's family data on human stature", The American Statistician 58 (2004); the HistData package.
  • Correlation and the correlation ratio. K. Pearson, "Regression, heredity, and panmixia" (1896); "On a form of spurious correlation which may arise when indices are used in the measurement of organs" (1897); η² in "On homotyposis in homologous but differentiated organs", Proc. Royal Society 71 (1903).
  • Mixtures. K. Pearson, "Contributions to the mathematical theory of evolution" (1894), on W. F. R. Weldon's Naples crabs.
  • Rank correlations. C. Spearman, "The proof and measurement of association between two things" (1904), which also gives the correction for attenuation; M. Kendall, "A new measure of rank correlation", Biometrika 30 (1938).
  • Distance correlation. G. Székely, M. Rizzo & N. Bakirov, Annals of Statistics 35 (2007).
  • Copulas. A. Sklar (1959); R. Nelsen, An Introduction to Copulas (2nd ed., 2006); H. Joe, Dependence Modeling with Copulas (2014); D. X. Li, "On default correlation: a copula function approach", J. Fixed Income (2000); D. MacKenzie & T. Spears, "'The formula that killed Wall Street'?", Social Studies of Science 44 (2014).
  • Exchangeability. F. Eggenberger & G. Pólya (1923); B. de Finetti (1931); P. Diaconis & D. Freedman, "Finite exchangeable sequences", Annals of Probability 8 (1980).
  • Covariance selection. A. P. Dempster, "Covariance selection", Biometrics 28 (1972).
  • Pairwise independence. S. N. Bernstein, Theory of Probability (in Russian, 1927).
  • The gamma characterization. E. Lukacs, "A characterization of the gamma distribution", Ann. Math. Statist. 26 (1955).
  • Compositional data. J. Aitchison, "The statistical analysis of compositional data", JRSS B 44 (1982).
  • Regression to the mean. A. Tversky & D. Kahneman, "Judgment under uncertainty" (1974); D. Kahneman, Thinking, Fast and Slow (2011), ch. 17.
  • Textbooks.
    • J. Blitzstein & J. Hwang, Introduction to Probability (2nd ed., 2019), chs. 7, 9, 10.
    • G. Casella & R. Berger, Statistical Inference (2nd ed., 2002), ch. 4.
    • T. W. Anderson, An Introduction to Multivariate Statistical Analysis (3rd ed., 2003).
    • S. Stigler, The History of Statistics (1986), Statistics on the Table (1999), The Seven Pillars of Statistical Wisdom (2016).
About this partfrom its README

Part 5 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage I, Bachelor's: Foundations. Parts 2–3 built one random variable at a time and Part 4 built the matrices; this part puts several variables together and asks how they move.

It opens with Francis Galton's table of 928 adult children and their mid-parents (1886). A fitted Gaussian gives nested ellipses with one centre and shape, approximating the count pattern; the children of tall parents are tall, but less so. From that one picture come joint, marginal and conditional distributions, conditional expectation as the best predictor (a projection), Eve's law, the multivariate normal and its conditioning formula, regression to the mean, the three lines through an ellipse, change of variables, latent variables, copulas, exchangeability and de Finetti, measures of dependence, and distributions on the simplex.

Every number on screen is computed in compute.py. Galton's counts are the Museum's (museum.GALTON_*, from HistData; Hanley 2004). Everything else is the World (seed 1662) or a seeded simulation, and is tagged as such.

Built in this part: the Gaussian slicer (GaussianSlicer in explainer/stats/viz.py). It is a bivariate normal density drawn as a turnable wireframe surface over its floor. It cuts the surface at chosen values of x, and each slice, renormalized, is the conditional density of y given x: a normal whose centre moves along the regression line and whose width never changes. It is used for the World's families (mid-parent and son), and it comes back whenever a later part conditions a Gaussian (Parts 15, 25, 26, 39).

Also built: a Pólya urn machine (s13_exchange.py) that draws a ball, returns it with a twin, and plots the running fraction of red for thirty urns at once.

Chapter notes
# Chapter What it does Numbers (computed)
0 Galton's ellipses Galton's 1886 table, counted and smoothed into nested ellipses; "regression towards mediocrity"; the objectives. 928 children, 205 families; r = 0.459; slope 0.646 (Galton's "two-thirds")
1 Joint, marginal, conditional Galton's table in four bands: joint cells, row and column sums, a conditional row; the joint density as a surface; slicing it with the Gaussian slicer; Bayes for densities; the exact joint table of the max and min of two dice. slices at 162/170/178 cm: conditional means 170.4/176.3/182.3, SD 6.06; Cov(max, min) = (35/36)², corr = 35/73
2 Dependence A gallery of uncorrelated-but-dependent shapes (Y = X², the ring, the random-sign pair); covariance as a bilinear form; the variance of an average of equicorrelated variables (diversification); Bernstein's pairwise-but-not-mutually independent coins. r ≈ 0.000, −0.006, −0.007; Var(X̄)/σ² → ρ
3 Conditional expectation The World's log incomes by age: the best constant, the best line, the conditional mean; the proof that E[Y | X] minimizes mean squared error; the tower property; E[Y | X] as an orthogonal projection in L²; the conditional median under absolute loss and conditional quantiles. MSE 0.408 / 0.405 / 0.360; R² 0.007 for the line vs 0.119 for E[Y | X]
4 Eve's law Var Y = E Var(Y | X) + Var E[Y | X], derived; Galton's children; the World's incomes by age; Pearson's correlation ratio η² against r²; a rare switch that makes the conditional variance larger. Galton 6.33 = 4.93 + 1.40 (η² 0.221 vs r² 0.210); log income 0.408 = 0.367 + 0.041
5 The multivariate normal AZ + μ moving a round cloud into an ellipse; the density from the change of variables; affine images, marginals, Cramér–Wold; two normals that are not jointly normal; squared Mahalanobis distances against χ²₃ as a radial diagnostic (insufficient to establish joint normality). sample covariance matches AAᵀ; 4,000 draws on the χ²₃ diagonal
6 Conditioning a Gaussian The conditioning theorem (Schur complement) and its proof by decorrelation; the two-variable case is the regression line; Galton's numbers; the precision matrix of a chain X → Y → Z, whose zero means conditional independence. conditional SD √(1 − r²)·s_y; corr(X, Z) = 0.56 but K₁₃ = 0
7 Regression to the mean The World's tallest tenth of mid-parents and their sons; both directions; Galton's stable variance via Eve's law; skill + luck test–retest; Kahneman's flight instructors. +8.76 → +6.60 cm; 6.33 = 1.33 + 5.00; top tenth about 1.71 → 0.83 SD, bottom about −1.74 → −0.86
8 Three lines through one ellipse Y on X, X on Y and the major axis on Galton's ellipse; what each minimizes; errors in variables and Spearman's attenuation. slopes 0.646, 1/0.326, 2.02; slope 1.01 → 0.49 with reliability ½
9 Change of variables The density of a transformed vector and its Jacobian; the sum of two uniforms by convolution (a triangle); the ratio of two normals (Cauchy); polar coordinates and the Rayleigh distribution. E R = √(π/2) = 1.2533 vs simulated 1.2567
10 Latent variables The World's adult heights as a mixture of men and women; marginalizing a latent class; Pearson's crabs (1894); the posterior class probability (the E step of EM); Simpson's paradox in Part 1's clinic as a latent variable. men 176.0 ± 7.1, women 163.0 ± 6.4, all SD 9.37; clinic: treated 0.624 vs 0.737 overall, but higher within each severity
11 Copulas Sklar's theorem (1959); Gaussian, Clayton and Gumbel copulas with the same Kendall's τ and different tails; sampling from a copula with any margins; Li's Gaussian copula and the crisis. τ = 0.5; joint tail rates (lower/upper) 0.45/0.375, 0.68/0.12, 0.33/0.555; τ 0.507 survives every step
12 Exchangeability The Pólya urn machine; its limiting fractions are uniform; exchangeable sequences; de Finetti's theorem (1931); finite exchangeability without replacement and the Diaconis–Freedman bound. RRB, RBR, BRR each 1/12; urn RRBB: P(RR) = 1/6 vs 1/4, corr −1/3
13 Measuring dependence Pearson, Spearman, Kendall, distance correlation and mutual information on six shapes; rank correlations defined; their invariance under an increasing transform, measured; dCor and MI. Pearson 0.396 → 0.301; Spearman 0.379 and Kendall 0.259 unchanged
14 The simplex The multinomial and its negative covariances; the Dirichlet in four shapes; the Dirichlet as normalized gammas (and independent of their total); Dirichlet–multinomial conjugacy; Pearson's spurious correlation of ratios. sample corr(X/Z, Y/Z) = 0.46 from independent positive lognormal X, Y, Z
15 Outro Recap, payoffs, problems, references, the Transcript, Part 6's question. —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Galton (1886). 928 children of 205 families; the smoothed table's ellipses; "regression towards mediocrity".
  2. Joint, marginal, conditional. Slicing a 3D density and renormalizing the slice.
  3. Dependence. Uncorrelated is not independent; covariance matrices are PSD (Part 4).
  4. Conditional expectation as best predictor. Minimizing mean squared error; the tower property; projection in L² (made rigorous in Part 44).
  5. Eve's law. Var Y = E Var(Y | X) + Var E(Y | X) as Pythagoras; R².
  6. The multivariate normal. An affine image of iid normals; ellipsoids from the spectral theorem; marginals; uncorrelated ⇒ independent only when jointly normal.
  7. Conditioning a Gaussian. The Schur complement (Part 4); linear conditional means: regression is born.
  8. Regression to the mean. The slope ρσ_y/σ_x; Galton recomputed; the sophomore slump; Kahneman's flight instructors.
  9. Three lines through one ellipse. Y on X, X on Y, the major axis.
  10. Change of variables in many dimensions. Jacobians; convolution; the Gaussian in polar coordinates.
  11. Latent variables. Mixture surfaces; marginalizing a class.
  12. Copulas. Sklar (1959); Gaussian vs Clayton vs Gumbel tails; the Gaussian copula and 2008 (Li 2000).
  13. Exchangeability. Pólya's urn → Beta; de Finetti (1931) (proved in Part 44); the finite version.
  14. Measuring dependence. Pearson, Spearman, Kendall, mutual information, distance correlation (Székely, Rizzo & Bakirov 2007), on a gallery of shapes.
  15. The simplex. Multinomial and Dirichlet.
  16. Outro.

Built: the Gaussian slicer; a Pólya urn machine. Data: Galton (Hanley 2004 transcription).

Build the film

python -m videos.stats.stats5.compute        # the part's numbers, into .cache/stats5
python tools/build.py stats5                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats5 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/stats/stats5. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.stats.stats5.compute          # once: every computed item (seconds; cached in .cache/stats5)
python tools/build.py stats5 -q l              # fast 480p preview
python tools/build.py stats5                   # 1080p30 -> renders/stats5.mp4
python tools/qa_scene.py stats5 Condition      # one chapter, silent, with a contact sheet
python tools/lecture_length.py stats5 --floor 50