SStatistics, Built

Stage III · Master's

Part 23 of 65

The Linear Model in Depth

Master'sstarts at this level56 min of film13 chaptersprerequisites: Part 12, Part 21, Part 22

What does the linear model really estimate, and how far can its standard errors be trusted?

In 1967 James Longley runs sixteen years of US employment data through the regression programs of the day and gets wrong digits: the predictors are nearly collinear, and the normal equations square the condition number that QR leaves alone. Part 12 derived least squares under four quiet assumptions, and this part drops each in turn, with one sandwich formula as the frame. The general linear hypothesis gives every F-test as a quadratic form. Correlated errors lead to Aitken's GLS, uneven errors to HC0 through HC3 and the wild bootstrap, and pupils grouped in the World's schools to Moulton's factor, the cluster-robust standard error and its failure with eight clusters. When the mean is not linear the fit still estimates the best linear predictor, and the sandwich is its correct standard error. A noisy regressor attenuates the slope, as Hubble's nebulae show. The part then fits quantiles and spline bases, returns to Householder's reflections and the digits lost to conditioning, and ends with the deletion formula, DFBETAS and masking.

What you need. Linear algebra at the level of Part 4 (projections, QR, quadratic forms) and the regression of Part 12.

Hook
Longley's benchmark, 1967
Mathematics
the general linear hypothesis, Cochran, GLS, heteroskedasticity and cluster theory, errors in variables, quantile regression, numerics
Built
statkit.ols (II)

What you will be able to do

Bachelor's

  • Explain why two programs can return different coefficients from the same ill-conditioned data, and what centring and scaling do to the condition number.

Master's

  • Test any linear hypothesis C beta = d by its F statistic, in the quadratic-form and the two-fits versions, and show they agree.
  • Derive GLS by whitening, Moulton's factor for a cluster-level regressor, and the attenuation of a slope under classical measurement error.
  • Compute HC and cluster-robust covariances and say which small-sample corrections each uses.

PhD

  • State what least squares estimates when the mean is not linear and the regressors are random, and prove that the sandwich, not the classical formula, gives its asymptotic variance.
  • Explain why cluster-robust inference fails with few clusters and what the restricted wild cluster bootstrap does and does not repair.

Practice

  • Choose the level to cluster at from the design, and report the number of clusters with the standard error.
  • Solve least squares by QR, not the normal equations, and check a fit with leverage, DFBETAS and deletion of groups of points to catch masking.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 6 min · Master's 52 min · PhD 56 min · Practice 14 min.

  1. 0Longley's test, 1967Bachelor's3 min
  2. 1Upgrade: what Part 12 assumedMaster's2 min
  3. 2The general linear hypothesisMaster's5 min
  4. 3GLS and AitkenMaster's4 min
  5. 4Heteroskedasticity theoryMaster's4 min
  6. 5ClusteringMaster's6 min
  7. 6Models as approximationsPhD4 min
  8. 7Errors in variablesMaster's6 min
  9. 8Quantile regressionMaster's5 min
  10. 9Splines and basesMaster's4 min
  11. 10NumericsPractice5 min
  12. 11InfluencePractice4 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.

Longley's test, 1967Bachelor's3 min

In 1967 James Longley, an economist at the US Bureau of Labor Statistics, published a warning in the Journal of the American Statistical Association. He had taken sixteen years of American economic data, a regression with seven coefficients, and run it through the least squares programs of the day. Many printed answers with hardly a correct digit. The programs did nothing wrong in algebra. They solved the right equations the wrong way.

Here are Longley's data: total employment from 1947 to 1962, with six predictors, the price deflator, gross national product, unemployment, the size of the armed forces, the population, and the year itself. They are almost the same variable six times over: GNP and the year are correlated point nine nine five, GNP and population point nine nine one. One variance inflation factor, Part 12's measure of collinearity, is nearly eighteen hundred. Decades later the US National Institute of Standards and Technology certified the right answer to fifteen digits, so we can grade any method against it.

Let's repeat Longley's test. Each bar counts the correct significant digits of a coefficient, out of fifteen. First the textbook formula, solving the normal equations X transpose X b equals X transpose y, in single precision, about seven digits, roughly what many machines of the sixties used. The matrix isn't even recognizably positive definite any more, the Cholesky factorization fails, and plain elimination returns numbers with no correct digits at all; several have the wrong sign. The same precision with a QR decomposition, Part 4's method, gets five or six digits right. In double precision the normal equations manage seven or eight, and QR eleven to thirteen. The arithmetic was the same; the route through it decided the answer.

Why? The condition number of the design matrix, the ratio of its largest to smallest singular value, is about five billion: some direction in the data is almost not there. Forming X transpose X squares it, to about two times ten to the nineteen. A rule of thumb says you lose about the log of the condition number in digits. This is a worst-case sensitivity guide, not a prediction of the observed digits. QR avoids squaring the working matrix condition number; actual accuracy also depends on the response and residual. Centring and scaling the predictors brings the condition number down to about one hundred and ten. Chapter ten returns to the numerics.

Numbers: digits 0 / 5–6 / 7–8 / 11–13; κ 4.9e9, κ(X'X) 2.4e19; scaled κ 111

1Upgrade: what Part 12 assumedMaster's2 min

Part 12 derived least squares and proved the Gauss–Markov theorem: the least squares estimator is the best linear unbiased estimator, with variance sigma squared times X transpose X inverse. It assumed a lot: that the mean really is linear in the predictors, that the errors have equal variances and are independent, that the predictors are measured exactly, and, as Longley just showed, that the arithmetic is exact. This part drops each assumption in turn and repairs what breaks.

Write the model as y equals X beta plus an error whose mean, given X, is zero. Part 12 added that the errors are uncorrelated with a common variance. The estimator's error is X transpose X inverse, X transpose, times the errors: it is linear in them. So its variance is a sandwich, with whatever the variance of the errors is in the middle. Every chapter of this part is about what goes in that middle, and what to do when we don't know.

A reminder of exactly where the assumptions enter. Take any other linear unbiased estimator, A y, with A X equal to the identity. Write A as least squares' matrix plus a difference D; unbiasedness forces D X to be zero. Its variance is least squares' variance plus sigma squared D D transpose, which can only add: the cross terms vanish because D X is zero. But that algebra used the error variance being sigma squared times the identity. Change the middle, and least squares need no longer win, which is where chapter three begins.

The map. If the errors' covariance has a known shape, generalized least squares uses it. If each error has its own unknown variance, heteroskedasticity-consistent standard errors estimate the middle from the residuals. If errors are correlated within clusters, sum within clusters first. With finite second moments and a nonsingular predictor moment matrix, least squares can estimate the best linear predictor even when the mean is curved. Classical independent error in a single regressor attenuates its slope; with several regressors the direction of bias can vary. And the arithmetic needs care too.

Numbers: the sandwich; Gauss–Markov's use of σ²I

2The general linear hypothesisMaster's5 min

Almost every question asked of a linear model is a set of linear restrictions: C beta equals d, with q linearly independent rows, one per restriction, and a full-rank design with more observations than coefficients. A single coefficient being zero is one row. Two coefficients being equal is a contrast. Several coefficients all being zero at once is a joint hypothesis with two or more rows. One test handles them all.

With errors jointly normal with conditional covariance sigma squared times the identity, C beta hat minus d is normal, centred at zero under the hypothesis, with covariance sigma squared C X transpose X inverse C transpose. Measure how far it is from zero in its own metric: the quadratic form Q, the squared length after the covariance has been undone. Divided by sigma squared it is chi-squared with q degrees of freedom, and, because it depends on the fit and not the residuals, independent of the residual variance s squared. Replace sigma squared by s squared and divide by q: an F statistic with q and n minus p degrees of freedom.

There's a second way to see the same statistic. Fit the model with the restriction imposed and without it. For homogeneous restrictions and nested models containing the intercept, these are projections onto nested linear spaces, giving the displayed Pythagorean decomposition. For general affine restrictions too, the extra residual sum of squares is exactly Q, though the first centered decomposition need not apply. So F compares two fits: how much worse the restricted model does, per restriction, against the noise level. Cochran's theorem from Part 4 says orthogonal pieces of a normal vector have independent chi-squared lengths, which is what makes the ratio an F.

For nested models with a common intercept and the same response, divide the residual sums by the total sum of squares and the same statistic reads in R squared: the gain in R squared per restriction, against the unexplained share per residual degree of freedom. Testing all the slopes at once gives the overall F that every regression printout shows. With a single restriction, F is the square of the familiar t. And in large samples q times F becomes chi-squared: it is Part 22's Wald test, under moment, design and homoskedasticity conditions. With uneven variances use a robust Wald covariance instead.

Four hundred families from the World, heights standardized. Regress each adult child on father and mother. The coefficients are point three three and point three four; the World was built with point three five for each. Do fathers and mothers count equally? F is point oh eight, p point seven eight: no evidence otherwise. Are both exactly point three five? A two-row test, p point eight five. Do parents matter at all? F is sixty-two. And the first test done as two fits, with and without the restriction, gives the same F to every digit.

Is the F distribution really right? Keep the predictor design of four hundred World families fixed, draw two thousand fresh Gaussian response vectors under equal-parent coefficients, and compute F each time. This conditional Gaussian experiment imposes the null exactly; resampling the finite World would not provide this exact reference model. The histogram follows the F density with one and three hundred and ninety-seven degrees of freedom. Its ninety-fifth percentile is three point eight six. The test rejects five point three percent of the time, within simulation error of five.

Inverting the joint test gives a confidence region: every pair of coefficients the F-test would not reject. It's an ellipse, its shape set by the covariance of the two estimates. The line of equal coefficients passes through it, so equality isn't rejected. The World's true pair is inside. And the origin, no effect of either parent, is far off the chart.

The ellipse also answers a harder question. One pre-planned contrast gets the usual t interval. But if you will look at every contrast within a specified q-dimensional coefficient subspace and report the interesting ones, Henry Scheffé's 1953 intervals replace t by the square root of q times the F quantile, and then all of them hold together with ninety-five percent confidence. The reason is Cauchy–Schwarz: the largest squared t over contrasts in that subspace is exactly q times its F statistic, the projection of the ellipse onto every direction. With two coefficients and four hundred families, the multiplier grows from one point nine seven to two point four five: the price of fishing, paid in advance. Part 33 returns to it.

Numbers: 0.326, 0.344; F 0.079 (p 0.78), 0.162 (p 0.85), 61.9; conditional Gaussian null rejection 5.3%; Scheffé 2.45

3GLS and AitkenMaster's4 min

Suppose the errors' covariance is sigma squared times a known positive-definite matrix omega, with Cholesky factor L, and a full-rank design. Multiply the whole model by L inverse: the new errors have covariance sigma squared times the identity, so they satisfy Part 12's assumptions. Least squares on the whitened data is generalized least squares, which weights the data by omega inverse. Alexander Aitken proved in 1935 that it is the best linear unbiased estimator: Gauss–Markov, applied after whitening. Weighted least squares, from Part 12, is the special case of a diagonal omega.

The simplest case is a diagonal omega. Suppose the data are group averages, the g-th of m g observations, so its variance is sigma squared over m g. GLS then weights each average by its group size: weighted least squares. If the predictors are the same within each group, this gives exactly the least squares fit to the individual data: averaging gives the same coefficient estimate. The within-group residual variation still matters for estimating uncertainty. With fixed weights, or exogenous weights determined by X, a correctly specified conditional mean keeps the estimate unbiased; it may be less efficient, but the standard error printed from the wrong weights is wrong. Remember that pattern.

A common case: a trend measured over time, sixty points, with errors that follow an autoregression, each equal to point eight times the previous plus fresh noise. The true trend has slope two. This particular series' least squares line has slope one point four eight. The errors wander in long runs above and below the trend, so sixty points carry much less information than sixty independent ones.

Two thousand such series. The least squares slope varies with a standard deviation of about two. Generalized least squares, using the true correlation, does a little better, one point eight seven. Prais and Winsten's feasible version, which estimates the correlation first, is almost as good. For trends under suitable short-memory stationary errors, Grenander and Rosenblatt established asymptotic efficiency results; these do not apply to every time-series regression. The real damage is elsewhere: the standard error least squares reports, which assumes independent errors, averages point six five, a third of the truth.

Coverage of nominal ninety-five percent intervals for the slope. With the naive standard error: forty-eight percent. Newey and West's autocorrelation-consistent standard error, from Part 17, helps but reaches only sixty-eight with sixty strongly correlated points. Feasible GLS reaches eighty-four. In this experiment, only the interval using the true correlation reaches nominal coverage. Strong dependence and short series are a hard combination; there's no free lunch in estimating the error structure.

How would we have known? James Durbin and Geoffrey Watson's 1950 statistic compares successive residuals; it is about two times one minus the residuals' lag-one correlation. That correlation is estimated directly from the residuals. For our example series it is about point eight one, and the actual Durbin–Watson statistic is point three eight; endpoint terms explain the difference from two times one minus rho, far below the value of two that independent errors would give. Donald Cochrane and Guy Orcutt's 1949 recipe then differences out the estimated correlation and refits, repeating until it settles; Prais and Winsten's version keeps the first observation instead of dropping it.

In practice omega is unknown, so feasible GLS estimates its parameters first, here the autocorrelation, and then whitens with the estimate. With a consistently estimated covariance model and suitable regularity, feasible GLS can have the same first-order efficiency as GLS. Since the assumed shape may itself be wrong, the modern habit is to pair either estimator with a standard error that doesn't trust the shape. The lesson carries through the whole part: getting a nearly efficient estimate is easy; getting an honest standard error is the hard part.

Numbers: SD 1.99 / 1.87 / 1.89; naive SE 0.65; coverage 47.7 / 68.2 / 83.8 / 94.8%; DW 0.380

4Heteroskedasticity theoryMaster's4 min

Now suppose each error has its own variance, and we don't know any of them. The sandwich from chapter one has the sum of sigma i squared x i x i transpose in the middle. Friedhelm Eicker, Peter Huber and Halbert White each proposed replacing each unknown variance by that observation's squared residual: HC zero, Part 12's robust standard error. One squared residual is a terrible estimate of one variance, but we never need the variances individually, only a weighted average of them, and under independent sampling, sufficient moments and controlled leverage, the weighted sum consistently estimates the covariance.

Should you test for heteroskedasticity first? The studentized Breusch–Pagan variant, associated with Koenker, regresses squared residuals on predictors. Under the null and suitable moment conditions, n times its R squared has an asymptotic chi-squared reference. White's version adds squares and products of the predictors. But testing first, and using the classical standard error when the test passes, works badly: in small samples, exactly where the classical formula fails, the test often lacks the power to notice. The modern habit is simpler: report robust standard errors routinely, and model the variance with weighted least squares only when efficiency matters.

Where does uneven noise come from? Averages of unequal groups, as chapter three's weights assumed. Multiplicative errors, common in money and biology, make the spread grow with the mean; a log transform can stabilize multiplicative noise when its distribution is stable. The transformed mean is a different estimand. Counts and proportions have variances tied to their means, which Part 24 builds in. And a slope that differs from person to person, an interaction left out of the model, shows up as noise that grows with x: the random slopes of Part 25.

Small samples are where it goes wrong. Thirty points, with noise proportional to x, and x skewed, so a few points sit far to the right. Those far points are both the noisiest and, drawn here by size, the ones with the most leverage. This sample's largest leverage is far above the average, p over n. A high-leverage point pulls the line towards itself, which can make its residual too small. In this experiment that damages HC zero most where uncertainty matters most; it is not a pointwise law for every heteroskedastic design.

Residuals are systematically too small: even with equal errors, the expected squared residual is one minus the leverage, times sigma squared. HC one inflates every residual by the same degrees-of-freedom factor. HC two divides each by one minus its own leverage, giving an unbiased covariance estimator under a correct linear mean with homoskedastic uncorrelated errors, not an exact confidence interval. HC three divides by the square, inflating the leverage correction further; MacKinnon and White found good small-sample performance in their experiments, and it is close to the jackknife variance of Part 16.

Four thousand samples of thirty for the covariance formulas, and one thousand for the more expensive wild-bootstrap procedure. The classical interval covers the true slope seventy-six percent of the time. HC zero, eighty-two; HC one and HC two, a little better; HC three, ninety-one: the best of the formulas, still short. The wild bootstrap does better still. Fit the tested null, keep its restricted fitted values, multiply its residuals by random signs, refit, and compare studentized statistics. This retains estimated variance patterns; it does not reveal each unknown variance. It covers ninety-three.

To the Board, with a fresh thousand samples. HC zero: eighty-one percent, broken. HC three: ninety, closer but still broken at this sample size. The wild bootstrap-t: ninety-four, kept. In this experiment resampling outperforms the displayed covariance formulas. Its finite-sample performance still depends on the design and resampling method.

Numbers: coverage 76.1 → 90.6 (HC3), wild 93.4%; Board 81.1 / 90.0 / 94.4%

5ClusteringMaster's6 min

The World has four hundred schools. Sample forty and take every pupil in them: about two and a half thousand pupils. Half the schools run a tutoring programme, assigned to whole schools. Each dot is a school's mean score, sized by its number of pupils. A regression of pupils' scores on the programme and home background estimates the effect at twenty-seven and a half points; the World's truth is twenty. The usual standard error says three point six five, so the estimate looks precise and wrong. The cluster-robust standard error says ten. The truth is well inside its interval.

Brent Moulton gave the size of the problem in 1986. A simple equal-size exchangeable model gives a variance inflation factor of one plus cluster size minus one, times the regressor and error intraclass correlations. Using average size with unequal clusters and covariate adjustment is a heuristic. It's Kish's design effect from Part 18. Here there are sixty-one pupils per school; the programme is the same for every pupil in a school, so its correlation is one; and the residuals' intraclass correlation is only point one one four. But point one one four times sixty is about seven: the variance is understated eightfold, the standard error by a factor of two point eight. The cluster-robust standard error came out two point seven five times the iid one.

The fix is chapter one's sandwich again, with clusters independent of each other but anything allowed inside. For the meat, add up each cluster's scores, X transpose e, and square the sum: correlations within a cluster are captured because the cross-products are kept. With a small-sample factor this is CR one, from Kung-Yee Liang and Scott Zeger and from Manuel Arellano, and it's compared with a t distribution with G minus one degrees of freedom. It is consistent as the number of clusters grows. Cluster asymptotics need many independent schools, finite moments and no dominant cluster. Information also depends on within-school predictor variation; there is no universal effective sample size equal to G.

But clusters are often few. With eight schools, the meat is estimated from eight summed residual vectors. And as chapter four found for single points, residuals understate errors, most for clusters that are large or unusual. With few clusters CR one can be too small and tests can reject too often, as Colin Cameron, Jonah Gelbach and Douglas Miller documented in 2008. This is everyday reality: policy studies cluster by state or country, and Part 37's difference-in-differences studies often have fewer than twenty.

The wild cluster bootstrap. First, fit the model with the null hypothesis imposed, keeping fitted values and residuals. Then make new data sets by multiplying all the residuals in a cluster by the same random weight, plus or minus one, or one of Matthew Webb's six values. Each school's residuals keep their internal pattern, which is what the inference needs to respect. Refit and compute the cluster-robust t-statistic each time. We use one plus the number of at-least-as-extreme bootstrap statistics, divided by one plus the number of draws. This Monte Carlo correction prevents zero p-values; it does not make few-cluster inference exact. With eight clusters, signs alone give only two hundred and fifty-six possible data sets; Webb's weights give one point seven million.

At which level should you cluster: pupils, schools, towns, or regions? Alberto Abadie, Susan Athey, Guido Imbens and Jeffrey Wooldridge argue from the design: cluster at the level where the treatment was assigned, or where the sample was drawn. Here the programme was assigned to schools, so schools. When errors are correlated along two dimensions at once, say schools and years, two-way clustering adds the two one-way variances and subtracts their intersection. Coarser clustering can reduce the available independent units and make variance estimates unreliable; it is not automatically conservative. Few-cluster two-way estimates can even be indefinite.

Clustering can be modelled instead of merely corrected. Give each school a mean-zero effect u g shared by all its pupils, uncorrelated with the predictors and independent of individual errors. Then each school's errors have an exchangeable covariance: equal variances, and one correlation between any two pupils. Generalized least squares with a known covariance gives the fixed-coefficient estimator for the random-intercept model of Part 25, more efficient than least squares when the model is right. Pairing it with a cluster-robust standard error can protect against covariance misspecification under cluster asymptotics, while a biased conditional-mean model still needs attention, which is exactly what Part 24's generalized estimating equations do.

The Board, with a thousand samples of forty schools. The iid standard error covers the programme's true effect forty-nine percent of the time: broken. Cluster-robust: ninety-five, kept. Now only eight schools. Cluster-robust with t on seven degrees of freedom: eighty-nine, broken. The wild cluster bootstrap with Webb's weights: ninety-six, kept.

Numbers: 27.5 (truth 20); SE 3.65 vs 10.04; Moulton 7.9, ratio 2.75; Board 49.1 / 95.1 / 88.6 / 96.0%

6Models as approximationsPhD4 min

Suppose the true mean of y given x has any shape at all. There is a unique best line when second moments exist and the predictor moment matrix is nonsingular: the population least-squares projection, beta star. Under suitable sampling and moment conditions least squares estimates it consistently, just as Part 22's maximum likelihood estimate converged to the closest wrong model. Andreas Buja and colleagues called this, in 2019, the view of models as approximations. The new twist is that the residual now contains the nonlinearity, the gap between the curve and the line, which is a function of x and doesn't average out at each x.

The World's incomes against age, for adults up to seventy-five: a sample of two hundred. The true mean, computed from all the World's adults, rises steeply through the twenties, levels off, and drops at retirement. The best line through the whole population rises two hundred and seventy-four a year. It is a summary of a curve: not the effect of a year of age at any particular age.

Here's the consequence. The best line for all adults has slope point two seven. Restrict to adults aged eighteen through forty and the best line has slope one point one five, four times steeper. The curve is the same; only the distribution of ages changed. When the model is wrong, what least squares estimates depends on the distribution of x, so random-design inference must account for the sampled predictor distribution, and a study of the young and a study of everyone are estimating different numbers.

The standard errors change too. The plainest example: x standard normal, y equal to x squared plus a little noise. The best line is flat, slope zero. Its projection residual, x squared minus one plus independent noise with standard deviation point three, is largest exactly where x is far from zero, the points that drive the slope. The classical standard error ignores that, and its intervals cover the target sixty-one percent of the time in samples of a hundred. The sandwich covers ninety-four. With random predictors, the squared projection residual depends on x, even though the noise has constant conditional variance. The empirical-score sandwich accounts for both sources of variation under suitable moments. For the World's incomes the two kinds of standard error happen to agree, covering ninety-six percent, but nothing guaranteed that in advance.

Part 16's bootstrap comes in three flavours for regression, and they answer different questions. The residual bootstrap keeps the fitted line and reshuffles residuals: it assumes the errors are interchangeable, and reproduces the classical standard error. The pairs bootstrap resamples whole observations, x and y together, as David Freedman analysed in 1981: it reproduces the sandwich. The wild bootstrap keeps each x and flips each residual: fixed predictors, a suitable mean model and uneven variances, under bootstrap regularity conditions. When the model may be wrong and the predictors were sampled, the pairs bootstrap can target beta star with iid sampling, adequate moments and a nonsingular design. Dependence or very heavy tails require further care.

So a linear model is a useful summary even when it is wrong, but the thing it summarizes depends on who was sampled. Its honest standard error is the sandwich, and a bootstrap that resamples whole observations, x and y together, agrees with it. And a coefficient, right or wrong, is a description, not an effect; turning it into a causal claim needs the arguments of Parts 35 to 37.

Numbers: BLP 0.27 vs 1.15 (ages 18–40); toy 61% vs 94%

7Errors in variablesMaster's6 min

Part 12 assumed the predictors are measured exactly. Suppose instead we see w, the true x plus independent measurement error. The least squares slope converges to the covariance of w and y over the variance of w. The error adds to the variance but not to the covariance, so the slope is beta times a fraction, the reliability lambda, the share of w's variance that is real. In this simple classical-error model the slope is attenuated towards zero however large the sample. This direction need not hold for every coefficient in a multiple regression. With several predictors the bias spreads: a confounder measured with error is only partly controlled for, and some of its effect is credited to the others, as Part 20 found with sodium.

Five hundred of the World's families: the child's height against the father's, both standardized. With exact heights the slope is point three six five; the whole World's is point three nine one. Now record each father's height with an error big enough that only sixty percent of the recorded variance is real, an illustrative reliability assumption, not a validated error model for actual self-reports or blood-pressure readings. The cloud spreads sideways. The slope falls to point two one six. The formula predicted point six times point three nine one, point two three five.

On the Board: a thousand samples of five hundred families with the noisy fathers. The usual ninety-five percent interval for the slope covers the World's true slope four times in a thousand. More data would make this worse, not better: the interval would shrink around the wrong value.

The most famous regression with a noisy x. In 1929 Edwin Hubble plotted the recession velocities of twenty-four nebulae against their distances, and found that the farther a galaxy, the faster it recedes: the expanding universe. His distances were far noisier than his velocities. Regress velocity on distance: four hundred and fifty-four kilometres per second per megaparsec, attenuated by the noisy distances. Regress distance on velocity instead and invert: seven hundred and twenty-nine. The truth, if the errors were all in distance, would be nearer this one. Deming regression, which needs the ratio of the two error variances, using an illustrative constant error ratio based on velocity SD one hundred kilometres per second and distance SD twenty percent of mean distance, not a validated historical calibration, lands between, at five hundred and eighty-two.

Deming regression minimizes errors in both directions, with delta, the ratio of the error variances, deciding how to trade them. With delta equal to one it's orthogonal regression, or total least squares, computed from the smallest singular vector of the data matrix; but here velocity and distance have different units, so one is an arbitrary choice and the answer is seven hundred and twenty-nine. The two naive slopes differ by a factor of r squared, and the positive Deming slopes lie between these two fitted slopes as the assumed variance ratio varies. Bracketing a true slope requires a valid classical-error model, not just this historical scatter. And a humbling footnote. Hubble's distances weren't just noisy, they were systematically too small, by a factor of about seven, because of a mistaken calibration of the stars he used as yardsticks. Today's value is about seventy. No regression method corrects an error that every observation shares.

SIMEX, simulation-extrapolation, from John Cook and Leonard Stefanski in 1994, needs only the error variance. Take the noisy fathers and deliberately add more error, half as much again, then the same again, twice as much. Average the slope over two hundred simulations at each step: it falls steadily. Fit a curve through those slopes and extrapolate back to minus one, the imaginary point where the original error is removed too. The estimate is point three one two, from a naive point two one six. The World's slope is point three nine one: Here the chosen quadratic recovers part of the loss. Extrapolation bias and uncertainty depend on the curve and on the assumed measurement-error distribution and variance.

Error in the outcome is a different matter. If what we record is y plus independent noise, the noise simply joins the regression error, and the slope stays unbiased. The cost is precision: larger standard errors and less power. The exception is differential error, a systematic conditional mean of recording error that depends on the predictors, such as under-reporting that differs by group. A variance that depends on x alone need not bias the slope when conditional mean error is zero.

Every cure needs information from outside the regression itself. If repeated measurements give the reliability, divide by it: Part 20's regression calibration. If you know the ratio of error variances, use Deming. If you have an instrument, something correlated with the true x but uncorrelated with both measurement error and the structural regression error, and satisfying exclusion, use instrumental variables, Part 37. SIMEX adds extra simulated error in steps, watches the slope shrink, and extrapolates back to no error at all. Part 41 treats measurement error in full.

Numbers: 0.365 → 0.216 (pred. 0.235); Board 0.4%; Hubble 454 / 729 / 582; SIMEX 0.312

8Quantile regressionMaster's5 min

Least squares models the mean. Roger Koenker and Gilbert Bassett showed in 1978 how to model any quantile. The check loss is a tilted absolute value: residuals above the line cost tau each, below it one minus tau. The minimizers of expected check loss are tau quantiles; ties can make the minimizer nonunique, just as the mean minimizes squared error and the median absolute error. So minimize the check loss over regression lines: the tau-th regression quantile. It's a linear program, Part 21's chapter four, and solved numerically to a solver tolerance.

A thousand of the World's working-age adults, income against age. The tenth percentile rises two hundred and twenty a year. The median rises four hundred and seventy. The ninetieth percentile rises eleven hundred. The lines fan out: incomes spread as people age, so a single slope for the mean, point four one, describes nobody in particular. Least squares, dashed, also sits above the median, pulled up by the long right tail.

Under iid sampling, finite score moments and a nonsingular density-weighted design, a quantile-regression line has an asymptotic sandwich covariance. The bread D weights each predictor outer product by the conditional density at the fitted line. The meat B is the expected outer product of the quantile score. If the conditional quantile really is linear, B simplifies to tau times one minus tau times E x x transpose. Sparsity means the inverse of the density at the quantile: fewer data near the line means greater uncertainty. Estimate D by a sample average of kernel-weighted predictor products. Our World example uses empirical score meat because the conditional quantile need not be exactly linear; pairs resampling provides a second approximation.

The standard errors, two ways: a kernel-bread, empirical-score sandwich, and one hundred pairs-bootstrap refits at each quantile. Differences include density estimation, finite-sample effects and substantial Monte Carlo uncertainty from only a hundred bootstrap draws. In this example the upper-quantile slope is much less precise. The median slope has a smaller estimated standard error than the mean slope; this comparison is a feature of these data, not a universal ranking.

A location–scale model has a linear mean and a positive linear scale, with an independent mean-zero error of fixed distribution. Its conditional quantiles are linear; their slopes change with tau in the direction set by the scale coefficients, increasing only where those coefficients are positive. A treatment coefficient describes a conditional quantile contrast under the fitted model. A causal interpretation additionally needs identification, such as randomization or adequate confounding control. It is not automatically the marginal quantile treatment effect. Nor is a contrast between distributional quantiles the effect on the person who started at that rank: treatment can reshuffle ranks. Part 35 makes this distinction precise.

Part 21 fitted quantile regressions to Ernst Engel's 1857 survey of two hundred and thirty-five Belgian households. The slopes of food spending on income ran from point four at the tenth percentile to point six nine at the ninetieth. The fitted intercepts are positive. A fitted food-spending quantile a plus b times income therefore has food share a over income plus b, which falls with income. A slope below one alone would not establish this. The fitted fan shows a wider conditional range of food spending at higher incomes, not which foods households eat. What chapter four treated as nuisance heteroskedasticity, quantile regression reads as substance.

Population quantiles commute with strictly increasing transformations. Exponentiating a correctly specified log-quantile model gives an income quantile, but refitting a parametric linear model after a nonlinear transformation need not give the same fitted values. The vertical residual score is bounded and depends on its sign; moving an inactive point without changing the relevant signs can leave the optimum unchanged. High-leverage predictors can still be influential. Lines fitted separately can cross where data are thin, which is impossible for true quantiles; sorting the fitted values fixes that. Quantile regression is how paediatric growth charts, financial value at risk and studies of inequality are built: they all care about the whole distribution, not its centre.

Numbers: slopes 0.22 → 1.14; SEs 0.06 → 0.32; Engel 0.40–0.69

9Splines and basesMaster's4 min

A linear model only has to be linear in its coefficients. Replace x by any set of basis functions of x, and least-squares algebra still applies. Exact F-tests need the Gaussian homoskedastic model and fixed basis choice; robust inference needs its own sampling and moment conditions. Selecting bases using y adds selection uncertainty. A cubic spline is a cubic polynomial allowed to change at chosen knots, staying smooth. The obvious basis adds a truncated cube at each knot. B-splines, from Carl de Boor's recursion, span exactly the same functions, but each is a local bump, and together they sum to one. They're far better for the computer: with three knots on ages, the truncated-power design has condition number thirty million; the B-spline design, under six.

Here are the seven cubic B-splines for knots at ages thirty-three, forty-four and sixty-one, the quartiles of a sample. Each is non-zero over at most four neighbouring intervals. At every age they add up to exactly one. Only neighbouring B-spline basis functions overlap in predictor space, so their Gram matrix is banded. This design is well conditioned, but poorly spaced knots or rank deficiency can still cause numerical trouble.

Fit log income against age for eight hundred of the World's adults. The World's true mean rises, levels off and steps down at retirement. One knot gives a smooth curve that can't follow the drop. Three or six knots, placed at sample quantiles, track the truth closely. Twenty knots wiggle: each piece is fitted to a handful of people.

How many knots? Part 19's answer: cross-validate. Ten-fold prediction error for zero to twenty-five knots. The displayed minimum is the computed value for this split; every fold learns its knots from training predictors alone. But look at the scale: many choices have very similar prediction errors. Individual incomes vary so much around the curve that its fine shape hardly changes the prediction error; we compute the one-standard-error choice shown here. The standard error across ten correlated fold losses is a heuristic, not an exact confidence interval. Choosing knots is awkward and unstable. Part 29 instead uses many knots and penalizes roughness, choosing one smoothing parameter.

Bases compose. Multiply the age basis by an indicator for women and the model has two age curves, one for each sex. Whether the curves differ is a single general linear hypothesis, all the interaction coefficients zero, tested with chapter two's F. Products of two bases make surfaces in two variables. The catch is the count: K columns for a curve, K squared for a surface, K cubed for three variables. Part 29 meets this curse of dimensionality.

Cubic splines misbehave at the ends, where data are thin. A natural cubic spline is forced to be a straight line beyond the outer knots. With J distinct interior knots and two fixed boundary knots, imposing zero second derivative at the boundaries removes two degrees of freedom from the unrestricted cubic spline. The natural basis has J plus two columns, including the intercept. Whether the curve is needed at all is then a general linear hypothesis: test that the nonlinear columns' coefficients are all zero, with chapter two's F. These are the restricted cubic splines Part 20 used for age in its blood-pressure model.

Numbers: κ 3.2e7 vs 5.7; CV flat, min 8 knots

10NumericsPractice5 min

The method behind QR, from Alston Householder in 1958, is a mirror. Take a column of the data, here the vector three, four. There is a mirror that reflects it onto the first axis. Its image is minus five, zero: the same length, with every component but the first zeroed. The reflection is an orthogonal matrix, the identity minus twice the projection onto v. In exact arithmetic orthogonal transformations preserve the norm of an existing error. Floating-point steps add roundoff too, but Householder QR controls it through backward stability.

Apply it to a whole design matrix, seven rows and three columns. The first reflection zeroes the first column below its top entry. The second works on the remaining rows and zeroes the second column below the diagonal, without disturbing the first row. After three reflections the matrix is upper triangular: R. Applying the same reflections to y gives Q transpose y. Then R b equals Q transpose y is solved from the bottom up. The normal equations never appear.

Three routes, at three prices. Forming X transpose X and taking its Cholesky factor is the fastest, but squares the condition number, Longley's disaster. Householder QR costs about twice as much and works with the condition number itself; it is what R's lm and most statistical software do. The singular value decomposition costs a few times more again, and shows directly which combinations of predictors are nearly missing. When the columns are exactly dependent, it gives the minimum-norm least squares solution through the pseudoinverse, which Part 59 will meet again when there are more parameters than data.

QR also updates well. When a new observation arrives, stack it under R, carry the transformed response alongside it, and rotate with p small Givens rotations, each mixing two rows. That costs order p squared per row, so least squares can be updated as data stream in. For data too big for one machine, factor each chunk separately, stack the small R factors together with each chunk's transformed response, and factor once more. In exact arithmetic this gives the same least-squares fit as one huge QR. Removing a row, downdating, is possible but less stable, the numerical cousin of chapter eleven's deletion formula.

The theory is James Wilkinson's backward error analysis. Householder QR is backward stable: what it computes is the exact least squares solution for data perturbed by a few units of rounding error. The forward error is then bounded by the condition number times machine epsilon, plus a second term with the condition number squared, multiplied by how large the residuals are compared with the fit. Machine epsilon is about ten to the minus seven in single precision and two times ten to the minus sixteen in double. A good fit alone does not make the squared-condition term small: Longley's enormous condition number makes this worst-case bound very pessimistic. Observed accuracy depends on directional sensitivity and the actual rounding errors, and must be measured against the certified answer.

Sensitivity guides, compared with a seeded experiment. Build designs with condition numbers from ten to a trillion. Score each floating-point answer against a ninety-digit least-squares solution of the exact rounded inputs, not the original generating coefficients. For near-exact fits the QR results roughly follow the one-digit-per-power guide, with variation across designs. The normal equations degrade faster and can fail to factor or solve. Failed solves receive zero digits and are recorded separately. With nonzero residuals, sensitivity can include a squared-condition term, so even backward-stable QR can lose accuracy much faster. Badly conditioned problems with poor fits are hard for every method. The dashed guides have slopes minus one and minus two.

The practical rules. Never invert X transpose X, and don't form it at all if you can avoid it. Centre and scale the predictors: Longley's condition number falls from five billion to a hundred and eleven, and even the single-precision normal equations recover three or four digits. Check the condition number and the variance inflation factors before trusting printed digits. And remember that single and even half precision are back, on the graphics processors used for machine learning: Longley's lesson is current.

Numbers: digits vs κ: slopes −1 (QR) and −2 (normal equations)

11InfluencePractice4 min

How much does one observation matter? Deleting it changes the coefficients by a formula that needs no refit: X transpose X inverse times x i, times its residual, divided by one minus its leverage. It follows from Sherman–Morrison, provided the deleted design remains full rank, equivalently leverage is below one. DFBETAS scales this by the deleted-fit residual standard deviation and the coefficient's full-design inverse-Gram factor. Part 12's Cook's distance summarizes the change in all the coefficients at once: large residual times large leverage. A common flag for DFBETAS is two over root n.

First, leverage, the diagonal of the hat matrix. With an intercept it is one over n plus the squared Mahalanobis distance of x i from the centre of the predictors, scaled by n minus one: leverage is distance in x, measured in the predictors' own covariance. The leverages add up to p, the trace of a projection, so their average is p over n. Under a correct mean with uncorrelated homoskedastic errors, a residual's variance is one minus leverage times sigma squared, which is why chapter four's small-sample corrections divide by it.

Hubble's nebulae, in order of distance, with each one's DFBETAS for the slope. The dashed lines are the two over root twenty-four flag. The most influential is a nebula at two megaparsecs moving at only five hundred kilometres per second, at the far edge of the data with a large negative residual. Remove it and the slope rises from four hundred and fifty-four to five hundred and four. The points at either end have the leverage: the slow far one, and the two nearest, which recede surprisingly fast, both hold the slope down. Influence isn't a reason to delete a point; it's a reason to check it.

The deletion formula gives every leave-one-out fit from a single fit. Their spread is Part 16's jackknife variance. For Hubble's slope the classical standard error is seventy-five, the jackknife's eighty-one, and HC three's eighty-two. That's no coincidence: HC three is the jackknife variance, up to a factor of n minus one over n and the centring. Chapter four's best formula and Part 16's resampling turn out to be one idea.

Leave-one-out has a blind spot. Twenty ordinary points and three outliers sitting together far to the right. With all twenty-three, the slope is flat. Delete one outlier and the other two hold the line almost where it was: the slope barely moves. Delete all three and it jumps to point four six. Each outlier's Cook's distance is below the usual cut-off of one, because each is masked by its neighbours. Group diagnostics can reveal this masking. Robust methods differ: ordinary residual-based M-estimators need not resist high-leverage groups.

Leverage is an unusual x; a large residual is an unusual y; influence combines residual size, leverage and coefficient direction; neither component must cross an arbitrary high threshold. Look at the influential points, refit without them, and if the conclusion changes, say so. Part 30 distinguishes residual-robust fits from methods designed to resist leverage contamination. And the deletion change, scaled up by n, is a first look at the influence function, which Parts 30 and 49 build into a theory of every estimator.

Numbers: 454 → 504; jackknife 80.5, HC3 82.3; masking −0.07 → −0.01 → 0.46

Recap, problems, and the road aheadAll tracks3 min

Part twenty-three in fourteen lines. Longley's data defeated the normal equations: no correct digits in single precision, against twelve for QR in double. Part 12's guarantees rested on a true linear mean, equal independent errors, exact predictors and exact arithmetic. Every linear question is C beta equals d, with one F-test. Generalized least squares whitens and then fits. With autocorrelated errors, the naive standard error covered forty-eight percent. HC estimators address uneven noise under regularity conditions; the wild bootstrap performed better in our small-sample experiment. Clustering greatly inflated uncertainty, approximately as the Moulton heuristic suggested. The Board assesses eight-school bootstrap inference conditionally on observing both treatment arms. A wrong line still estimates the best linear predictor, whose value depends on who is sampled. Classical error in a single regressor attenuates its slope, and Hubble's data give three different answers. Quantile regression shows the whole fan of a distribution; B-splines make curves into linear models. Householder's mirrors avoid ever forming X transpose X. And the deletion formula measures influence and gives the jackknife for free.

Where it comes back. Part 24's generalized estimating equations put chapter five's clusters into generalized linear models. Part 25 models the clusters instead of correcting for them. Part 29 penalizes splines rather than choosing knots. Part 30 builds robust regression and influence functions. Part 32 fits linear models with more predictors than observations. Part 37 runs difference-in-differences with few clusters. Part 41 treats measurement error in full. And Part 59 returns to the minimum-norm solution, when least squares interpolates.

Six problems, with full solutions in the README. The two forms of the F statistic; Moulton's factor; attenuation, and what it does to the intercept; why HC two is unbiased under equal variances; the deletion formula; and the best linear predictor of x squared. Pause here if you want to try them.

The books this part follows: Weisberg's Applied Linear Regression, Cameron and Trivedi's Microeconometrics, Koenker's Quantile Regression, and Golub and Van Loan's Matrix Computations; with the papers from Aitken and Hubble to Buja and his colleagues.

Twenty-three parts of sixty-five. The linear model now has uncertainty methods for uneven noise, clustering and approximation error, with explicit conditions and finite-sample checks. Next, outcomes that are not normal at all: counts, proportions, yes-or-no answers. In 1972 John Nelder and Robert Wedderburn showed that one algorithm fits them all. Part 24: generalized linear models.

Where it goes next. Working correlations and GEE follow in Part 24; random intercepts model the clusters in Part 25; penalized splines are Part 29, robust regression and influence functions Part 30, the lasso when p > n Part 32, few-cluster difference-in-differences Part 37 and measurement error in full Part 41.

Key results

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

The sandwich frame\(\displaystyle \operatorname{Var}(\hat\beta\mid X)=(X^\top X)^{-1}X^\top\operatorname{Var}(\varepsilon)\,X\,(X^\top X)^{-1}\)
The general linear hypothesis\(\displaystyle F=\frac{(C\hat\beta-d)^\top\bigl[C(X^\top X)^{-1}C^\top\bigr]^{-1}(C\hat\beta-d)}{q\,s^2}=\frac{(\mathrm{RSS}_0-\mathrm{RSS})/q}{\mathrm{RSS}/(n-p)}\sim F_{q,\,n-p}\)
Aitken's GLS\(\displaystyle \hat\beta_{\mathrm{GLS}}=(X^\top\Omega^{-1}X)^{-1}X^\top\Omega^{-1}y,\qquad\allowbreak \operatorname{Var}(\varepsilon)=\sigma^2\Omega\)
Moulton's factor\(\displaystyle \frac{\operatorname{Var}_{\text{true}}(\hat\beta)}{\operatorname{Var}_{\text{iid}}(\hat\beta)}=1+(m-1)\rho\quad\allowbreak \text{(clusters }\allowbreak \text{of }\allowbreak \text{size } m\text{, }\allowbreak \text{regressor }\allowbreak \text{constant }\allowbreak \text{within }\allowbreak \text{clusters)}\)
Attenuation\(\displaystyle w=x+u:\qquad\allowbreak \hat\beta_w\xrightarrow{p}\lambda\beta,\qquad\allowbreak \lambda=\frac{\sigma_x^2}{\sigma_x^2+\sigma_u^2}\)
The deletion formula\(\displaystyle \hat\beta_{(i)}=\hat\beta-\frac{(X^\top X)^{-1}x_i\,e_i}{1-h_{ii}}\)

Try it

Lab 23 · Moulton's factor, and cluster-robust errors with few clusters

Simulate pupils in schools with an intraclass correlation of 0.15 and a programme assigned by school, and compare the estimate's true spread with the iid and the cluster-robust (CR1) standard errors, first with forty schools and then with eight.

Figure produced by Lab 23: Moulton's factor, and cluster-robust errors with few clusters
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.stats.labs 23 needs numpy, scipy, matplotlib · download lab23.py · source on GitHub
Moulton's factor 1 + (m - 1) rho     5.35   (SE ratio 2.31)
40 schools: true sd of the estimate  0.1353   iid SE 0.0575   CR1 SE 0.1310
40 schools: true sd / iid SE         2.35   (Moulton 2.31)
40 schools: 95% interval covers      iid 60.7%   CR1 with t(G-1) 94.2%
8 schools: true sd of the estimate   0.3066   iid SE 0.1266   CR1 SE 0.2673
8 schools: true sd / iid SE          2.42   (Moulton 2.31)
8 schools: 95% interval covers       iid 59.0%   CR1 with t(G-1) 92.2%

Ignoring the schools understates the standard error by the square root of Moulton's factor; the cluster-robust error repairs it with forty schools and is itself too small with eight.
The code (70 lines; it asserts its own result)
"""Lab 23: assign a programme by school, and compare the iid and the cluster-robust standard errors."""

import numpy as np
from scipy import stats

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

TITLE = "Moulton's factor, and cluster-robust errors with few clusters"
GOAL = ("Simulate pupils in schools with an intraclass correlation of 0.15 and a programme assigned by school, and "
        "compare the estimate's true spread with the iid and the cluster-robust (CR1) standard errors, first with "
        "forty schools and then with eight.")
TASKS = [
    "Assign the programme pupil by pupil instead of school by school. What is Moulton's factor now, and who covers?",
    "Make the school sizes unequal (say 10 to 90 pupils). Does CR1 with eight schools get better or worse?",
    "Add ols.wild_cluster_boot for the eight-school case and compare its rejection rate under the null with CR1's.",
]


def study(G, m, rho, reps, rng):
    """reps data sets: G schools of m pupils, half the schools treated (true effect 0), unit total variance."""
    school = np.repeat(np.arange(G), m)
    treat = (school < G // 2).astype(float)
    X = ols.design(treat)
    tq = stats.t.ppf(0.975, G - 1)
    est, se_i, se_c = np.empty(reps), np.empty(reps), np.empty(reps)
    for r in range(reps):
        y = np.sqrt(rho) * rng.standard_normal(G)[school] + np.sqrt(1 - rho) * rng.standard_normal(G * m)
        f = ols.fit(X, y)
        est[r], se_i[r] = f.coef[1], f.se()[1]
        se_c[r] = np.sqrt(ols.cluster_cov(f, school)[1, 1])
    return dict(est=est, sd=est.std(), se_i=se_i.mean(), se_c=se_c.mean(),
                cov_i=np.mean(np.abs(est) < stats.t.ppf(0.975, G * m - 2) * se_i), cov_c=np.mean(np.abs(est) < tq * se_c))


def run(seed=0):
    rng = np.random.default_rng(seed)
    m, rho = 30, 0.15
    factor = ols.moulton(m, 1.0, rho)  # the regressor is constant within schools: rho_x = 1
    big, small = study(40, m, rho, 600, rng), study(8, m, rho, 1500, rng)
    lab = labs.Lab()
    lab.row("Moulton's factor 1 + (m - 1) rho", f"{factor:.2f}   (SE ratio {np.sqrt(factor):.2f})")
    for name, r in (("40 schools", big), ("8 schools", small)):
        lab.row(f"{name}: true sd of the estimate", f"{r['sd']:.4f}   iid SE {r['se_i']:.4f}   CR1 SE {r['se_c']:.4f}")
        lab.row(f"{name}: true sd / iid SE", f"{r['sd'] / r['se_i']:.2f}   (Moulton {np.sqrt(factor):.2f})")
        lab.row(f"{name}: 95% interval covers", f"iid {r['cov_i']:.1%}   CR1 with t(G-1) {r['cov_c']:.1%}")
    lab.note = ("Ignoring the schools understates the standard error by the square root of Moulton's factor; the "
                "cluster-robust error repairs it with forty schools and is itself too small with eight.")
    assert abs(big["sd"] / big["se_i"] / np.sqrt(factor) - 1) < 0.12, "the iid SE is off by Moulton's factor"
    assert big["cov_i"] < 0.72 and small["cov_i"] < 0.75, "iid intervals are broken"
    assert abs(big["se_c"] / big["sd"] - 1) < 0.1 and abs(big["cov_c"] - 0.95) < 0.03, "CR1 works with 40 clusters"
    assert small["se_c"] / small["sd"] < 0.97 and small["cov_c"] < 0.95, "CR1 is too small with 8"

    fig, ax = labs.figure(2, size=(11, 4.2))
    bins = np.linspace(-4 * big["sd"], 4 * big["sd"], 50)
    ax[0].hist(big["est"], bins=bins, density=True, color=labs.BLUE, alpha=0.6, label="600 estimates (true effect 0)")
    for se, color, name in ((big["se_i"], labs.RED, "iid SE"), (big["se_c"], labs.GREEN, "CR1 SE")):
        ax[0].plot(bins, stats.norm.pdf(bins, 0, se), color=color, label=f"normal with the {name}")
    ax[0].set(title="Forty schools: which SE matches the spread?", xlabel="estimated programme effect (SD units)",
              ylabel="density")
    ax[0].legend(loc="upper left", fontsize=8)
    names = ["iid\n40 schools", "CR1\n40 schools", "iid\n8 schools", "CR1\n8 schools"]
    vals = [big["cov_i"], big["cov_c"], small["cov_i"], small["cov_c"]]
    bars = ax[1].bar(names, vals, color=[labs.RED, labs.GREEN, labs.RED, labs.GREEN], width=0.6)
    for b, v in zip(bars, vals):
        ax[1].text(b.get_x() + b.get_width() / 2, v - 0.07, f"{v:.1%}", ha="center", fontsize=10, color=labs.BG, fontweight="bold")
    ax[1].axhline(0.95, color=labs.MUTED, ls="--", lw=1)
    ax[1].set(title="Coverage of nominal 95% intervals", ylabel="coverage", ylim=(0, 1.1))
    lab.fig = fig
    return lab

Now change it

  1. Assign the programme pupil by pupil instead of school by school. What is Moulton's factor now, and who covers?
  2. Make the school sizes unequal (say 10 to 90 pupils). Does CR1 with eight schools get better or worse?
  3. Add ols.wild_cluster_boot for the eight-school case and compare its rejection rate under the null with CR1's.

Problems, with solutions

Try each problem before opening its solution.

1. Two forms of F. Show that \(F = (\mathrm{RSS}_0 - \mathrm{RSS})/(q s^2)\) equals the Wald form \((C\hat\beta - d)^\top[C(X^\top X)^{-1}C^\top]^{-1}(C\hat\beta - d)/(q s^2)\).

Solution

Assume X has full column rank, n > p, and C has q independent rows. The restricted estimator is β̃ = β̂ − (X'X)⁻¹C'[C(X'X)⁻¹C']⁻¹(Cβ̂ − d), by Lagrange. Then y − Xβ̃ = e + X(β̂ − β̃), with X'e = 0, so RSS₀ = RSS + (β̂ − β̃)'X'X(β̂ − β̃). Substituting, (β̂ − β̃)'X'X(β̂ − β̃) = (Cβ̂ − d)'[C(X'X)⁻¹C']⁻¹(Cβ̂ − d) = Q. Dividing by qs² gives the same F.

2. Moulton's factor. Equicorrelated errors within clusters of size \(m\), a cluster-level regressor: derive Moulton's factor \(1 + (m - 1)\rho\).

Solution

Take clusters of size m with Var ε = σ²[(1 − ρ)I + ρ11'] within each cluster, and a regressor x constant within clusters.

  • The iid variance. Var(β̂) = σ²/Σ(x − x̄)².
  • The true variance. With x constant within a cluster, the slope's numerator Σᵢ(xᵢ − x̄)εᵢ is a sum over clusters of (x_g − x̄) times the cluster's error sum, and Var(Σᵢ∈g εᵢ) = mσ²(1 + (m − 1)ρ). So Var(β̂) = σ²(1 + (m − 1)ρ)/Σᵢ(xᵢ − x̄)².
  • The ratio. 1 + (m − 1)ρ. The familiar extension multiplying by a regressor ICC is an approximation under suitable exchangeability and balance; it is not exact for arbitrary adjusted designs or unequal cluster sizes.

3. Attenuation. With \(w = x + u\), show \(\hat\beta_w \to \beta\lambda\). What happens to the intercept?

Solution

In a simple linear conditional-mean model with finite variances and mean-zero independent classical measurement error, β̂_w → Cov(w, y)/Var(w) = Cov(x + u, α + βx + ε)/(σ²ₓ + σ²ᵤ) = βσ²ₓ/(σ²ₓ + σ²ᵤ) = βλ. The intercept converges to ȳ − βλ x̄ = α + β(1 − λ)μₓ: it absorbs what the slope lost, so it is biased unless μₓ = 0.

4. Residual variances. Show \(E\,e_i^2 = (1 - h_{ii})\sigma^2\) under homoskedasticity, so HC2 is unbiased there.

Solution

With a correct mean E(ε | X) = 0, full-rank X, and hᵢᵢ < 1, e = (I − H)ε with H = X(X'X)⁻¹X' symmetric and idempotent. Under Var ε = σ²I, Var e = σ²(I − H)(I − H)' = σ²(I − H), so E eᵢ² = σ²(1 − hᵢᵢ). Hence eᵢ²/(1 − hᵢᵢ) has expectation σ², and the HC2 meat Σ eᵢ²xᵢxᵢ'/(1 − hᵢᵢ) has expectation σ²X'X, so the HC2 covariance estimator is unbiased for the classical covariance. This does not imply exact t coverage.

5. The deletion formula. Derive \(\hat\beta - \hat\beta_{(i)} = (X^\top X)^{-1}x_i e_i/(1 - h_{ii})\) from Sherman–Morrison.

Solution

Assume the design remains full rank after deletion (hᵢᵢ < 1). Write A = X'X. Sherman–Morrison gives (A − xᵢxᵢ')⁻¹ = A⁻¹ + A⁻¹xᵢxᵢ'A⁻¹/(1 − hᵢᵢ). Then β̂₍ᵢ₎ = (A − xᵢxᵢ')⁻¹(X'y − xᵢyᵢ). Expanding and using xᵢ'β̂ = yᵢ − eᵢ, we get β̂₍ᵢ₎ = β̂ − A⁻¹xᵢeᵢ/(1 − hᵢᵢ).

6. The best linear predictor of x². \(x \sim N(0, 1)\), \(y = x^2\): find \(\beta^*\), and the true and classical variances of the OLS slope.

Solution

With x ~ N(0, 1) and y = x², β* = (E xx')⁻¹E xy with x = (1, x)'. E xx' = I, and E xy = (E x², E x³) = (1, 0), so β* = (1, 0): a flat line at 1. The residual is r = x² − 1.

  • The true variance of the OLS slope. About E[x²r²]/(n (E x²)²) = E[x²(x² − 1)²]/n = (15 − 6 + 1)/n = 10/n.
  • The classical variance. About E[r²]/(n E x²) = 2/n.
  • The consequence. The classical SE is √5 ≈ 2.2 times too small. A nominal ±1.96 SE interval is then really ±0.88 true SEs, which covers about 62%; the simulation, which adds independent noise of variance 0.09, gave 61%. With that noise the asymptotic variances are 10.09/n and 2.09/n; the displayed analytic toy is the noiseless limit.

Notes and sources

Where it comes back

Idea Returns in
GEE and working correlations 24
random intercepts: the clusters modelled 25
penalized splines and smoothing parameters 29
robust regression; influence functions 30
the lasso when p > n 32
difference-in-differences with few clusters 37
measurement error in full 41
minimum-norm interpolation 59
the Coverage Board every part; 65

Glossary

  • Condition number κ; machine epsilon; backward stability: σ_max/σ_min; the relative rounding unit; the exact answer to a nearby problem.
  • Normal equations; Cholesky; Householder QR; Givens rotation; SVD: X'Xb = X'y; LL' factorization; orthogonal reflections to triangular form; plane rotations for updating; the singular value decomposition.
  • General linear hypothesis; F-test; Scheffé intervals: Cβ = d; the quadratic form over qs²; simultaneous intervals for every contrast in a specified coefficient subspace.
  • GLS; WLS; whitening; FGLS; Prais–Winsten; Cochrane–Orcutt; Durbin–Watson: least squares after undoing a known covariance; the diagonal case; multiplying by L⁻¹; with an estimated covariance; AR(1) recipes; the lag-one test.
  • Heteroskedasticity-consistent SEs (HC0–HC3); leverage; wild bootstrap: sandwich meats from squared residuals, with leverage corrections; hᵢᵢ; resampling by flipping residuals.
  • Cluster-robust SE (CR1); Moulton factor; ICC; wild cluster bootstrap; Webb weights: sums of scores within clusters; the variance inflation 1 + (m − 1)ρₓρ_ε; the within-cluster correlation; flipping whole clusters' residuals; a six-point weight distribution.
  • Best linear predictor; models as approximations; pairs bootstrap: the population least squares line; inference for β* under a wrong model; resampling (x, y) together.
  • Errors in variables; reliability; attenuation; Deming regression; total least squares; SIMEX: noisy predictors; σ²ₓ/Var(w); the slope's shrinkage; fitting with both error variances; orthogonal fitting; simulate and extrapolate.
  • Quantile regression; check loss; sparsity; quantile treatment effect: modelling F⁻¹(τ | x); ρ_τ; the inverse density at the quantile; shifts in a distribution's quantiles.
  • Basis expansion; B-spline; truncated power basis; natural spline; tensor product: curves as linear models; de Boor's local bumps; (x − k)₊³; linear beyond the boundary; products of bases.
  • DFBETAS; Cook's distance; masking; jackknife: deletion changes in SEs; their summary; outliers hiding each other; leave-one-out variance.

Sources

  • History.
    • J. Longley, JASA 62 (1967); NIST Statistical Reference Datasets, "Longley".
    • E. Hubble, PNAS 15 (1929).
    • A. Aitken, Proc. Roy. Soc. Edinburgh 55 (1935).
    • A. Householder, J. ACM 5 (1958); G. Golub, Numer. Math. 7 (1965).
  • Methods.
    • H. Scheffé, Biometrika 40 (1953); U. Grenander & M. Rosenblatt (1957).
    • D. Cochrane & G. Orcutt, JASA 44 (1949); S. Prais & C. Winsten (1954); J. Durbin & G. Watson, Biometrika 37 (1950).
    • F. Eicker, Ann. Math. Stat. 34 (1963); H. White, Econometrica 48 (1980); J. MacKinnon & H. White, J. Econometrics 29 (1985); T. Breusch & A. Pagan, Econometrica 47 (1979); R. Koenker, J. Econometrics 17 (1981), studentized test; W. Newey & K. West, Econometrica 55 (1987).
    • B. Moulton, J. Econometrics 32 (1986); K.-Y. Liang & S. Zeger, Biometrika 73 (1986); M. Arellano, Oxford BES 49 (1987).
    • A. C. Cameron, J. Gelbach & D. Miller, REStat 90 (2008) and JBES 29 (2011); M. Webb, Queen's WP 1315 (2014); A. Abadie, S. Athey, G. Imbens & J. Wooldridge, QJE 138 (2023).
    • A. Buja et al., Stat. Sci. 34 (2019); D. Freedman, Ann. Stat. 9 (1981).
    • J. Cook & L. Stefanski, JASA 89 (1994); W. E. Deming, Statistical Adjustment of Data (1943).
    • R. Koenker & G. Bassett, Econometrica 46 (1978); J. Powell (1991); V. Chernozhukov, I. Fernández-Val & A. Galichon, Econometrica 78 (2010).
    • C. de Boor, J. Approx. Theory 6 (1972); D. Belsley, E. Kuh & R. Welsch, Regression Diagnostics (1980).
  • Books.
    • S. Weisberg, Applied Linear Regression (4th ed., 2014).
    • A. C. Cameron & P. K. Trivedi, Microeconometrics (2005).
    • R. Koenker, Quantile Regression (2005).
    • G. Golub & C. Van Loan, Matrix Computations (4th ed., 2013).
About this partfrom its README

Part 23 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the third part of Stage III, Master's. Part 12 derived least squares under four quiet assumptions: a linear mean, equal and independent errors, exactly measured predictors, and exact arithmetic. This part drops each in turn. Each time it asks what the estimator still estimates and how to keep its standard error honest.

It opens with James Longley's 1967 test of the era's regression programs. His sixteen years of US employment data have predictors correlated up to 0.995 and variance inflation factors up to 1,789. Against NIST's certified coefficients:

  • the normal equations in single precision get no digit right (Cholesky fails, and four signs are wrong);
  • QR in single precision gets 5–6 digits;
  • the normal equations in double precision get 7–8;
  • QR in double precision gets 11–13.

κ(X) is 4.9 × 10⁹ and κ(X'X) is 2.4 × 10¹⁹. Centring and scaling brings κ down to 111.

From there the part covers:

  • The upgrade. The sandwich (X'X)⁻¹X'Var(ε)X(X'X)⁻¹ as the frame for everything; the Gauss–Markov proof, and where it uses Var ε = σ²I.
  • The general linear hypothesis.
    • Cβ = d. The F-test is derived as a quadratic form, as two nested fits (Cochran), and in R² form.
    • On 400 of the World's families (standardized heights) the coefficients are 0.326 and 0.344, against a truth of 0.35 each. Equal parents: F = 0.079, p = 0.78. Both equal to 0.35: p = 0.85. Both zero: F = 61.9.
    • On the fixed family design with 2,000 fresh iid Gaussian response vectors under the null, F rejects 5.3% at 5%.
    • The joint confidence ellipse, and Scheffé's multiplier (1.97 → 2.45).
  • GLS and Aitken (1935).
    • Whitening by Cholesky; WLS for group means.
    • A trend with AR(1) errors (ρ = 0.8, n = 60, 2,000 series). Slope SDs: OLS 1.99, GLS 1.87, Prais–Winsten 1.89 (Grenander–Rosenblatt). The naive SE averages only 0.65.
    • Coverage: naive 47.7%, Newey–West 68.2%, FGLS 83.8%, GLS with ρ known 94.8%.
    • Durbin–Watson = 0.380 (OLS residual lag-one estimate 0.815; iterated PW estimate 0.820) for the example, and Cochrane–Orcutt.
  • Heteroskedasticity theory.
    • Eicker–Huber–White, and testing (Breusch–Pagan) versus always-robust; where uneven noise comes from.
    • Leverage shrinks residuals, which motivates HC1–HC3.
    • With n = 30 and SD ∝ x (4,000 samples), coverage is: classical 76.1%, HC0 81.5%, HC1 82.9%, HC2 86.1%, HC3 90.6%, and the wild bootstrap-t 93.4% from 1,000 samples. Formula and bootstrap denominators are recorded separately. Three Board rows.
  • Clustering.
    • Forty of the World's 400 schools (2,452 pupils); the tutoring programme was assigned by school.
    • The estimate is 27.5 points (truth 20), with iid SE 3.65 against CR1 SE 10.04.
    • Moulton's equal-size exchangeable approximation gives 1 + (61.3 − 1) × 1 × 0.114 = 7.9 and SE ratio 2.81; the observed ratio is 2.75. Unequal sizes and SES adjustment make this a heuristic.
    • CR1; few clusters; the restricted wild cluster bootstrap with Webb weights; which level to cluster at, two-way clustering, and random intercepts as GLS. Four Board rows.
  • Models as approximations (Buja et al. 2019).
    • The best linear predictor β*. The World's income–age BLP slope is $274 a year, but $1,150 for adults aged 18–40 inclusive.
    • A quadratic truth with x random: the classical SE covers 61%, HC3 94%.
    • Residual, pairs and wild bootstraps.
  • Errors in variables.
    • Attenuation λ = σ²ₓ/(σ²ₓ + σ²ᵤ). The World's fathers with reliability 0.6: the slope falls from 0.365 to 0.216 (predicted 0.235). The naive CI covers 0.4%.
    • Hubble's 24 nebulae: velocity on distance 454, reverse regression 729, Deming 582 km/s/Mpc. Today's H₀ is about 70: a calibration error that no regression fixes.
    • SIMEX gives 0.312; errors in y; the cures.
  • Quantile regression (Koenker & Bassett 1978).
    • 1,000 of the World's working adults: income-on-age slopes of 0.22, 0.27, 0.47, 0.63 and 1.14 thousand a year at τ = 0.1–0.9, against 0.41 for OLS.
    • Kernel-bread, empirical-score sandwich SEs are compared with 100 pairs-bootstrap refits per quantile; agreement is approximate, with a notable difference at τ = 0.1. The median's slope (SE 0.082) is more precise than the mean's (0.134).
    • The location–scale fan, quantile treatment effects, and Engel's law (0.40 to 0.69).
  • Splines and bases.
    • Truncated powers against B-splines (κ 3.2 × 10⁷ vs 5.7); the B-splines' partition of unity.
    • Log income on age with 1, 3, 6 and 20 knots. Each CV fold learns its distinct interior knots from training predictors only. Ten-fold CV is flat (minimum at 8 requested knots); the heuristic one-SE rule chooses 0.
    • Interactions and tensor products; natural splines.
  • Numerics.
    • Householder's mirror and the column-by-column triangularization.
    • Cholesky against QR against SVD, and Givens updating.
    • Backward stability and worst-case forward sensitivity. The seeded digits experiment uses a 90-digit least-squares reference for the exact supplied binary64 inputs, including nonzero-residual cases. One- and two-digit-per-power lines are guides, not universal predictions; failed normal-equation solves are recorded and score zero.
  • Influence.
    • Leverage as Mahalanobis distance; the deletion formula; DFBETAS. Hubble's most influential nebula (2 Mpc, 500 km/s): the slope goes 454 → 504 without it.
    • The jackknife SE is 80.5, against 75.3 classical and 82.3 HC3.
    • Masking: three clustered outliers each have Cook's D < 1. Deleting one moves the slope −0.07 → −0.01; deleting all three gives 0.46.

Every number on screen is computed in compute.py:

  • Longley's data, NIST's certified values and Hubble's nebulae are the Museum's;
  • families, incomes and schools are the World's;
  • the rest are seeded simulations.

Built in this part:

  • statkit.ols II (explainer/stats/kit/ols.py), checked in tests/test_stats_kit_ols2.py:
    • normal equations and QR in any precision, and correct digits;
    • Householder QR written out;
    • the general linear hypothesis;
    • GLS, AR(1) covariance and Prais–Winsten, and Newey–West;
    • cluster-robust covariance, Moulton's factor, the ICC, and the restricted wild (cluster) bootstrap with Rademacher or Webb weights;
    • Deming and total least squares;
    • DFBETAS and jackknife coefficients;
    • truncated-power and B-spline bases;
    • quantile-regression sandwich SEs.
  • The digits board (DigitsBoard in explainer/stats/viz.py): correct digits per coefficient per method.
  • The World: the schools block, with 400 schools, about 24,000 pupils, a school-level programme (SCHOOL_PROGRAMME_EFFECT = 0.20 SD), school effects (SD 0.35) and SES. It is reused in Parts 25 and 26.
  • The Museum: longley(), LONGLEY_CERTIFIED, and HUBBLE_1929 / hubble().

The Coverage Board gains eight rows:

Method Setting Reps Achieved Verdict
iid SE, school programme 40 schools, pupils clustered 1,000 49.1% broken
cluster-robust SE (CR1) 40 schools 1,000 95.1% kept
cluster-robust SE (CR1) 8 schools, both arms observed, t₇ 500 88.6% broken
wild cluster bootstrap 8 schools, both arms observed, Webb weights 500 96.0% kept
naive slope, noisy regressor reliability 0.6, n = 500 1,000 0.4% broken
HC0 SE heteroskedastic, n = 30 1,000 81.1% broken
HC3 SE heteroskedastic, n = 30 1,000 90.0% broken
wild bootstrap-t heteroskedastic, n = 30 1,000 94.4% kept
Chapter notes
# Chapter Numbers
0 Longley's test, 1967 digits 0 / 5–6 / 7–8 / 11–13; κ 4.9e9, κ(X'X) 2.4e19; scaled κ 111
1 Upgrade: what Part 12 assumed the sandwich; Gauss–Markov's use of σ²I
2 The general linear hypothesis 0.326, 0.344; F 0.079 (p 0.78), 0.162 (p 0.85), 61.9; conditional Gaussian null rejection 5.3%; Scheffé 2.45
3 GLS and Aitken SD 1.99 / 1.87 / 1.89; naive SE 0.65; coverage 47.7 / 68.2 / 83.8 / 94.8%; DW 0.380
4 Heteroskedasticity theory coverage 76.1 → 90.6 (HC3), wild 93.4%; Board 81.1 / 90.0 / 94.4%
5 Clustering 27.5 (truth 20); SE 3.65 vs 10.04; Moulton 7.9, ratio 2.75; Board 49.1 / 95.1 / 88.6 / 96.0%
6 Models as approximations BLP 0.27 vs 1.15 (ages 18–40); toy 61% vs 94%
7 Errors in variables 0.365 → 0.216 (pred. 0.235); Board 0.4%; Hubble 454 / 729 / 582; SIMEX 0.312
8 Quantile regression slopes 0.22 → 1.14; SEs 0.06 → 0.32; Engel 0.40–0.69
9 Splines and bases κ 3.2e7 vs 5.7; CV flat, min 8 knots
10 Numerics digits vs κ: slopes −1 (QR) and −2 (normal equations)
11 Influence 454 → 504; jackknife 80.5, HC3 82.3; masking −0.07 → −0.01 → 0.46
12 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Longley (1967). Ill-conditioned data and wrong digits; QR vs normal equations (computed).
  2. Upgrade card (Part 12).
  3. The general linear hypothesis. Cβ = d; the F-test derived; Cochran's theorem (Part 4) in full.
  4. GLS and Aitken (1935). Feasible GLS; the efficiency of OLS when GLS is right.
  5. Heteroskedasticity theory. Eicker–Huber–White; HC0–HC3 (MacKinnon & White 1985); leverage and small samples.
  6. Clustering. The Moulton factor; cluster-robust SEs (Liang & Zeger 1986; Arellano 1987); few clusters and the wild cluster bootstrap (Cameron, Gelbach & Miller 2008) (Board).
  7. Models as approximations (Buja et al. 2019). The best linear predictor; the sandwich as its correct SE.
  8. Errors in variables. Attenuation derived; Deming regression and total least squares; Hubble (1929).
  9. Quantile regression (Koenker & Bassett 1978). Check loss, LP (Part 21); asymptotics.
  10. Splines and bases. Regression splines; knot choice; the bridge to Part 29.
  11. Numerics. Householder QR, Cholesky, SVD; condition numbers squared.
  12. Influence theory. DFBETAS; the jackknife as influence (Part 16).
  13. Outro.

Built: statkit.ols (II): wild bootstrap, quantile regression.

Build the film

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

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

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