SStatistics, Built

Stage II · Bachelor's: Methods

Part 12 of 65

Least Squares

Bachelor'sstarts at this level51 min of film13 chaptersprerequisites: Part 4, Part 8, Part 11

How do you fit a line through noise, and how sure are you of its slope?

On 1 January 1801 Piazzi finds Ceres and loses it in the Sun's glare; Gauss, twenty-four, says where it will reappear. The part takes his method apart. Least squares is a projection: the fitted values are the shadow of the data on the plane the predictors span, and everything else (the normal equations, R squared, the t and F tests) is Pythagoras in that picture. Gauss-Markov says the projection is the best linear unbiased guess when the noise is even; when it is not, the slope stays honest but its classical standard error lies, and White's sandwich repairs it. The part ends with what a regression cannot do: tell cause from company, or exempt anyone from regression to the mean.

What you need. Calculus, and the matrix language of Part 4 (projections, rank, quadratic forms).

Hook
Gauss finds Ceres, 1801
Mathematics
projection, Gauss–Markov, t and F, FWL, diagnostics, robust standard errors
Built
statkit.ols; an influence probe

What you will be able to do

Bachelor's

  • Fit a line by least squares, read the coefficient table, and say in words what a slope and its interval claim.
  • Read residual, leverage and QQ plots, and tell an outlier from an influential point.

Master's

  • Derive the normal equations and the hat matrix, and prove Gauss-Markov.
  • Use Frisch-Waugh-Lovell to explain what 'controlling for' computes, and compute omitted-variable bias.

PhD

  • State exactly which assumptions each guarantee needs (unbiasedness, BLUE, exact t and F, consistency of HC standard errors) and give a counterexample when each is dropped.

Practice

  • Report a regression a reader can trust: robust standard errors, a prediction band rather than a confidence band where one is meant, and no causal verb the design cannot support.

Contents

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

  1. 0Ceres, lost and foundBachelor's2 min
  2. 1The principleBachelor's5 min
  3. 2GeometryBachelor's5 min
  4. 3Gauss-MarkovPhD3 min
  5. 4Normal theoryMaster's5 min
  6. 5Controlling forMaster's4 min
  7. 6Interpreting coefficientsBachelor's5 min
  8. 7BandsPractice3 min
  9. 8CollinearityPractice3 min
  10. 9DiagnosticsBachelor's5 min
  11. 10Uneven noiseMaster's4 min
  12. 11The regression fallacyBachelor's4 min
  13. 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.

Ceres, lost and foundBachelor's2 min

On the first night of the nineteenth century, the astronomer Giuseppe Piazzi, in Palermo, saw a faint point of light that moved against the stars between the orbits of Mars and Jupiter. It was Ceres, the first asteroid ever found. He followed it for six weeks, across only a small arc of its path, until it disappeared into the glare of the Sun. Where would it reappear? Astronomers made predictions, and they disagreed. A twenty-four-year-old mathematician in Brunswick, Carl Friedrich Gauss, took Piazzi's few, noisy positions and fitted an orbit to them. On the last night of 1801, Franz von Zach found Ceres within half a degree of where Gauss said it would be. Gauss became famous for his orbit calculation. In 1809 he published a systematic treatment of least squares for astronomical observations; the exact role of least squares in the 1801 recovery is historically disputed.

A constructed orbital illustration, not a reconstruction of Piazzi's records or Gauss's fit. Piazzi's observations were a handful of noisy points on a short arc of a long orbit. Many orbits pass near those points. Least squares would choose an orbit minimizing total squared residuals under a specified observation model. The curve shown here is constructed to explain extrapolation. Then he followed it around the Sun, to where Ceres would be months later. A short arc constrains a long orbit only if you use every observation as well as possible, and squaring the errors turned out to be the way.

And then came one of the great priority disputes in science. In 1805 Adrien-Marie Legendre, in an appendix to a book on comet orbits, published the method, named it, the method of least squares, and showed how to use it. In 1809 Gauss published his own account, derived it from the normal law of errors, which is how the normal curve got its other name, the Gaussian, and remarked that he had used it since 1795. Legendre was furious. Historians, including Stephen Stigler, think Gauss's claim is plausible, but it was Legendre's clear account that the world learned from.

1The principleBachelor's5 min

Here's the principle in one picture. Thirty of the World's families: across, the parents' average height, and up, the adult child's, using sex-standardized parental heights averaged on the horizontal axis and the child's standardized height vertically. The parental average itself need not have variance one. Draw any line. Each point misses it by a vertical distance, the residual. Draw each residual as a square: its area is the residual squared. Now turn the line. The squares grow and shrink, and their total area changes. Least squares chooses the line with the smallest total area. Here, a slope of point five three: children of tall parents are taller than average, but only about half as much, Galton's regression toward the mean.

The algebra. The total squared miss is a quadratic function of the intercept and slope: a bowl. At the bottom of the bowl both derivatives vanish. The first says the residuals add up to zero, so the line passes through the point of averages. The second says the residuals are uncorrelated with x: whatever is left over has no linear relation to the predictor. With any number of predictors, written as a matrix X with a column of ones, these are the normal equations: X transpose X beta-hat equals X transpose y. Legendre wrote them down in 1805.

For one predictor, the solution is Part 5's regression slope: the covariance over the variance of x, which is the correlation times the ratio of standard deviations. The intercept puts the line through the point of averages. In general, beta-hat is X transpose X inverse, X transpose y, though, as Part 4 insisted, you compute it with a QR decomposition, never by forming the inverse. statkit's ordinary least squares module does exactly that, and reference outputs are checked against the statsmodels library.

Why squares, and not absolute values, or the largest miss? There are four good answers. Convenience: squares give a smooth bowl, linear equations and, with full column rank, a unique answer, which was Legendre's argument. Probability: if errors are independent normal with common variance and zero conditional mean, least squares is maximum likelihood, which was Gauss's argument in 1809, and Part 9's. Optimality without normality: Gauss proved in 1821 that it's the best linear unbiased estimator, chapter three. And geometry: it finds the closest point in a plane in ordinary distance, chapter two. The price is that squaring gives large misses great weight, so a single outlier pulls the line hard.

Gauss's 1809 argument ran in a surprising direction. He postulated what every astronomer already did: when a quantity is measured several times, the average is the most probable value. If errors follow some law phi, the most probable value solves a likelihood equation, and Gauss demanded that its solution be the average, for every possible set of measurements. That forces the log-derivative of phi to be linear, so phi must be e to the minus k u squared over two: the normal curve. And under that law, the most probable fit of any linear model is least squares. The normal distribution entered the world as a justification for least squares, which is why it carries Gauss's name. Laplace's central limit theorem, a year later, gave the deeper reason it fits.

The alternative is older than least squares. In 1757 Roger Boscovich, studying the shape of the Earth, used an early constrained absolute-error fit, and Laplace developed the idea. Here's Anscombe's third data set: ten nearly collinear points, and one outlier. Least squares tilts toward the outlier: slope point five. The least absolute deviations line ignores it and follows the other ten closely: slope point three four five. It's more robust, but harder to compute and to do theory with, which is why least squares won the nineteenth century. Robust regression returns in Part 30.

It helps to see the choice as a choice of loss. Least squares charges each residual its square. Fit just a constant with this loss and you get the mean. Least absolute deviations charges the absolute value, and a constant fit gives the median. Peter Huber's 1964 loss is quadratic near zero and linear far out, a compromise between the two. The shape of the loss far from zero is what decides how much one wild point can pull: under squares, a miss twice as big costs four times as much. Part 30 builds regression on the slower-growing losses.

Numbers: 30 families: b̂ = 0.53; Anscombe 3: LS slope 0.500 vs LAD 0.345

2GeometryBachelor's5 min

Now the picture that explains everything, from Part 4. Take a dataset of just three observations. The three responses are one point, one vector, in three-dimensional space. Every possible fitted line, a times the ones vector plus b times the x vector, is a point in the plane spanned by those two vectors: the column space of X. Least squares picks the point of that plane closest to y, in ordinary distance, because the sum of squared residuals is the squared distance. The closest point is the foot of the perpendicular: the residual vector stands at right angles to the plane. That's what the normal equations say: X transpose times the residual is zero, the residual is orthogonal to every column. Normal, in normal equations, means perpendicular. Turn the picture to see the right angle.

You can check the right angle numerically on the thirty families. The residuals add up to zero, to fifteen decimal places: they're perpendicular to the ones vector. Their products with x add up to zero: perpendicular to x. And so they're perpendicular to every fitted value, which is a combination of the two. That's why a plot of residuals against fitted values can never show a linear trend from least squares itself. If yours does, something is wrong with the computation, not with the world.

In matrix form, the fitted values are a matrix H, the hat matrix, times y: it puts the hat on y. H is symmetric and idempotent, a projection, the object Part 4 opened with, so its eigenvalues are zero and one. One minus H makes the residuals, and it's also a projection, onto the space perpendicular to the columns. For full column rank X, the trace of H is the number of columns, p, including the intercept, so the residuals live in n minus p dimensions. That's why the variance estimate divides the residual sum of squares by n minus p, Part 8's n minus one, generalized.

How does a computer actually find the projection? It orthonormalizes the columns of X, Part 4's Gram–Schmidt, writing X as Q times R, where Q has orthonormal columns spanning the same plane and R is upper triangular. Then the normal equations become R beta-hat equals Q transpose y, solved by back-substitution, with no inverse anywhere. The hat matrix is just Q Q transpose, and each point's leverage is the squared length of its row of Q, for free. Forming X transpose X squares the condition number, so if X is nearly collinear you lose twice as many digits. That's why statkit, like many numerical routines, uses QR; SVD is another stable approach.

And because there's a right angle, there's Pythagoras. Centre everything at the mean. The squared length of the data's deviation from its mean equals the squared length of the fitted values' deviation plus the squared length of the residual. In words: the total sum of squares is the explained sum of squares plus the residual sum of squares. R squared is the explained share, the squared cosine of the angle between the data and the fit. For our thirty families, point one eight: the squared correlation. Parents' heights explain under a fifth of the variation in these children's heights. Chapter four turns this Pythagoras into the F-test.

With many predictors, nothing in the picture changes except the dimension. The possible fits form a p-dimensional plane inside n-dimensional space, and the fitted values are the foot of the perpendicular from y. Each coefficient is a Frisch–Waugh–Lovell slope: the partial linear association after projecting out the others, as chapter five shows. The residuals live in the remaining n minus p dimensions, so as p approaches n there's little left over to estimate the noise. And when p exceeds n, a full-row-rank design spans the whole space and can interpolate the data. Prediction then needs further structure or regularization. That's the starting point of Part 32.

Numbers: R² = 0.181 = r²; residual sums ≈ 10⁻¹⁵

3Gauss-MarkovPhD3 min

Gauss's second justification, from 1821, needs no normal distribution at all. For fixed full-column-rank X, suppose the errors have mean zero, are uncorrelated, and all have the same variance. Then among all estimators that are linear in y and unbiased, least squares has the smallest variance, for every coefficient and every linear combination of coefficients. Andrey Markov restated it in 1912, and it has carried both their names since the 1930s. Least squares is BLUE: the best linear unbiased estimator. And the conditions are mild: means, variances, and no correlation between the errors.

The proof is four lines of Part 4's matrix algebra. Write any linear estimator as C times y, and write C as the least squares matrix plus some difference D. Unbiasedness for every beta forces D times X to be zero. Its variance is sigma squared C C transpose, and when you multiply out, the cross terms vanish because D X is zero. So the rival's variance exceeds least squares' by sigma squared D D transpose, which is positive semidefinite. Every linear combination of the rival's coefficients has at least as much variance. Least squares is never beaten.

Let's watch a rival lose. Twenty points, a true slope of a half, and a lazy rival: draw the line through the first and last points. It's linear in y, and it's unbiased. Over twenty thousand samples both centre on a half. But the end-point slope has a standard deviation of point three four, and least squares point two one, exactly as theory says. The rival wastes eighteen of the twenty points.

What if the variances are unequal but known? Divide each row of the data by its error standard deviation. The rescaled errors all have variance one, so Gauss–Markov applies to the rescaled problem. That's weighted least squares, the simplest case of Alexander Aitken's generalized least squares: weight each observation by its inverse variance. In a simulation where the noise grows with x, both estimators are unbiased, but weighting cuts the slope's standard deviation by about a quarter. Noisy points should count for less.

It matters what the theorem doesn't say. It compares only linear estimators. With heavy-tailed errors a nonlinear estimator, like least absolute deviations, can be far better. It compares only unbiased ones. Biased estimators like ridge regression can have smaller mean squared error, Parts 25 and 32. It assumes equal variances and no correlation. When the covariance is known and positive definite, Alexander Aitken's generalized least squares, from 1935, is the best linear unbiased estimator instead. It gives the classical covariance formula under its assumptions; exact distributional tests need more, as the next chapter and chapter ten show.

Numbers: slope SD 0.208 (OLS) vs 0.341 (end points); WLS 0.165 vs OLS 0.214

4Normal theoryMaster's5 min

For fixed full-column-rank X and independent mean-zero normal errors with common variance, exact inference follows. Beta-hat is linear in the normal y, so it's normal, centred at beta, with covariance sigma squared X transpose X inverse. The residual sum of squares over sigma squared is chi-squared with n minus p degrees of freedom, independent of beta-hat: Part 8's Cochran theorem, with the residual projection. So s squared, the residual sum of squares over n minus p, estimates sigma squared without bias. And each coefficient, standardized by its estimated standard error, is Student's t with n minus p degrees of freedom. This is the classical normal-model coefficient table; robust and generalized models use other approximations.

Here's the coefficient table that every statistics package prints, for the dummy-variable model of the World's four hundred families: each estimate, its standard error, its t statistic on three hundred and ninety-seven degrees of freedom, and its interval. Read each t as a test of one coefficient given all the others in the model, in the sense of Frisch–Waugh–Lovell. And not every row is a sensible question: the intercept's test asks about children of parents zero centimetres tall.

On the World's finite synthetic families, this is an empirical check of the normal approximation: the true slope, over all fifty thousand families, is point seven oh three. Take ten thousand samples of thirty, standardize each estimated slope by its own standard error, and the histogram follows Student's t with twenty-eight degrees of freedom. The ninety-five percent intervals cover ninety-five point three percent of the time. Kept.

How much does the normality assumption matter? The slope's error is a weighted average of the errors. With finite variance and no observation dominating, a weighted central limit theorem can apply. With strongly skewed exponential errors, the ninety-five percent interval for the slope covers ninety-five percent with ten observations, and with thirty, and with a hundred. Normality matters for very small samples and, as Part 11 showed, for prediction intervals, which concern a single error. These results are specific to this well-spread design; skewness, extreme leverage or infinite moments can defeat a small-sample approximation.

Pythagoras also gives the F-test, for whether a group of variables matters. Fit a small model and a full one containing it. The small model's residual sum of squares is the full model's plus the squared distance between the two fits: another right angle. The F statistic divides the extra fit per extra parameter by the leftover noise per degree of freedom, and under the null that the extra coefficients are zero it has an F distribution, Snedecor's ratio from Part 8. A hundred families: child's height on father's, then adding mother's. F is twenty-three, p about six in a million. R squared rises from point zero three to point two one. With a single added variable, F is exactly the square of that variable's t statistic.

The nested sums of squares are usually laid out in a table, the analysis of variance, Fisher's invention. The total sum of squares of the hundred children's heights splits into the part explained by fathers, the extra part explained by mothers given fathers, and the residual. Each split is one of chapter two's right angles. Divide each by its degrees of freedom to get mean squares, and each F is a mean square over the residual mean square: twenty-three for the mother, as before. One subtlety: these sequential sums of squares depend on the order in which variables enter, unless the columns are orthogonal. Making them orthogonal on purpose is exactly what a designed experiment does, in Part 13.

R squared is the most quoted and most misread number in regression. It isn't a test: adding any variable, even pure noise, can only raise it. The adjusted version penalizes that. It isn't the share of the outcome caused by the predictors. It isn't comparable across samples, because it depends on how spread out the x's you happened to sample were. And it isn't a check that the model is right: chapter nine shows four datasets with identical R squared and wildly different shapes.

Numbers: true slope 0.703; coverage 95.3%; adding mother: F = 22.8, p = 6.5 × 10⁻⁶; R² 0.029 → 0.214; skewed errors: 95% coverage at n = 10, 30, 100

5Controlling forMaster's4 min

What does a coefficient mean when there are several predictors? The Frisch–Waugh–Lovell theorem, from Ragnar Frisch and Frederick Waugh in 1933, the year Econometrica began publication, and Michael Lovell in 1963, answers exactly. The coefficient on x1 in a multiple regression equals the slope you get by first removing from y the linear projection on x2, removing from x1 the linear projection on x2, and regressing the first leftover on the second. That's what controlling for x2 means: compare y and x1 after taking out whatever x2 explains in each. In the geometry of chapter two, project everything onto the space perpendicular to x2, and fit there.

Let's check it on the World. Two hundred families. Regress the child's height on both parents' heights: the father's coefficient is point four three five four. Now do it the long way. Remove from the father's height whatever the mother's predicts, and the same from the child's, and plot the two leftovers. The slope through this cloud is point four three five four again, to every digit. Regressing on the father alone gives point four eight three: larger, because tall fathers tend to have tall partners, and without controlling for the mother, the father's coefficient picks up part of the association with her height. This decomposition is not by itself a causal attribution.

That's a special case of the most important formula in applied regression. Suppose the truth involves x1 and x2, but x2 is left out. Write how the omitted variable tracks the included one, with slope delta. Then the population short-regression slope differs from beta-one by gamma times delta: the omitted variable's effect, times its association with the included one. Both must be non-zero for bias, and the sign of the bias is the product of their signs.

The economists' classic case. In a simulated population, each year of schooling raises the log wage by point zero eight. Regress log wages on schooling and ability, and you recover point zero eight. But ability is rarely measured. Leave it out, and the coefficient on schooling becomes point one one: a thirty-eight percent overstatement. The formula predicts it exactly: ability's effect, point one, times its association with schooling, point three, added to the truth. Able people both earn more and stay in school longer, and the short regression credits school with both.

Part 5's Simpson's paradox is the same formula. Regress recovery on treatment, across all twenty thousand of the World's clinic patients: treatment seems to lower the chance of recovery by eleven points. Control for severity, and the treatment coefficient becomes positive: plus eight points, while severe illness lowers recovery by forty. The bias is gamma times delta: severity's effect times how much more often the treated are severe, about minus nineteen points. And the short coefficient is exactly the long one plus that bias. The paradox was omitted-variable bias all along.

So a regression coefficient answers a question about comparison, not intervention. It says: among people with the same values of the other variables, those with one more unit of x1 have, on average, beta-one-hat more y. A causal interpretation additionally requires a valid adjustment set, conditional exchangeability, overlap, consistency, and an appropriate functional form. Controlling for a collider or a consequence of treatment can introduce bias. And no amount of data can prove that nothing has been left out. That's why the next part is about designing the data instead, and why Parts 35 to 37 exist.

Numbers: FWL 0.4354 = 0.4354 (father alone 0.483); OVB: 0.110 vs truth 0.080, formula 0.11; clinic −0.112 vs +0.078

6Interpreting coefficientsBachelor's5 min

Coefficients carry units, and their meaning depends on what's in the model. Four hundred of the World's families, now in centimetres: sons in blue, daughters in red. One line through everyone explains only ten percent of the variation, because it ignores the biggest fact about height. Add a dummy variable, one for a son and zero for a daughter. Its coefficient, twelve point eight centimetres, is the difference between sons and daughters with the same parents' height, and R squared jumps to sixty percent. Geometrically, a dummy gives each group its own intercept: two parallel lines.

A variable with many categories needs one dummy fewer than it has levels. Three hundred of the World's men, and their region, one of ten: nine dummies plus an intercept. All ten dummies plus an intercept would be exactly collinear, since the dummies add up to the ones column. So one region is left out as the reference, and the intercept is its mean, a hundred and seventy-six centimetres. Every other coefficient is a difference from the reference. To ask whether region matters at all, test all nine together with one F-test: F of point nine, p of point five two. No evidence the regions differ, which is how the World was built. That test is the one-way analysis of variance of Part 13.

To let the slopes differ too, add an interaction: the product of the dummy and mid-parent height. Then the daughters' slope is beta-one, and the sons' slope is beta-one plus beta-three. Here the interaction is small and its p-value is point four six: no evidence that sons and daughters regress differently, which is how the World was built. Beware one trap: with an interaction in the model, the son coefficient means the difference at a mid-parent height of zero centimetres, a meaningless extrapolation. Centring the predictor fixes that.

A slope always carries units: units of y per unit of x. Measure x in centimetres instead of metres, and the coefficient shrinks a hundredfold, while its t statistic, its p-value and R squared don't change at all. A coefficient's size tells you nothing until you know its units. Standardized coefficients, per standard deviation of x in standard deviations of y, remove the units, but do not make predictors comparable in causal importance. But they depend on how spread out x happened to be in this sample, the same weakness as R squared.

Logarithms change the meaning of a coefficient, usefully. With log y on the left, a slope of point zero five means each unit of x is associated with about five percent higher conditional geometric mean y: effects become proportional, which is how incomes and prices behave. With log x on the right, each one percent increase in x adds approximately beta over a hundred to y: diminishing returns. With logs on both sides, the slope is an elasticity: the percentage change in y per percentage change in x, a number with no units at all.

Linear regression can fit curves. Six hundred of the World's adults: log income against age. A straight line explains one percent of the variation; it can't follow a career. A quadratic, with age and age squared as two columns, rises and falls: twelve percent. A linear spline, a broken line with knots at thirty, forty-five, sixty and sixty-seven, built from columns like age minus thirty where positive, does better still and catches the drop at retirement. The dashed curve is the World's mean log income in three-year age bins. All three are still linear regression: linear in the coefficients, not in age. Part 29 does this with smoothing.

A warning about curves. Ask the fitted quadratic about ages it never saw. At a hundred and twenty, an exponentiated fitted log income of about three thousand two hundred, a geometric-scale prediction rather than the arithmetic mean. At a hundred and fifty, a hundred and sixty. The parabola has kept falling, as parabolas do. A fitted curve is checked only where there are data; beyond them it's pure assumption. Mark Twain made the point in 1883: the lower Mississippi had shortened by two hundred and forty-two miles in a hundred and seventy-six years, so a million years earlier it must have stuck out over the Gulf of Mexico like a fishing rod.

Numbers: son dummy +12.8 cm (R² 0.10 → 0.60); interaction 0.089 ± 0.120; regions F = 0.90, p = 0.52; log-income R² 0.013 / 0.123 / 0.153

7BandsPractice3 min

Under the full-rank linear model with independent normal errors of common variance, how uncertain is the fitted line? The variance of the fitted value at a point x-nought is smallest at the mean of the x's and grows quadratically as x-nought moves away, because a small error in the slope matters more far from the centre. That gives a pointwise confidence interval for the mean of y at x-nought. For a new observation, add the noise of one more point: Part 11's prediction interval, now along a line. And for the whole line at once, Holbrook Working and Harold Hotelling replaced the t multiplier by the square root of p times an F quantile in 1929: Part 11's Scheffé idea, for regression.

Here are all three on the thirty families. The fitted line, and its pointwise ninety-five percent confidence band: a bow tie, narrowest at the average parent and widening toward the ends. The Working–Hotelling band, which covers the whole true line at once, is a little wider. And the prediction band, for a new family's child, is much wider: it has to contain the scatter of individuals, not just the uncertainty about the average. The new-observation prediction guarantee does not assert simultaneous coverage, or a fixed fraction of these training points. With more data, the confidence band shrinks onto the line; the prediction band never shrinks below the noise.

A concrete prediction. A couple whose average height is a hundred and seventy-five centimetres are expecting a son. The dummy-variable model predicts a hundred and seventy-nine centimetres. The ninety-five percent confidence interval for the average height of all such sons is barely two centimetres wide: four hundred families pin it down well. But the prediction interval for this particular son runs from about a hundred and sixty-eight to a hundred and ninety. Parents' heights tell you a lot about sons on average, and much less about any one of them.

So which band answers your question? How tall are the children of tall parents, on average? The confidence band. How tall will this particular child be? The prediction band. Where does the whole regression line lie? Working–Hotelling. Plotting software usually draws the first by default, while the question people are asking is usually the second.

Numbers: t = 2.05 vs √(2F) = 2.58; one son: 178.9, mean CI [177.9, 180.0], PI [167.8, 190.1]

8CollinearityPractice3 min

Frisch–Waugh–Lovell explains collinearity directly. A coefficient is estimated from the part of its predictor that the other predictors can't explain. Its variance is the simple-regression variance divided by one minus R-j squared, where R-j squared measures how well the other predictors predict this one. That factor is the variance inflation factor. If two predictors correlate point nine five, it's about ten, and both standard errors are about three times as large as they would be if the predictors were unrelated.

Here's what it looks like. Two predictors, both with true coefficient one, fifty observations. When the predictors are unrelated, the ninety-five percent confidence region for the two coefficients together is nearly a circle, and each standard error is about a tenth. When they correlate point nine five, the region becomes a long thin ellipse, lying along a diagonal. The individual standard errors triple, and here the estimates split the effect unevenly, one point two and point six. But look along the diagonal: the sum of the two coefficients is estimated as precisely as before, even a little more precisely. The data can't tell the two predictors apart, but they estimate the sum more precisely in this model.

Collinearity also has a numerical face. The condition number of X, its largest singular value over its smallest, measures how close the columns are to being linearly dependent. For two standardized predictors with correlation rho, the condition number of X transpose X for the centred two-predictor Gram block is one plus absolute rho over one minus absolute rho: thirty-nine at point nine five, twenty thousand at point nine nine nine nine. Roughly, you lose the log, base ten, of the condition number in digits of accuracy. The statistical cost, the variance inflation factor, and the numerical cost grow together, which is no coincidence: both measure how little the data say about the separate directions.

Collinearity is a shortage of information, not an error in the method. The estimates are still unbiased, and collinearity alone need not ruin predictions, as long as the predictors keep moving together. What you can't learn is the separate effect of things that never varied separately in your data. The cures: more data; better data, collected so that the predictors do vary separately, which is design, Part 13; or questions about combinations rather than separate effects. Or accept a little bias to reduce the variance, Arthur Hoerl and Robert Kennard's ridge regression, Part 32.

Numbers: VIF 1.0 vs 7.2; SE 0.12 vs 0.34; SE of the sum 0.15 vs 0.13

9DiagnosticsBachelor's5 min

In 1973 Francis Anscombe published four small datasets to make a point. All four have the same means, the same variances, the same correlation, and the same fitted line: three plus a half x, with R squared of point six seven. The first is an ordinary noisy line. The second is a smooth curve, for which a straight line is the wrong model. The third is nearly a line with one outlier. The fourth has no relationship at all, except for a single point far to the right that decides the entire slope. Identical numbers, four different stories. Diagnostics are how you tell them apart without having to look at every plot.

Two quantities do most of the work. The leverage of a point is its diagonal entry in the hat matrix, and for one predictor it measures how far its x is from the others. Leverages add up to p, so the average is p over n. A residual's variance is sigma squared times one minus the leverage: high-leverage points drag the line toward themselves, so their residuals look deceptively small. Dividing by that standard deviation gives the studentized residuals, which are comparable across points.

Here's the instrument built for this part, the influence probe. Twenty points and their fitted line. One point, in orange, can be dragged, and the line refits as it moves. The readout shows the slope, the point's leverage, and its Cook's distance, which measures how much the whole fit depends on it. Move it straight up, in the middle of the data. It gets a big residual, but the slope barely changes: at the centre, a point has little leverage. Now bring it back and slide it far to the right, along the line. Its leverage soars, but it agrees with the others, so nothing changes. Finally, far to the right and far off the line. Now the slope swings, and Cook's distance explodes. Influence needs both: leverage, from an unusual x, and a residual, from an unusual y.

Dennis Cook's distance, from 1977, summarizes influence in one number: how far all the fitted values move when a point is deleted, scaled by the noise. It's a residual squared times a function of leverage, so it needs both. In Anscombe's third dataset, the outlier has a Cook's distance of one point four. A common rule of thumb says anything above one deserves a hard look. In the fourth, the lone point on the right has leverage exactly one: the slope is determined by that single point, the fit passes through it, and its residual is zero. Deleting it leaves no slope at all.

What should you do with an influential point? First, check it. Is it a typing error, a member of a different population, a broken instrument? Then report the fit with and without it, and if the conclusions change, say so. Never delete points simply because they're inconvenient: that's one of Part 10's forking paths. And if outliers are part of the process, use a method designed for them, the robust regression of Part 30.

The single most useful diagnostic is a plot. Plot the residuals against the fitted values. For Anscombe's second dataset, the residuals form an arch. A curve means the model is missing a term: here, a square. A funnel means the noise grows with the fitted value, the subject of the next chapter. A few far points mean outliers or influence. A shapeless cloud is what you hope to see: whatever's left is noise.

One more plot belongs in every regression. Part 1's normal quantile plot, applied to the studentized residuals. Under IID homoskedastic normal errors, these dependent internally studentized residuals should lie approximately near the diagonal; this is a diagnostic, not a proof. Here they don't: both tails bend away, far heavier than normal. These are the funnel-shaped data of the next chapter, where the noisiest points are also the most influential. The plot can't tell you why the tails are heavy, but it tells you to find out.

Numbers: Anscombe: all 3.00 + 0.500x, R² 0.67; max Cook's D 1.39 (set 3); leverage 1 (set 4)

10Uneven noiseMaster's4 min

Gauss–Markov and the classical standard errors assume every observation has the same error variance. Real data often don't. Here are four hundred of the World's working-age adults: income against age. The spread of incomes grows with their level, a funnel. Unequal variances are called heteroskedasticity. In a correctly specified exogenous linear model, least squares remains unbiased; here it estimates a linear summary of a curved age relationship, about seven hundred a year. Here the classical standard error and a robust one, which we'll build in a moment, happen to agree. But they don't always.

When do they disagree? When the noise is biggest exactly where x is extreme. Here's a simulated case: a skewed x, and errors whose spread is proportional to x. The extreme x's have the most leverage on the slope, and they're also the noisiest points. The classical formula pretends their noise is average, and reports a standard error of point zero nine five. The robust standard error is point two seven: nearly three times larger. The exact conditional standard error in this simulated model is point two nine nine; HC3 is still an estimate. Intervals built on the classical one would be far too narrow.

The exact variance of beta-hat, for any error covariance, is a sandwich: X transpose X inverse on both sides, and X transpose Sigma X in the middle. If errors are uncorrelated with equal variance, the middle collapses and you get the classical formula. Halbert White's insight, in 1980, published in what became one of the most cited papers in economics: you can't estimate each error variance, but you don't need to. Estimate the middle of the sandwich with the squared residuals, and the result is consistent under independent sampling, suitable finite moments and a non-dominating design, allowing unequal variances. It does not handle arbitrary error correlation. James MacKinnon and White's HC3 version divides each squared residual by one minus its leverage, squared, because high-leverage points have deceptively small residuals, as chapter nine showed. It often improves small-sample behavior, but has no universal finite-sample coverage guarantee.

Incomes are a natural case for logs. On the log scale, the classical and robust standard errors for the age slope agree closely. Taking logs turns noise that grows in proportion to the level into noise of roughly constant size. And the coefficient changes meaning, to a percentage change per year of age. Choose the scale for the question first, and fix the standard errors second.

The Coverage Board settles it, with the ninety-five percent interval for the slope. On the World's families, where the noise is even, classical and HC3 intervals both keep the promise: ninety-five point three and ninety-five point two. In the funnel-shaped simulation with fifty points, the classical interval covers only sixty percent. HC3 covers ninety. Better, but still broken. With five hundred points, the classical interval gets worse, fifty-five percent, because its error doesn't shrink with more data: it's the wrong formula. HC3 climbs to ninety-four. Robust standard errors are large-sample tools, and in small samples with extreme leverage even they fall short.

In practice: plot the residuals against the fitted values, where a funnel is easy to see. Report HC3 standard errors by default; under independent sampling they are useful against heteroskedasticity, though finite-sample efficiency and calibration can differ from classical inference. A transformation, like taking logs of incomes, often removes the funnel, and changes the question to one about proportional effects. If you know how the variance changes, weight each observation by the inverse of its variance: weighted least squares is the best linear unbiased estimator again. And when errors are correlated, in clusters or over time, different sandwiches are needed, in Parts 17 and 23.

Numbers: funnel data: classical SE 0.095 vs HC3 0.267; the board rows above

11The regression fallacyBachelor's4 min

And here's where the word regression came from. Galton's own table of nine hundred and twenty-eight children and their parents, from 1886, each dot sized by its count. The least squares slope is point six five. Galton estimated about two thirds, drawing ellipses by hand. If children were exactly like their parents, the points would follow the dashed diagonal. They follow a flatter line instead: regression toward the mean. Galton called it regression towards mediocrity, and the name of the phenomenon became the name of the method.

Part 5 met regression to the mean. With regression in hand, here's how it fools people. In the World, fathers more than one and a half standard deviations above average have children only point seven seven above. Short fathers' children are closer to average too. It looks as if the population is converging on mediocrity, as Galton first feared. But read the data backwards: the fathers of very tall children are only point seven six above average. Regression goes both ways, which does not establish a causal shrinking of the population. Causal relationships can still underlie the association. And the spread is approximately one in each generation's own standardized units: nothing is shrinking. Regression to the mean is what imperfect correlation looks like, in either direction.

The fallacy has a costly form. Give ten thousand students a noisy test. Take the worst ten percent, give them a remedy that does absolutely nothing, and test them again. Their average rises by one point three raw score units, about point nine two standard deviations of a test score. It looks like a spectacular success. But part of why they scored so badly the first time was bad luck on the day, and luck doesn't repeat. A direct way to handle it is a control group, chosen the same way and randomly denied the remedy. Then both groups regress equally in expectation, and the difference is the effect. Daniel Kahneman told of flight instructors convinced that praise after a great landing made pilots worse and criticism after a bad one made them better: regression to the mean, both times.

In medicine the stakes are concrete. Patients often enrol in a trial because a measurement, say blood pressure, is high on the day they're tested. A month later, even untreated, it's lower on average, partly because the high reading was partly chance. A before-and-after comparison credits the drug with all of that fall. The placebo arm of a randomized trial regresses by the same amount in expectation, so comparing arms subtracts it out. Martin Bland and Douglas Altman's short note on this, in the British Medical Journal in 1994, is still worth reading.

The most famous casualty was Horace Secrist, a professor of statistics, whose 1933 book, The Triumph of Mediocrity in Business, spent four hundred and sixty-eight pages showing that the most and least profitable firms drift toward the average over time, and concluded that competition was levelling business. Harold Hotelling's review pointed out that the result was a statistical necessity, and proved nothing. Sorting firms by later profits and looking backward would show them diverging. The sophomore slump in sport, the fading of last year's star fund manager: the same arithmetic, mistaken for a cause. Whenever a group is selected for being extreme, expect it to look less extreme next time, and ask for a comparison group before believing in a cause.

Numbers: Galton 1886: slope 0.646; World: fathers +1.94σ → children +0.77σ; children +1.94σ → fathers +0.76σ; a useless remedy "gains" 1.30 raw units = 0.92 test SD

Recap, problems, and the road aheadAll tracks3 min

Part twelve in thirteen lines. Gauss's recovery of Ceres motivates orbit fitting; Legendre published least squares first, followed by Gauss's 1809 account. The method minimizes the squared misses; the normal equations solve it, and for one predictor the slope is the correlation rescaled. Squares are convenient, are maximum likelihood for normal errors, and are optimal among linear unbiased estimators, though Boscovich's absolute errors resist outliers. Geometrically the fit is a projection, with Pythagoras giving R squared and the F-test. Gauss–Markov makes it best linear unbiased, and normal errors give exact t and F. Frisch–Waugh–Lovell says what controlling for a variable means, and leaving one out biases the rest by gamma times delta. Dummies, interactions, logs and splines change what coefficients mean. Confidence bands are for the line, prediction bands for the next point. Collinearity inflates variances; leverage and Cook's distance find influential points; independent uneven noise suggests robust covariance estimates such as HC3. And regression to the mean is not a cause.

Where it comes back. Least squares is the trunk from which much of statistics branches: the analysis of variance in the next part; generalized linear models in Parts 14 and 24; the linear model in full depth in Part 23; mixed models, smoothing, robust regression, ridge and the lasso; and, in Parts 35 to 37, the regressions that try to identify causes.

Six problems, with full solutions in the README. The simple-regression formulas; the hat matrix; Frisch–Waugh–Lovell, proved; an omitted variable; standard errors for a fitted mean and a prediction; and the variance inflation factor. Each one takes a page or less, and each uses an idea from this part that later parts take for granted. Pause here if you want to try them.

The books and papers this part follows: Weisberg's Applied Linear Regression, Gelman, Hill and Vehtari's Regression and Other Stories, Seber and Lee, Fox, and Stigler's history, with the papers from Boscovich to White.

Twelve parts of sixty-five, the second of Stage II. We can fit a relationship, measure our uncertainty about it, and check whether it's being fooled. But a regression on observed data can't tell a cause from a coincidence. In 1919 the young Fisher arrived at the Rothamsted experimental station and found seventy years of carefully kept wheat records whose treatment and weather comparisons posed difficult inferential problems. His solution was to design the data. Part 13: experiments by design.

Where it goes next. The projection returns as ANOVA (Part 13), as the working step of every GLM (Parts 14, 24), and in full matrix generality in Part 23; 'controlling for' becomes a causal question in Parts 35-37.

Key results

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

Normal equations\(\displaystyle X^\top X\hat\beta = X^\top y,\qquad\allowbreak \hat y = Hy,\quad\allowbreak H = X(X^\top X)^{-1}X^\top\)
Gauss-Markov\(\displaystyle \operatorname{Var}(\tilde\beta)-\operatorname{Var}(\hat\beta)\succeq 0\quad\allowbreak \text{for }\allowbreak \text{every }\allowbreak \text{linear }\allowbreak \text{unbiased }\tilde\beta\)
Frisch-Waugh-Lovell\(\displaystyle \hat\beta_1=\frac{\tilde x_1^\top \tilde y}{\tilde x_1^\top \tilde x_1},\qquad\allowbreak \tilde x_1=(I-H_2)x_1,\ \tilde y=(I-H_2)y\)
White's sandwich\(\displaystyle \widehat{\operatorname{Var}}(\hat\beta)=(X^\top X)^{-1}\Bigl(\sum_i \hat e_i^2\,x_i x_i^\top\Bigr)(X^\top X)^{-1}\)

Try it

Lab 12 · Least squares under even and uneven noise

Simulate y = 1 + 2x + noise two thousand times, first with even noise and then with noise that is large only where x is above 3, and compare the slope's true spread with the classical and the HC3 standard errors.

Figure produced by Lab 12: Least squares under even and uneven noise
Produced by the lab below, seed 0, in 0.6 s.
python -m videos.stats.labs 12 needs numpy, scipy, matplotlib · download lab12.py · source on GitHub
even noise: mean slope              2.002   (truth 2.0)
even noise: true sd of the slope    0.111   classical SE 0.108   HC3 SE 0.111
even noise: 95% interval covers     classical 95.0%   HC3 94.8%
uneven noise: mean slope            2.002   (truth 2.0)
uneven noise: true sd of the slope  0.306   classical SE 0.230   HC3 SE 0.306
uneven noise: 95% interval covers   classical 85.7%   HC3 95.0%

Uneven noise leaves the slope unbiased but makes the classical standard error too small; the sandwich estimator tracks the true spread in both worlds.
The code (67 lines; it asserts its own result)
"""Lab 12: fit a line two thousand times, and see which standard error tells the truth."""

import numpy as np

from videos.coursekit import labs
from explainer.stats.kit import ols

TITLE = "Least squares under even and uneven noise"
GOAL = ("Simulate y = 1 + 2x + noise two thousand times, first with even noise and then with noise that is large only "
        "where x is above 3, and compare the slope's true spread with the classical and the HC3 standard errors.")
TASKS = [
    "Make the noise t-distributed with 3 degrees of freedom (even variance). Which of the three guarantees survives?",
    "Replace HC3 by HC0 (kind='HC0') at n = 20. How far below 95% does the interval's coverage fall?",
    "Add a point at x = 10 on the line, then off it. Compare its leverage, its residual and Cook's distance.",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    n, reps, beta = 60, 2000, 2.0
    x = rng.uniform(0, 4, n)
    X = ols.design(x)
    lab = labs.Lab()
    out = {}
    for name, scale in (("even", np.full(n, 1.0)), ("uneven", 0.1 + 1.2 * x * (x > 3))):
        slopes, se_c, se_r, cover_c, cover_r = [], [], [], 0, 0
        for _ in range(reps):
            f = ols.fit(X, 1 + beta * x + scale * rng.standard_normal(n))
            slopes.append(f.coef[1])
            se_c.append(f.se()[1])
            se_r.append(f.se("HC3")[1])
            lo, hi = f.ci()[1]
            cover_c += lo < beta < hi
            lo, hi = f.ci(kind="HC3")[1]
            cover_r += lo < beta < hi
        out[name] = dict(slopes=np.array(slopes), sd=np.std(slopes), se_c=np.mean(se_c), se_r=np.mean(se_r),
                         cover_c=cover_c / reps, cover_r=cover_r / reps, scale=scale)
        r = out[name]
        lab.row(f"{name} noise: mean slope", f"{r['slopes'].mean():.3f}   (truth {beta})")
        lab.row(f"{name} noise: true sd of the slope", f"{r['sd']:.3f}   classical SE {r['se_c']:.3f}   HC3 SE {r['se_r']:.3f}")
        lab.row(f"{name} noise: 95% interval covers", f"classical {r['cover_c']:.1%}   HC3 {r['cover_r']:.1%}")
    lab.note = ("Uneven noise leaves the slope unbiased but makes the classical standard error too small; "
                "the sandwich estimator tracks the true spread in both worlds.")
    e, u = out["even"], out["uneven"]
    assert abs(e["slopes"].mean() - beta) < 0.02 and abs(u["slopes"].mean() - beta) < 0.03, "unbiased either way"
    assert abs(e["se_c"] / e["sd"] - 1) < 0.06 and abs(e["cover_c"] - 0.95) < 0.02, "classical theory holds"
    assert u["se_c"] / u["sd"] < 0.87 and u["cover_c"] < 0.91, "classical SE understates under heteroskedasticity"
    assert abs(u["cover_r"] - 0.95) < 0.03, "HC3 restores coverage"

    fig, ax = labs.figure(2, size=(11, 4.2))
    y = 1 + beta * x + u["scale"] * rng.standard_normal(n)
    f = ols.fit(X, y)
    grid = np.linspace(0, 4, 50)
    ax[0].scatter(x, y, s=14, color=labs.BLUE, alpha=0.8)
    ax[0].plot(grid, f.predict(ols.design(grid)), color=labs.GOLD, label=f"fit: slope {f.coef[1]:.2f}")
    ax[0].plot(grid, 1 + beta * grid, color=labs.MUTED, ls="--", label="truth: slope 2")
    ax[0].set(title="One sample with uneven noise", xlabel="x", ylabel="y")
    ax[0].legend()
    bins = np.linspace(beta - 4 * u["sd"], beta + 4 * u["sd"], 60)
    ax[1].hist(u["slopes"], bins=bins, density=True, color=labs.BLUE, alpha=0.6, label="2,000 fitted slopes")
    for se, color, name in ((u["se_c"], labs.RED, "classical SE"), (u["se_r"], labs.GREEN, "HC3 SE")):
        ax[1].plot(bins, np.exp(-0.5 * ((bins - beta) / se) ** 2) / (se * np.sqrt(2 * np.pi)), color=color,
                   label=f"normal with the {name}")
    ax[1].set(title="Uneven noise: which standard error matches the spread?", xlabel="fitted slope")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Make the noise t-distributed with 3 degrees of freedom (even variance). Which of the three guarantees survives?
  2. Replace HC3 by HC0 (kind='HC0') at n = 20. How far below 95% does the interval's coverage fall?
  3. Add a point at x = 10 on the line, then off it. Compare its leverage, its residual and Cook's distance.

Problems, with solutions

Try each problem before opening its solution.

1. Simple regression. Derive \(\hat a, \hat b\) for simple regression from the normal equations, and show \(\hat b = r\,s_y/s_x\).

Solution

The first normal equation, Σ(yᵢ − a − bxᵢ) = 0, gives a = ȳ − bx̄. Substitute into the second, Σxᵢ(yᵢ − a − bxᵢ) = 0. Since Σx̄(yᵢ − ȳ − b(xᵢ − x̄)) = 0 as well, this becomes Σ(xᵢ − x̄)(yᵢ − ȳ) = bΣ(xᵢ − x̄)².

Hence b̂ = Sxy/Sxx = r·√(Syy/Sxx) = r·s_y/s_x.

2. The hat matrix. Show that \(H = X(X^\top X)^{-1}X^\top\) is symmetric and idempotent, and that \(\mathrm{tr}\,H = p\).

Solution
  • Symmetric: Hᵀ = X((XᵀX)⁻¹)ᵀXᵀ = H, since XᵀX is symmetric.
  • Idempotent: H² = X(XᵀX)⁻¹XᵀX(XᵀX)⁻¹Xᵀ = H.
  • Trace: tr H = tr((XᵀX)⁻¹XᵀX) = tr Iₚ = p, by tr(AB) = tr(BA) (Part 4).

3. FWL. Prove the Frisch–Waugh–Lovell theorem for two predictors.

Solution

Let M₂ = I − X₂(X₂ᵀX₂)⁻¹X₂ᵀ. Multiply y = X₁β̂₁ + X₂β̂₂ + e by M₂. Since M₂X₂ = 0 and M₂e = e (e is orthogonal to X₂), this gives M₂y = M₂X₁β̂₁ + e.

e is also orthogonal to X₁, hence to M₂X₁ = X₁ − X₂(⋯). So this is exactly the least squares decomposition of M₂y on M₂X₁, and its coefficient is β̂₁.

4. An omitted variable. True model \(y = \beta_1 x_1 + \beta_2 x_2 + \varepsilon\); \(x_2 = 0.5 x_1 + u\). What does the regression of \(y\) on \(x_1\) alone estimate?

Solution

y = β₁x₁ + β₂(0.5x₁ + u) + ε = (β₁ + 0.5β₂)x₁ + (β₂u + ε). If u is uncorrelated with x₁, the short regression estimates β₁ + 0.5β₂: the bias is γδ with γ = β₂ and δ = 0.5.

5. Standard errors along the line. With \(n = 25\), \(\bar x = 10\), \(\sum (x_i - \bar x)^2 = 100\), \(s = 2\): the SE of the fitted mean at \(x_0 = 10\) and at \(x_0 = 20\), and the prediction SE at \(x_0 = 20\).

Solution

SE(ŷ(x₀)) = s√(1/n + (x₀ − x̄)²/Sxx).

  • At x₀ = 10: 2√(1/25) = 0.40.
  • At x₀ = 20: 2√(0.04 + 100/100) = 2√1.04 = 2.04.
  • Prediction at x₀ = 20: 2√(1 + 1.04) = 2.86.

6. The VIF for two predictors. Two predictors with correlation \(\rho\): show \(\mathrm{VIF} = 1/(1 - \rho^2)\).

Solution

Regressing x₁ on x₂ gives R₁² = ρ², so VIF₁ = 1/(1 − ρ²). By symmetry VIF₂ is the same. At ρ = 0.95 the VIF is 10.3.

Notes and sources

Where it comes back

Idea Returns in
ANOVA, orthogonal designs 13
GLMs: logistic and Poisson regression 14, 24
the linear model in depth (GLS, the Gauss–Markov theorem generalized) 23
mixed models, shrinkage 25
splines, smoothing 29
robust regression, Huber's loss 30
ridge, lasso, p > n 32
sandwich SEs for clusters and time 17, 23
causal regression, IV, DiD 35, 36, 37
the Coverage Board every part; 65

Sources

  • The founding papers.
    • A.-M. Legendre, Nouvelles méthodes pour la détermination des orbites des comètes (1805).
    • C. F. Gauss, Theoria motus (1809); Theoria combinationis (1821–23).
    • R. Boscovich (1757).
    • F. Galton, J. Anthropol. Inst. 15 (1886).
    • A. Markov (1912); A. Aitken, Proc. R. Soc. Edinburgh 55 (1935).
  • Regression in practice.
    • R. Frisch & F. Waugh, Econometrica 1 (1933); M. Lovell, JASA 58 (1963).
    • H. Working & H. Hotelling, JASA 24 (1929).
    • F. Anscombe, Am. Stat. 27 (1973); D. Cook, Technometrics 19 (1977).
    • H. White, Econometrica 48 (1980); J. MacKinnon & H. White, J. Econometrics 29 (1985).
    • P. Huber, Ann. Math. Stat. 35 (1964); A. Hoerl & R. Kennard, Technometrics 12 (1970).
  • The regression fallacy and history.
    • H. Secrist, The Triumph of Mediocrity in Business (1933), and H. Hotelling's review, JASA 28 (1933).
    • J. M. Bland & D. G. Altman, BMJ 308 (1994).
    • S. Stigler, Ann. Stat. 9 (1981); The History of Statistics (1986).
  • Textbooks.
    • S. Weisberg, Applied Linear Regression (4th ed., 2014).
    • A. Gelman, J. Hill & A. Vehtari, Regression and Other Stories (2020).
    • G. Seber & A. Lee, Linear Regression Analysis (2nd ed., 2003).
    • J. Fox, Applied Regression Analysis (3rd ed., 2016).
About this partfrom its README

Part 12 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage II, Bachelor's: Methods. Part 11 put honest intervals on single quantities. This part fits relationships.

It opens with Ceres: Piazzi finds it on 1 January 1801 and loses it in the Sun's glare, and Gauss predicts where it will reappear. Then comes the Legendre (1805) vs Gauss (1809) priority dispute. From there the part covers:

  • the principle, drawn as squares that shrink as the line turns, and the normal equations;
  • why squares (Legendre's convenience, Gauss's derivation of the normal law, Gauss–Markov, geometry), and Boscovich's absolute errors;
  • least squares as a projection (NSpace), the hat matrix and QR, and Pythagoras for R²;
  • Gauss–Markov, proved, with a rival estimator losing; weighted least squares;
  • normal theory, the coefficient table, the nested F-test and the ANOVA table, and robustness to skewed errors;
  • Frisch–Waugh–Lovell, omitted-variable bias (with the World's clinic as Simpson's paradox);
  • dummies, region factors, interactions, logs and splines, standardized coefficients, extrapolation;
  • confidence, Working–Hotelling and prediction bands;
  • collinearity, VIFs and confidence ellipses, the condition number;
  • diagnostics: Anscombe's quartet, leverage, the influence probe, Cook's distance, residual and QQ plots;
  • heteroskedasticity, White's sandwich and HC3;
  • the regression fallacy: Galton's 1886 table, the World's fathers both ways, Secrist (1933), Bland & Altman.

The normal-model t, F, Working–Hotelling and prediction guarantees require an exogenous full-rank linear model with independent normal errors of common variance. World sampling is an empirical approximation check. Gauss–Markov uses second moments and an exogenous design; GLS additionally needs a known positive-definite covariance shape. Robust HC3 inference is asymptotic and assumes independent observations and regular moments/design; it does not repair confounding, misspecified means or arbitrary dependence.

The joint two-slope confidence ellipses use the exact 2 F(2, n−p) cutoff with estimated variance. Cropped histograms retain full sample mass, and paths are geometrically clipped instead of flattening values. The remedy example's gain is 1.30 raw score units, 0.92 SD of a test score (each test has variance 2). Exponentiated predictions of log income are geometric-scale summaries, not arithmetic means. Regression in both directions does not rule out causal relationships, and causal interpretation of adjusted coefficients requires additional identification assumptions.

The orbit is explicitly a constructed schematic, not a reproduction of Piazzi's observations or Gauss's historical calculation. The role of least squares in the 1801 recovery is distinguished from Gauss's published 1809 treatment.

Every number on screen is computed in compute.py or inline in a scene:

  • the families, heights, incomes and clinic come from the World (seed 1662);
  • Anscombe's quartet and Galton's table come from the Museum;
  • everything else is a seeded simulation.

Built in this part:

  • statkit.ols (explainer/stats/kit/ols.py): QR-based fits with:

    • classical and HC0–HC3 covariances;
    • t, p and intervals, R² and adjusted R², nested F-tests;
    • confidence, Working–Hotelling and prediction bands;
    • leverage, studentized residuals and Cook's distance;
    • VIFs and a least-absolute-deviations line.

    Reference outputs are checked against statsmodels in tests/test_stats_kit_ols.py.

  • The influence probe (InfluenceProbe in explainer/stats/viz.py): drag one point and watch the fit, its leverage and Cook's distance respond.

The Coverage Board gains six rows: 95% intervals for the slope, R = 10,000. In the last four, x ~ Exp(1) and the error SD ∝ x.

Method Setting Achieved Verdict
OLS slope, classical SE child on mid-parent, n = 30 95.31% kept
OLS slope, HC3 SE child on mid-parent, n = 30 95.17% kept
OLS slope, classical SE n = 50 60.47% broken
OLS slope, HC3 SE n = 50 90.36% broken
OLS slope, classical SE n = 500 55.42% broken
OLS slope, HC3 SE n = 500 93.80% broken (approaching 95% as n grows)
Chapter notes
# Chapter Numbers
0 Ceres, lost and found —
1 The principle 30 families: b̂ = 0.53; Anscombe 3: LS slope 0.500 vs LAD 0.345
2 Geometry R² = 0.181 = r²; residual sums ≈ 10⁻¹⁵
3 Gauss–Markov slope SD 0.208 (OLS) vs 0.341 (end points); WLS 0.165 vs OLS 0.214
4 Normal theory true slope 0.703; coverage 95.3%; adding mother: F = 22.8, p = 6.5 × 10⁻⁶; R² 0.029 → 0.214; skewed errors: 95% coverage at n = 10, 30, 100
5 Controlling for FWL 0.4354 = 0.4354 (father alone 0.483); OVB: 0.110 vs truth 0.080, formula 0.11; clinic −0.112 vs +0.078
6 Interpreting coefficients son dummy +12.8 cm (R² 0.10 → 0.60); interaction 0.089 ± 0.120; regions F = 0.90, p = 0.52; log-income R² 0.013 / 0.123 / 0.153
7 Bands t = 2.05 vs √(2F) = 2.58; one son: 178.9, mean CI [177.9, 180.0], PI [167.8, 190.1]
8 Collinearity VIF 1.0 vs 7.2; SE 0.12 vs 0.34; SE of the sum 0.15 vs 0.13
9 Diagnostics Anscombe: all 3.00 + 0.500x, R² 0.67; max Cook's D 1.39 (set 3); leverage 1 (set 4)
10 Uneven noise funnel data: classical SE 0.095 vs HC3 0.267; the board rows above
11 The regression fallacy Galton 1886: slope 0.646; World: fathers +1.94σ → children +0.77σ; children +1.94σ → fathers +0.76σ; a useless remedy "gains" 1.30 raw units = 0.92 test SD
12 Outro —
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Ceres (1801). Piazzi loses it; Gauss predicts its return; Legendre (1805) vs Gauss (1809).
  2. The principle. Normal equations; why squares (Gauss), and why absolute errors (Boscovich 1757, Laplace).
  3. Geometry. The column space; H; orthogonal residuals (NSpace).
  4. Gauss–Markov. BLUE, proved.
  5. Normal theory. β̂'s distribution; t-tests; nested F-tests as Pythagoras; R².
  6. Frisch–Waugh–Lovell (1933). "Controlling for", concretely; omitted-variable bias.
  7. Interpreting. Units, dummies, interactions, polynomials and splines; extrapolation.
  8. Bands. Confidence vs prediction.
  9. Collinearity. VIFs; the elongated confidence ellipse.
  10. Diagnostics. Leverage, studentized residuals, Cook's distance (1977); the InfluenceProbe.
  11. Heteroskedasticity. The classical SE lies; White (1980) and HC3 (Board).
  12. Regression to the mean, revisited (Part 5), and the regression fallacy.
  13. Outro.

Built: statkit.ols (I), checked against statsmodels; the InfluenceProbe.

Build the film

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

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

Build it
python -m videos.stats.stats12.compute         # once (about a minute; cached in .cache/stats12)
python tools/build.py stats12 -q l             # fast 480p preview
python tools/build.py stats12                  # 1080p30 -> renders/stats12.mp4
python tools/qa_scene.py stats12 Diagnostics
python tools/lecture_length.py stats12 --floor 50