SStatistics, Built

Stage I · Bachelor's: Foundations

Part 4 of 65

Matrices for Statistics

Bachelor'sstarts at this level50 min of film14 chaptersprerequisites: none

What matrix facts does statistics run on?

The part opens with the hat matrix of a line fitted to forty of the World's families. It is symmetric and idempotent, so its eigenvalues can only be zero and one: two ones, thirty-eight zeros, and a residual sum of squares that averages n minus p times the noise variance, not n. From that fact the toolkit is laid out. A sample is a vector and centring is a projection; the trace gives the expectation of any quadratic form; the spectral theorem draws the ellipses of a covariance matrix and the SVD gives the best low-rank approximation. Pseudoinverses, Schur complements, Woodbury, Kronecker products and matrix calculus follow, each checked numerically. Quadratic forms in projections of normal vectors are chi-squared, which is where t and F come from. The part ends in floating point: the condition number of X'X is the square of X's, so the normal equations lose the digits that QR keeps.

What you need. A first course in linear algebra (vectors, matrices, rank, eigenvalues), or AI, Built Part 3.

Hook
the hat matrix's two eigenvalues
Mathematics
projections, idempotents, trace tricks, PSD order, spectral and SVD, Schur, Woodbury, Kronecker, matrix calculus, quadratic forms
Built
a projection lab

What you will be able to do

Bachelor's

  • Compute a projection matrix, check that it is symmetric and idempotent, and read degrees of freedom as its trace.
  • Explain why dividing a residual sum of squares by n underestimates the noise variance.
  • Read a covariance matrix as an ellipse: its axes are eigenvectors, its squared half-lengths eigenvalues.

Master's

  • Derive P = A(A'A)^-1 A', the expectation of a quadratic form, and the leave-one-out residual e_i / (1 - h_ii).
  • Use the Schur complement and Woodbury to invert in blocks, and matrix calculus to derive least squares and the Gaussian MLE of a covariance.
  • Prove that z'Pz is chi-squared with rank(P) degrees of freedom for standard normal z.

PhD

  • Prove Eckart-Young for the Frobenius norm and state Cochran's theorem with its rank condition.

Practice

  • Solve least squares by QR after centring and scaling, and never by inverting X'X.
  • Diagnose a loss of digits from a condition number, and compute a variance in two passes.

Contents

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

  1. 0The hat matrixBachelor's3 min
  2. 1Vectors as dataBachelor's4 min
  3. 2ProjectionsBachelor's4 min
  4. 3Trace tricksBachelor's4 min
  5. 4The spectral theoremBachelor's4 min
  6. 5Positive semidefinite matricesMaster's4 min
  7. 6The singular value decompositionBachelor's3 min
  8. 7Generalized inversesMaster's3 min
  9. 8Block matricesMaster's3 min
  10. 9Kronecker products and vecMaster's2 min
  11. 10Matrix calculusMaster's3 min
  12. 11Quadratic forms in normal vectorsMaster's5 min
  13. 12Conditioning and numericsPractice4 min
  14. Recap, problems, and the road aheadAll tracks3 min

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

Lecture

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

The hat matrixBachelor's3 min

Here's a matrix you'll meet in almost every part of this series. Forty of the World's families: the parents' average height across, the child's height up. Fit a straight line by least squares, which Part 12 will derive; each child gets a fitted value on the line. With two linearly independent design columns, stack the forty heights into a vector y. The fitted values are X times the fitted coefficients, and the coefficients turn out to be X transpose X inverse, X transpose, y. So the fitted values are one matrix times the data. Statisticians call it the hat matrix, H, because it puts the hat on y.

Here's H for the forty families, sorted by the parents' height. Each row says how a fitted value is built from all forty observed heights: families with similar parents get positive weight; distant families can receive negative weights. H has two properties that define it. It's symmetric, and it's idempotent: H times H is H. Fitting the fitted values changes nothing, because they're already on the line.

And idempotence forces something remarkable. If v is an eigenvector of H, with eigenvalue lambda, then H squared times v is lambda squared times v. But H squared is H, so lambda squared equals lambda: every eigenvalue is zero or one. Here are all forty. Two ones, one for each column of X, and thirty-eight zeros. The trace, the sum of the eigenvalues, counts the ones: two, the number of parameters.

Why should anyone care? The residuals are I minus H, times y, and I minus H is also a projection, with thirty-eight eigenvalues equal to one. Assume the mean lies in the fitted column space and errors are uncorrelated with common variance sigma squared. Simulate two thousand data sets with the same parents and independent normal errors, and measure the residual sum of squares each time. It averages sigma squared: n minus p, not n. So dividing the residual sum of squares by n underestimates the noise; dividing by n minus p is exactly right. That's what degrees of freedom are: the number of eigenvalues equal to one in the projection the residuals live in. One fact about one matrix, and out of it come the n minus one of the sample variance, the chi-squared distributions, regression and the analysis of variance.

What it does: 40 World families. H as a heat map; H² = H ⇒ eigenvalues 0 and 1; tr H = p. 2,000 simulated data sets: E RSS = (n − p)σ².; Numbers (computed): eigenvalues two 1s, 38 0s; RSS/σ² averages 37.95; RSS/n is 0.949σ² vs RSS/(n − p) 0.999σ²

1Vectors as dataBachelor's4 min

Part 1 had one idea that this whole part builds on. A sample of three heights is three numbers, and three numbers are one point in three-dimensional space: the first person's height along one axis, the second's along another, the third's up. Here it is, measured from a hundred and sixty centimetres. Forty families make one point in forty dimensions. We can't draw that, but nothing we do depends on drawing it: lengths, angles and projections work in forty dimensions exactly as they do in three. The inner product, the length and the angle are all a statistician needs: sums of squares are squared lengths, and Part 1 showed that correlation is the cosine of an angle.

Now the first projection. The diagonal line through the vector of all ones holds every sample in which everyone is the same height. Drop a perpendicular from the data onto it. The foot is the inner product with the ones vector, over its squared length, times the ones vector: the mean, repeated. As a matrix, that projection is one over n times the all-ones matrix J. What's left, the data minus its mean, is the residual, at right angles to the diagonal. Centring data is projecting it away from the ones vector.

This is our first upgrade: a result from an earlier part, made more general. Part 1 showed that correlation is the cosine of the angle between centred vectors, drawn with three people. We can now write the same geometry in any number of dimensions, because inner products and angles do. And one more fact comes with it. The slope of the regression of y on x is the coefficient of the projection of the centred y onto the centred x: the inner product over the squared length. Rewrite it with the cosine, and the slope is r times the ratio of the standard deviations, which is why Part 1 warned that correlation is not slope.

This is where n minus one comes from. The residual is at right angles to the ones vector, so it's trapped in a plane: the residuals always add to zero. In n dimensions that's a subspace of dimension n minus one. I minus one over n J is a projection too, onto that subspace, and its trace is n minus one. That's why the sample variance divides the squared length of the residual by n minus one: the residual has only n minus one dimensions to spread out in. Part 8 proves it's exactly unbiased, and the hat matrix's n minus p is the same idea with p columns instead of one.

With several variables, the data become a matrix. One row per person, one column per variable: height, weight, income. There are two ways to look at it, and statistics uses both. Read it by rows, and it's n points in p dimensions, a cloud of people, which is how Part 5 will picture it. Read it by columns, and it's p arrows in n dimensions, one per variable. In that picture the angle between two centred columns is their correlation, and regressing one variable on others is projecting one arrow onto the space of the others. Both views meet in one formula: centre each column, and the sample covariance matrix is X c transpose X c over n minus one. Every entry is an inner product of two columns.

What it does: A sample as a point in ℝⁿ; centring as projection onto 1 in the lab; why n − 1; the upgrade card for Part 1's r = cos θ, and slope = r s_y/s_x; the data matrix's two views.

2ProjectionsBachelor's4 min

Projecting onto a line is the simplest case. Statistics needs projections onto any subspace, spanned by the columns of a matrix A. The projection of y has to lie in the column space, so it's A times some vector b. And the residual has to be at right angles to every column, which is A transpose times the residual equal to zero. For linearly independent columns of A, solve: b is A transpose A inverse, A transpose y. These are the normal equations of least squares, named for the normal, the perpendicular. So the projection matrix is A, A transpose A inverse, A transpose: the hat matrix again. Multiply it by itself and the middle cancels, so it's idempotent; and it's symmetric. Those two properties define an orthogonal projection.

Here's the projection lab, the build of this part. The green plane is the column space of a three-by-two matrix A: every combination of its two columns. The white vector is the data, y. Its projection, blue, is the closest point of the plane, and the residual, red, stands at right angles to the plane. Turn the space and you can see the right angle from every side. Project the projection again, and nothing moves: it's already in the plane. Project the residual, and it vanishes. And because the angle is right, Pythagoras splits the squared length of the data into fitted and residual parts: the decomposition behind every analysis of variance.

Projections are easiest with orthonormal columns, and Gram–Schmidt makes them. Normalize the first column. From the second, subtract its projection onto the first, leaving the yellow part at right angles, and normalize that. The result is a factorization: A equals Q, with orthonormal columns, times R, upper triangular. With orthonormal columns the projection is just Q Q transpose: no inverse at all. That's not only elegant; chapter twelve shows it's how a computer should actually do least squares.

The eigenvalues of a projection now make geometric sense. Every vector already in the plane is left alone: eigenvalue one. Every vector at right angles to the plane is sent to zero: eigenvalue zero. So this projection's eigenvalues are one, one and zero, and its rank, the dimension of the plane, equals its trace. Ones on the subspace, zeros off it: that's all a projection is.

Projections onto nested subspaces give the analysis of variance its shape. For the hook's forty families, split the identity into three projections: onto the ones vector; onto the part of the column space of X perpendicular to it; and onto everything perpendicular to X. They're mutually perpendicular, and their ranks are one, one and thirty-eight. Apply them to the centred data, and Pythagoras splits its squared length in two: the part the regression line explains, and the residual. Those are the sums of squares of every ANOVA table. For the families, equals plus , and the share explained, R squared, is : parents' heights explain about a quarter of the variation in children's.

The diagonal of the hat matrix has a meaning of its own. The i-th fitted value puts weight h i i on its own observation: that's its leverage. Because H is a projection, every leverage lies between zero and one, and they add up to the trace, p, so they average p over n. For a straight line, the leverage is one over n plus the squared distance from the average x, as a share of the total. Families whose parents are unusually short or tall have the most leverage: they pull the fitted line toward themselves. Part 30 makes leverage and influence precise.

What it does: P = A(AᵀA)⁻¹Aᵀ derived; the lab; Pythagoras; Gram–Schmidt and QR; eigenvalues of a projection; ANOVA as nested projections; leverage.; Numbers (computed): 19.00 = 8.71 + 10.29; SS 3,736 = 946 + 2,790, R² = 0.253; leverages sum to 2

3Trace tricksBachelor's4 min

The trace, the sum of a matrix's diagonal, looks too simple to matter. It matters because of one identity. The trace of A B is a double sum of A i j times B j i. Swap the order of summation and it's the trace of B A, even when A and B are different shapes and A B is tiny while B A is big. So you can cycle the factors of a product inside a trace, though you can't shuffle them. And the trick that statisticians use daily: a quadratic form, x transpose A x, is a single number, so it's its own trace, and cycling turns it into the trace of A times x x transpose, a matrix we can take expectations of.

Here's that trick earning its keep. The expectation of a quadratic form is the expectation of a trace, and since trace and expectation are both linear, they swap. The expected outer product of x is its covariance matrix plus the mean's outer product. So the expected quadratic form is the trace of A Sigma plus mu transpose A mu, for any distribution with a covariance, normal or not. A Monte Carlo check with two hundred thousand draws differs by less than three hundredths. Put A equal to I minus H and Sigma equal to sigma squared times the identity, with the mean in the column space of X, and out comes the hook's result: the expected residual sum of squares is n minus p times sigma squared.

The same identity splits the error of any estimator. Let theta hat estimate a vector of parameters theta. Its expected squared error is the expected trace of an outer product. Apply the quadratic-form identity with the estimator's mean in place of mu, and it splits in two: the total variance of the estimator, plus its squared bias. Mean squared error is variance plus bias squared. Accepting a little bias to remove a lot of variance is the bias–variance trade-off, and it's behind ridge regression, shrinkage and most of modern statistics.

One more use. A projection can be diagonalized, with its eigenvalues, ones and zeros, on the diagonal. Cycle the orthogonal factors around, and the trace of the projection is the trace of the diagonal: the number of ones, which is its rank. And for the hat matrix there's an even quicker route. Cycle X to the end, and the trace of an n by n matrix becomes the trace of the p by p identity: p. Cycling the trace turns big questions into small ones.

Two numbers summarize a whole covariance matrix, and both come from its eigenvalues. The trace is the sum of the eigenvalues, so the trace of a covariance matrix is the total variance, summed over all directions. The determinant is their product, which Samuel Wilks called the generalized variance: it measures the volume of the cloud's ellipse. And the trace also gives the Frobenius norm, the matrix version of a sum of squares, which chapter six will use to measure the error of an approximation. For the four hundred families, both identities check exactly.

What it does: tr(AB) = tr(BA); E[xᵀAx] = tr(AΣ) + μᵀAμ (Monte Carlo); MSE = tr Cov + bias²; rank = trace; tr and det of Σ.; Numbers (computed): 13.456 exact vs 13.481 MC; det S = 1,677 = λ₁λ₂

4The spectral theoremBachelor's4 min

Symmetric matrices are everywhere in statistics: covariance matrices, projections, the matrices of quadratic forms. The spectral theorem says every real symmetric matrix is Q Lambda Q transpose: an orthogonal change of coordinates, scaling by the eigenvalues, and a change back. Negative eigenvalues reverse their directions. Here's the idea of the proof. Look for the unit vector u that makes u transpose A u as large as possible; the unit sphere is compact, so it exists. At the maximum, Lagrange's condition says A u is a multiple of u: an eigenvector. Because A is symmetric, it maps the directions perpendicular to u into themselves. So repeat the argument there, one dimension down, until the eigenvectors fill the space, every one at right angles to the others.

The theorem has a picture. Four hundred of the World's families: parents' average height against the child's. Their covariance matrix is two by two and symmetric. Its eigenvalues are about eighty-five and twenty. The quadratic form of its inverse traces ellipses around the mean. Their axes point along the eigenvectors, and their half-lengths are proportional to the square roots of the eigenvalues. The long axis is the direction in which the cloud spreads most: the first principal component, the subject of Part 31.

The proof's maximization has a statistical meaning. For a unit vector u, u transpose Sigma u is the variance of the data projected onto u. Turn u around the circle. The variance rises and falls, and its maximum is the largest eigenvalue, reached along the first eigenvector; its minimum is the smallest. This ratio is the Rayleigh quotient, and it always lies between the smallest and largest eigenvalues. Finding the direction of greatest variance is an eigenvalue problem: that's principal components.

The ellipses give the right way to measure how unusual a point is. Distance from the centre, but measured in the ellipse's own units: the Mahalanobis distance, named for Prasanta Chandra Mahalanobis, founder of the Indian Statistical Institute. It's the ordinary distance after multiplying by Sigma to the minus a half, the inverse square root from the spectral theorem. That map whitens the data: the tilted ellipse becomes a round cloud with identity covariance. In the whitened picture, the circled family stands out. Neither its parents' height nor its child's is far out on its own, but goes against the correlation, and the Mahalanobis distance sees it. For a normal population with known mean and covariance the squared distance is chi-squared with two degrees of freedom. Here both parameters are estimated from the displayed sample, so this is an approximate Gaussian reference, so the ninety-five percent circle should leave about five percent outside; here it leaves .

How does a computer actually find eigenvectors? The simplest method is beautiful. For this positive definite covariance with a distinct largest eigenvalue, start with a vector having a nonzero component along its leading eigenvector. Multiply and normalize; repeat. Written in the eigenvector basis, each multiplication scales every component by its eigenvalue, so after k steps the largest eigenvalue's component dominates. For the families' covariance, starting from the horizontal direction, the vector swings onto the long axis of the ellipse in a handful of steps, and the Rayleigh quotient locks onto the largest eigenvalue to four decimals. Asymptotically, the direction error shrinks at the eigenvalue ratio, and the Rayleigh-quotient error faster. For a general matrix the dominant eigenvalue is the one largest in absolute value. Variants of this power iteration compute Google's PageRank and the principal components of huge data sets.

What it does: Statement and proof sketch; ellipses of the families' covariance; the Rayleigh quotient around the circle; Mahalanobis distance and whitening; power iteration.; Numbers (computed): λ = 85.06, 19.71; 3.75% outside the χ²₂ 95% circle; power iteration converges in about 5 steps

5Positive semidefinite matricesMaster's4 min

Which symmetric matrices can be covariance matrices? Exactly the positive semidefinite ones: those whose quadratic form is never negative, which, by the spectral theorem, means every eigenvalue is at least zero. The reason is one line: the variance of any linear combination u transpose x is u transpose Sigma u, and a variance can't be negative. PSD matrices have square roots: take the square root of each eigenvalue in the spectral decomposition. And the condition has teeth. This matrix has ones on the diagonal and entries between minus one and one, so it looks like a correlation matrix. But it has a negative eigenvalue, so no three variables can have these correlations: the first two strongly positive, the second and third strongly positive, yet the first and third strongly negative.

Matrices like that one appear in practice, when correlations are estimated from different subsets of the data, or by hand. Its eigenvalues are minus point eight, one point nine and one point nine. To repair it, find the nearest matrix that is a valid correlation matrix in Frobenius norm. Higham's method uses Dykstra-corrected alternating projections: clip negative eigenvalues and restore the unit diagonal, while retaining a correction from previous steps. Plain alternation can find a valid matrix without guaranteeing the nearest one. The answer here keeps the pattern of signs but shrinks every correlation to a half, and its eigenvalues are zero, one and a half, and one and a half: just barely valid. It's how risk managers and geneticists clean up estimated correlation matrices.

A positive definite matrix also factors as L times L transpose, with L lower triangular: the Cholesky decomposition, named for a French army surveyor who devised it for map-making and was killed in the First World War. It's how a computer makes correlated random numbers. Start with independent standard normals: a round cloud. Multiply each point by L, here for a correlation of point eight. The cloud tilts and stretches into exactly the covariance we asked for: its sample correlation comes out at . Part 7 uses this to simulate any multivariate normal, and the World's families were built this way.

PSD matrices also give a way to compare matrices. Say A is at least B, in the Loewner order, when A minus B is positive semidefinite. It's only a partial order: for many pairs, neither is bigger. But when it holds between two estimators' covariance matrices, it means one is at least as precise as the other for every linear combination of the parameters at once. That's the sense in which least squares is best in Part 12's Gauss–Markov theorem, and in which the Cramér–Rao bound of Part 45 is a floor.

One rule moves covariances through linear maps, and it's used constantly. The covariance of A x is A Sigma A transpose: expand the definition and pull the constant matrices out of the expectation. It's automatically positive semidefinite, as it must be. For example, turn each family's pair of heights into their average and their difference. The formula gives the new covariance matrix without touching the data, and computing it directly from the transformed data agrees to every digit. Part 5 builds the multivariate normal on this rule, and Part 12 uses it for the covariance of regression coefficients.

What it does: Covariances are PSD; an impossible "correlation" matrix, repaired by Higham's Dykstra-corrected alternating projections; Cholesky makes correlated normals; Var(Ax) = AΣAᵀ; the Loewner order.; Numbers (computed): λ_min = −0.8 → nearest valid matrix with all correlations ±0.5; simulated r = 0.795 for target 0.8

6The singular value decompositionBachelor's3 min

The spectral theorem is for symmetric matrices. The singular value decomposition is its version for every matrix, square or not. Watch what a two by two matrix does to the unit circle. First, an orthogonal matrix V transpose rotates two special perpendicular directions onto the axes. Then a diagonal matrix stretches along the axes, by the singular values. Then another orthogonal matrix, U, rotates the result. The circle has become an ellipse. In general orthogonal maps may also reflect, and rectangular maps can add or remove dimensions; the same decomposition still applies. In symbols, M equals U Sigma V transpose. The singular values are the square roots of the eigenvalues of M transpose M, and the columns of V are its eigenvectors.

The decomposition comes from the spectral theorem. M transpose M is symmetric and positive semidefinite, so it's V times the squared singular values times V transpose. Write M as a sum of rank-one pieces, each a singular value times an outer product, largest first. Keep only the first r pieces. The theorem of Carl Eckart and Gale Young, from 1936, says this truncation is the best possible rank-r approximation to M, and its squared error is the sum of the squared singular values you threw away.

Here's what that buys. The World's population density, drawn as a sixty by a hundred matrix: six thousand numbers. Its best rank-one approximation, one column times one row, is a blur. Rank two, five, ten: the island and its regions emerge. At rank twenty-five the picture is all but exact, stored in four thousand numbers instead of six thousand, and every error is exactly the root sum of the discarded squared singular values, as Eckart and Young promised. Most of the matrix's energy sits in a few singular values. That's the idea behind principal components in Part 31, and behind the sparse and low-rank methods of Parts 32 and 52.

The SVD and the spectral theorem are two views of the same thing in statistics. Take the SVD of the centred data matrix. Then the sample covariance, X c transpose X c over n minus one, is V times the squared singular values over n minus one times V transpose: its eigenvectors are the right singular vectors, and its eigenvalues the scaled squared singular values. For the families the two computations agree, and the first principal axis carries percent of the total variance. Many implementations compute principal components directly from the SVD of the data for numerical stability. Covariance eigensolvers are also used when their size and conditioning make them suitable.

What it does: Orthogonal maps and stretches on the unit circle (reflections allowed in general); Mᵀ M; Eckart–Young; low-rank approximations of the World's population map; PCA as the SVD of the centred data.; Numbers (computed): errors match √(Σ_{k>r} σ²_k) exactly; first PC 81%

7Generalized inversesMaster's3 min

The projection formula needs A transpose A to be invertible, which fails when columns are redundant, or when there are more unknowns than equations. The simplest case: one equation, x one plus two x two equals four, in two unknowns. Every point on this line is a solution. Which one should we report? Slide along the line and watch the distance to the origin. There's a unique closest solution, where the line is tangent to a circle around the origin: the foot of the perpendicular. That minimum-norm solution is what the Moore–Penrose pseudoinverse gives: point eight, one point six.

The general definition comes from the singular value decomposition. Invert every nonzero singular value, leave the zeros alone, and swap the two rotations: that's A plus, defined for every matrix. Eliakim Moore found it in 1920 and Roger Penrose rediscovered it in 1955. Penrose characterized it by four equations. And A times A plus is always the projection onto the column space of A, so X plus times y is a least-squares solution even when X transpose X can't be inverted: the one with the smallest norm. It turns up whenever a design has redundant columns, and as the limit of ridge regression when the penalty vanishes.

Here's where rank deficiency happens in practice, and it catches beginners every year. Put an intercept in a regression, and an indicator column for every one of three regions. The three indicators add up to the intercept column, so the columns are dependent, X transpose X is singular, and there's no unique answer: the dummy-variable trap. The pseudoinverse still gives a least-squares solution, the one of minimum norm. But add any multiple of one, minus one, minus one, minus one, and the fit doesn't change: another solution, equally good. What doesn't change is any difference between regions: region two minus region one is in every solution, the difference of the two regions' means. Such combinations are called estimable, and Part 13's designed experiments are built around them.

There's another way to reach the pseudoinverse, and it previews a central idea of modern statistics. Penalize all coefficients, including the intercept in this example, by adding a positive multiple of the identity to X transpose X. Now it's always invertible, whatever the rank: that's ridge regression, Hoerl and Kennard's method from 1970. Follow the coefficients as lambda shrinks. With a big penalty they're squashed toward zero; as the penalty vanishes, they converge exactly to the pseudoinverse solution. Adding lambda trades a little bias for a lot of stability, and Part 19 makes that trade the heart of learning from data.

What it does: Minimum-norm solution of x₁ + 2x₂ = 4; Moore–Penrose; the dummy-variable trap and estimable contrasts; the ridge path converging to X⁺y.; Numbers (computed): A⁺b = (0.8, 1.6); region difference 11.00 in every solution

8Block matricesMaster's3 min

Statistics constantly splits variables into groups: the ones we observe and the ones we don't, the parameters we care about and the nuisance ones. Matrices split with them. Write a matrix in four blocks. Eliminate the lower-left block, exactly as in Gaussian elimination but a block at a time. What's left in the corner, D minus C A inverse B, is called the Schur complement of A. The determinant factors through it. And it has a statistical meaning we'll prove in Part 5: for a normal vector, the conditional covariance of one group given the other is exactly a Schur complement of the covariance matrix.

Finishing the elimination gives the inverse of a block matrix. Every block of M inverse is built from A inverse and the inverse of the Schur complement S. In particular, the lower-right block is just S inverse. Inverting a big matrix reduces to inverting two small ones, and the compute file checks every block against a direct inverse.

One block identity deserves its own name. The Woodbury identity gives the inverse of a matrix plus a low-rank update in terms of the inverse you already have and a small matrix the size of the update. For a rank-one update it's the Sherman–Morrison formula. It's why regression can be updated cheaply when one new observation arrives, in p squared operations instead of p cubed, and it's the engine inside Gaussian process regression and the Kalman filter later in the degree.

Block inverses explain one of the most useful facts in regression. Regress a child's height on both parents. Split the columns into two blocks: the intercept and the father's height, Z, and the mother's height, x. Work out the mother's coefficient from the block inverse, and it simplifies to this: remove the father's influence from both the child and the mother, by projecting it out, then regress residual on residual. Here are the three hundred residual pairs and their line. Its slope is exactly the mother's coefficient in the full regression, to every digit. That's the Frisch–Waugh–Lovell theorem, and it's what holding the father fixed means. Ignoring the father gives a slightly different answer, because in the World tall mothers tend to marry tall fathers.

Sherman–Morrison has a famous consequence for regression. Suppose we want each observation's prediction from a fit that didn't use it: leave-one-out cross-validation, which seems to need forty separate regressions. Removing one row changes X transpose X by a rank-one matrix, and Sherman–Morrison simplifies the whole calculation to one line: the leave-one-out residual is the ordinary residual divided by one minus its leverage. Refitting forty times and using the formula agree to twelve digits. Their sum of squares, called PRESS, is a little larger than the ordinary residual sum of squares, an honest estimate of prediction error, computed from one fit. Part 19 builds model selection on this idea.

What it does: Schur complement; block inverse and determinant; Woodbury and Sherman–Morrison; Frisch–Waugh–Lovell on mother's height given father's; leave-one-out residuals eᵢ/(1 − hᵢᵢ).; Numbers (computed): FWL 0.4552 = full-regression coefficient; LOO formula vs 40 refits: 1e−12; PRESS 3,105 vs RSS 2,790

9Kronecker products and vecMaster's2 min

Measurements in space and time have covariances with structure. The Kronecker product of A and B replaces each entry of A by that entry times the whole of B. Take a correlation between two measuring sites, and a correlation between three times that decays with the gap. Their Kronecker product is a six by six covariance for every site at every time, a pattern of blocks within blocks. Its inverse, determinant and eigenvalues all factor into those of the small pieces, which is what makes the spatial and longitudinal models of Parts 25 and 39 computable.

The Kronecker product's partner is vec. Vec of a matrix stacks its columns into one long vector. And then a product of three matrices, unpacked, is a Kronecker product acting on the middle one: vec of A B C equals C transpose Kronecker A, times vec of B. That turns any linear matrix equation into an ordinary system of equations, and it's the bridge between matrix calculus and ordinary calculus in the next chapter.

Why do Kronecker structures make big problems small? If u is an eigenvector of A and v of B, the Kronecker product of u and v is an eigenvector of A Kronecker B, with the product of the eigenvalues. So the eigenvalues of a Kronecker product are all the products of the small matrices' eigenvalues: an mn-dimensional problem solved with an m-dimensional one and an n-dimensional one. The determinant follows. For the site-time covariance, the six eigenvalues match the products exactly.

And Kronecker structure makes simulation cheap too. The Cholesky factor of a Kronecker product is the Kronecker product of the Cholesky factors. Multiply a vector of independent normals by it, and you get a draw with exactly the space-time covariance. Here are two sites over sixty time steps: each series wanders smoothly, because neighbouring times are correlated, and the two sites move together, because the sites are. Part 39 fits models like this to real measurements.

What it does: A ⊗ B; site × time covariance; vec(ABC) = (Cᵀ ⊗ A)vec B; eigenvalues are products; a simulated space–time field.; Numbers (computed): max error 9e−16

10Matrix calculusMaster's3 min

Statistics optimizes over vectors and matrices, so it needs their derivatives. The gradient of a linear function a transpose x is a, term by term. The gradient of a quadratic form x transpose A x is A plus A transpose times x, or two A x when A is symmetric: the matrix version of the derivative of a x squared. Apply both to the least-squares criterion, the squared length of y minus X beta. Set the gradient to zero, and the normal equations of chapter two fall out in three lines.

For symmetric positive definite Sigma and symmetric S, normal likelihoods need two derivatives. We use Frobenius gradients, paired with symmetric matrix perturbations. Nudge Sigma by a small multiple of a direction E and factor Sigma out of the determinant. To first order, the determinant of the identity plus a small matrix is one plus its trace. So the gradient of log det Sigma is Sigma inverse, a beautiful identity. And differentiating an inverse, the matrix version of minus one over x squared, gives the derivative of the trace of Sigma inverse S.

Is the solution of the normal equations really a minimum? Differentiate the gradient again: the Hessian of the least-squares criterion is two X transpose X. It's positive semidefinite, since u transpose X transpose X u is a squared length, and definite when X has full column rank. So the criterion is a convex bowl, and the solution is its unique bottom. In fact the criterion is exactly quadratic around the solution, with level sets that are ellipses shaped by X transpose X: the confidence ellipses of Part 12. For criteria that aren't quadratic, like logistic regression's, the Hessian drives Newton's method, in Part 21.

For independent normal observations whose centered scatter is positive definite, the covariance maximum likelihood estimate takes one line. If that scatter is singular, there is no positive definite interior maximizer. The normal log-likelihood, with the mean already estimated, is minus n over two log det Sigma, minus n over two times the trace of Sigma inverse times the sample covariance. Differentiate and set to zero. The estimate is the sample covariance with divisor n. For four hundred families it's this matrix; the unbiased version, divisor n minus one, differs slightly, for the reason the hook gave. Part 22 does likelihood in full.

One more application shows where all this is heading. The normal log-likelihood as a function of the mean. Its gradient, the score, is n Sigma inverse times x bar minus mu: zero exactly at the sample mean. Its negative Hessian, the curvature, is n Sigma inverse: Fisher called it the information. And the inverse of the information is Sigma over n, exactly the covariance of the sample mean. A sharply curved likelihood means a precise estimate. That's Fisher's great idea, and Parts 9 and 22 develop it in full.

What it does: ∂aᵀx, ∂xᵀAx, least squares in three lines; the Hessian 2XᵀX; ∂ log det Σ = Σ⁻¹; the Gaussian MLE of Σ; score and Fisher information for μ.; Numbers (computed): Σ̂_MLE for 400 families

11Quadratic forms in normal vectorsMaster's5 min

Here the hook's eigenvalues pay off completely. Take a standard normal vector z and a projection P, and diagonalize P. Rotating a standard normal vector gives another standard normal vector: Herschel's rotation invariance from Part 3. So z transpose P z is a sum of squared independent standard normals, one for each eigenvalue equal to one: chi-squared, with degrees of freedom equal to the rank. And the converse holds: for a symmetric matrix, the quadratic form is chi-squared only if that matrix is an orthogonal projection. A nonsymmetric matrix contributes only through its symmetric part.

Check it. Take a hat matrix for n equal to and p equal to , and twenty thousand standard normal vectors. z transpose H z, blue, falls on the chi-squared with degrees of freedom, and z transpose I minus H z, red, on the chi-squared with . And the two are uncorrelated, in fact independent, because they're built from different coordinates of the rotated vector: the fitted part and the residual part never share a direction.

That observation generalizes into one of the central theorems of classical statistics. If the identity splits into projections onto mutually perpendicular subspaces, the corresponding pieces of the squared length of a standard normal vector are independent chi-squareds, with the ranks as degrees of freedom. It's William Cochran's theorem, from 1934. In Part 8 it gives the independence of the sample mean and variance and the chi-squared law of the variance; in Part 12, the t and F tests of regression; in Part 13, the whole analysis of variance.

What if the normal vector isn't centred at zero? Shift it by mu. The quadratic form now averages its rank plus the squared length of the projected shift, and its distribution is the noncentral chi-squared. With no shift, grey, it's the ordinary chi-squared with seven degrees of freedom. A shift of length two, yellow, moves it right; a shift of length four, red, moves it far right. Draw the line that an ordinary chi-squared exceeds only five percent of the time. The shifted versions exceed it and percent of the time, in twenty thousand simulations each, matching the theory. That fraction is a test's power, the probability that it notices a real effect, and it's the subject of Part 10.

The perpendicular split has a striking consequence, and a striking limitation. The sample mean depends only on the projection onto the ones vector; the sample variance only on the perpendicular part. For normal data those parts are independent, so the mean and the variance are independent too. Twenty thousand normal samples of ten, with a subset of fifteen hundred shown: the cloud of means and variances shows no relation at all. But the argument used rotation invariance, together with independent coordinates. Rotation invariance alone is shared by many non-Gaussian spherical distributions. For exponential data, the same plot shows a strong relation: samples with larger means have larger variances, a correlation of about point seven. Under the usual independent, identically distributed, nondegenerate finite-variance assumptions, independence of the sample mean and variance characterizes the normal: Geary's theorem from 1936.

Put the pieces together and Student's t falls out. For normal data, the sample mean, standardized with the true sigma, is standard normal: it lives in the projection onto the ones vector. The sample variance lives in the perpendicular projection, of rank n minus one, so scaled by sigma squared it's chi-squared with n minus one degrees of freedom. And the two are independent. So the mean standardized with the estimated s is a standard normal over the root of an independent chi-squared over its degrees of freedom: exactly Part 3's definition of t with n minus one degrees of freedom. Gosset's 1908 result, in three lines of projections.

What it does: zᵀPz ~ χ²_rank; 20,000 simulations of zᵀHz and zᵀ(I − H)z; Cochran's theorem (1934); noncentral χ² and power; independence of x̄ and s² (normal) vs strong dependence (exponential); Student's t from projections.; Numbers (computed): means 3.01 and 6.92; power 25% and 85% at ‖Pμ‖ = 2, 4; corr(x̄, s²) −0.002 vs 0.70

12Conditioning and numericsPractice4 min

Everything so far has been exact algebra. Computers don't do exact algebra. In double precision, nought point one plus nought point two is not quite nought point three. Numbers carry about sixteen significant digits. The spacing at one is two to the minus fifty-two; rounding a basic operation in the normal finite range has relative error at most half that spacing. Usually that's harmless. The question is when it gets amplified.

The amplification factor is the condition number. It's the ratio of the largest to the smallest singular value: how much the matrix stretches its most-stretched direction compared with its least. Relative errors in the data can be amplified by that factor in the solution. And here's the trap: X transpose X has the squared singular values of X, so its condition number is the square of X's. Forming X transpose X and inverting it squares the damage. A QR decomposition works with X directly and doesn't.

Here's the difference, measured. A regression with two nearly identical columns, whose exact coefficients are one, two and three, with no noise at all. As the columns get closer, the condition number grows from twenty to twenty million. Solving the normal equations, red, loses accuracy fast: at the end the coefficients are wrong in the first decimal. QR, blue, stays accurate to nine or ten digits. That's why stable general-purpose least-squares solvers typically use QR or the SVD, and why you should never write the inverse of X transpose X in code, however often it appears in formulas.

Some poor conditioning comes from how variables are coded, and centering can help. Intrinsic near-collinearity can remain after centering and scaling. Fit a quadratic in height, with columns one, h and h squared. Heights are all near a hundred and seventy, so h and h squared are almost perfectly correlated, and the condition number is in the millions. Centre the heights first. The correlation drops to a sixth, and the condition number to about two hundred. It's exactly the same model, with the same fitted values; only the coordinates changed. Centring and scaling before fitting cost nothing and buy several digits.

The same lesson appears in the humblest formula in statistics. The variance can be computed in one pass, as the sum of squares minus n times the squared mean. Or in two passes, centring first. Algebraically they're identical. Take a thousand of the World's heights and add a constant, as if measuring from further away; the variance shouldn't change at all. With an offset of a hundred million, the one-pass formula loses meaningful digits: it subtracts two enormous, nearly equal numbers, and the digits that mattered cancel away. The two-pass formula doesn't notice. Statistical software uses two passes, or Welford's clever one-pass update.

So here, in five steps, is how good regression software solves least squares, and how this part's toolkit fits together. Centre and scale the nonconstant predictors, while retaining the intercept, to improve conditioning. Factor X as Q R, using Householder's reflections, as Gene Golub showed in 1965, which is more stable still than Gram–Schmidt. Solve the triangular system by back-substitution. When standard errors need X transpose X inverse, get it from R, never by forming the product. And if R has a tiny diagonal entry, the design is nearly rank-deficient: pivot the columns, or fall back on the SVD and the pseudoinverse. Every formula in Part 12 will be written with inverses; every computation should be done like this.

What it does: 0.1 + 0.2; condition numbers; κ(XᵀX) = κ(X)²; normal equations vs QR on near-collinear columns (exact floating-point errors depend on the platform); centring a quadratic in height; catastrophic cancellation in the one-pass variance; how software solves least squares.; Numbers (computed): at κ = 2×10⁷, error 0.17 vs 4×10⁻¹⁰; κ 6.2×10⁶ → 220 after centring; offset 10⁸: s² = 90.20 vs 93.26

Recap, problems, and the road aheadAll tracks3 min

Part four in thirteen lines. The hat matrix's eigenvalues are zero and one, and degrees of freedom count the ones. Data are vectors, and centring is a projection. Projections are A, A transpose A inverse, A transpose, or Q Q transpose after Gram–Schmidt. The trace cycles, and gives the expectation of any quadratic form. The spectral theorem draws ellipses, and the Rayleigh quotient finds their axes. Covariance matrices are exactly the positive semidefinite ones, and Cholesky makes correlated normals. Every matrix has orthogonal maps and stretches, and the truncated SVD is the best low-rank approximation. The pseudoinverse picks the minimum-norm solution. Schur complements and Woodbury invert in blocks; Kronecker products build structured covariances. The derivative of log det is the inverse. Quadratic forms in projections are chi-squared. And you should never invert X transpose X.

This part is a toolkit, so it comes back everywhere. Projections and n minus p in sampling theory, regression and the analysis of variance. Schur complements in Part 5's conditional distributions and Part 25's mixed models. The spectral theorem and the SVD in principal components, sparsity and random matrices. Cochran's theorem in every chi-squared, t and F test. Matrix calculus in likelihood and the linear model in depth. Woodbury in mixed models, the Kalman filter and kriging. And conditioning in optimization.

Six problems, with full solutions in the README. The complement of a projection; the trace of the hat matrix; why the sample variance is unbiased, by the trace trick; an ellipse from an eigen-decomposition; checking Sherman–Morrison; and the chi-squared law of the centred sum of squares. Pause here if you want to try them.

The books and papers this part follows: Harville, Searle and Khuri, Magnus and Neudecker, Seber, Strang, and Trefethen and Bau for numerical linear algebra, along with the original papers from Cochran to Golub.

Four parts of sixty-five. We have the tools; now we use them. In 1886 Francis Galton plotted parents' heights against their children's and saw ellipses, the same ellipses as our spectral theorem. Joint distributions of many variables, their covariances, conditioning on some of them, and the multivariate normal: that's Part 5. Galton's question was about inheritance, but his answer, regression toward the mean, turned out to be a fact about ellipses, and Part 5 will prove it with the Schur complement from chapter eight.

Where it goes next. Projections and n minus p return in the sampling theory of Part 8, regression in Part 12 and ANOVA in Part 13; Schur complements give Part 5's conditional Gaussians and Part 25's mixed models; the SVD returns as principal components in Part 31; Cochran's theorem is used in Part 8; the linear model in full matrix generality is Part 23.

Key results

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

The hat matrix\(\displaystyle H=X(X^\top X)^{-1}X^\top,\quad\allowbreak H^2=H=H^\top\ \Longrightarrow\ \lambda_i(H)\in\{0,1\},\quad\allowbreak \operatorname{tr}H=p,\quad\allowbreak \mathbb E\,\mathrm{RSS}=(n-p)\sigma^2\)
Expectation of a quadratic form\(\displaystyle \mathbb E[x^\top A x]=\operatorname{tr}(A\Sigma)+\mu^\top A\mu\quad\allowbreak \text{for }\mathbb E x=\mu,\ \operatorname{Var}x=\Sigma\)
Eckart-Young\(\displaystyle \min_{\operatorname{rank}B\le r}\lVert A-B\rVert_F=\Bigl(\sum_{k>r}\sigma_k^2\Bigr)^{1/2},\quad\allowbreak \text{attained }\allowbreak \text{by }\allowbreak \text{the }\allowbreak \text{truncated }\allowbreak \text{SVD}\)
Woodbury\(\displaystyle (A+UCV)^{-1}=A^{-1}-A^{-1}U\,(C^{-1}+VA^{-1}U)^{-1}\,VA^{-1}\)
Quadratic forms in normal vectors\(\displaystyle z\sim N(0,I_n),\ P\text{ a }\allowbreak \text{projection }\allowbreak \text{of }\allowbreak \text{rank }r\ \Longrightarrow\ z^\top P z\sim\chi^2_r\)
Conditioning\(\displaystyle \kappa(X)=\frac{\sigma_{\max}(X)}{\sigma_{\min}(X)},\qquad\allowbreak \kappa(X^\top X)=\kappa(X)^2\)

Try it

Lab 4 · The hat matrix and degrees of freedom

Build the hat matrix of a line fitted to forty of the World's families, check that it is a projection with p eigenvalues equal to one, and simulate 2,000 data sets on the same design to see the residual sum of squares average (n - p) sigma^2, for p = 2, 5 and 10.

Figure produced by Lab 4: The hat matrix and degrees of freedom
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.stats.labs 4 needs numpy, scipy, matplotlib · download lab04.py · source on GitHub
H is symmetric and idempotent                          max |H - H'| = 3.7e-16   max |HH - H| = 4.1e-15
eigenvalues of H                                       2 ones, 38 zeros   trace 2.000000 = p
p = 2: mean RSS / sigma^2                              37.98   (n - p = 38, n = 40)
p = 5: mean RSS / sigma^2                              35.24   (n - p = 35, n = 40)
p = 10: mean RSS / sigma^2                             29.83   (n - p = 30, n = 40)
p = 2: RSS / n and RSS / (n - p), in units of sigma^2  0.950 and 0.999   (theory 0.950 and 1)
p = 2: RSS / sigma^2 against chi-squared(38)           variance 73.0 (theory 76)   KS p-value 0.72
condition numbers                                      kappa(X) = 5957   kappa(X'X) = 3.55e+07 = kappa(X)^2

A projection's eigenvalues are 0 and 1, and degrees of freedom count the ones: the residuals live in n - p dimensions, so RSS / (n - p), not RSS / n, is centred on sigma^2.
The code (94 lines; it asserts its own result)
"""Lab 4: the hat matrix's eigenvalues are 0 and 1, so residual sums of squares average (n - p) sigma^2."""

import numpy as np
from scipy import stats

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

TITLE = "The hat matrix and degrees of freedom"
GOAL = ("Build the hat matrix of a line fitted to forty of the World's families, check that it is a projection with "
        "p eigenvalues equal to one, and simulate 2,000 data sets on the same design to see the residual sum of "
        "squares average (n - p) sigma^2, for p = 2, 5 and 10.")
TASKS = [
    "Draw the errors from a centred exponential instead of a normal. Which survives: the mean of RSS / sigma^2, or "
    "its chi-squared shape?",
    "Add a column that is the mid-parent height in inches (the same variable in other units). What happens to the "
    "rank, the trace of H and the condition number?",
    "Compare kappa(X) before and after centring the mid-parent heights, and solve both by ols.normal_equations in "
    "float32. How many digits does each keep?",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    f = World().families
    n = 40
    idx = rng.choice(len(f["child"]), n, replace=False)
    mid, child = (f["father"][idx] + f["mother"][idx]) / 2, f["child"][idx]
    lab = labs.Lab()

    # 1. The hat matrix of the line: symmetric, idempotent, eigenvalues 0 and 1, trace p.
    X = ols.design(mid)
    fit = ols.fit(X, child)
    H = X @ fit.XtX_inv @ X.T
    eig = np.sort(np.linalg.eigvalsh(H))[::-1]
    p = X.shape[1]
    lab.row("H is symmetric and idempotent", f"max |H - H'| = {np.abs(H - H.T).max():.1e}   max |HH - H| = {np.abs(H @ H - H).max():.1e}")
    lab.row("eigenvalues of H", f"{(eig > 0.5).sum()} ones, {(eig < 0.5).sum()} zeros   trace {np.trace(H):.6f} = p")
    assert np.allclose(H, H.T, atol=1e-10) and np.allclose(H @ H, H, atol=1e-10)
    assert np.allclose(eig[:p], 1, atol=1e-8) and np.allclose(eig[p:], 0, atol=1e-8), "p ones and n - p zeros"
    assert np.allclose(np.diag(H), fit.leverage) and np.isclose(fit.leverage.sum(), p), "leverages sum to p"

    # 2. Simulate on the same design, and on designs with extra columns: E RSS = (n - p) sigma^2.
    sigma, reps = 5.0, 2000
    results = {}
    for p_k in (2, 5, 10):
        Xk = np.column_stack([X, rng.standard_normal((n, p_k - 2))])
        Q, _ = np.linalg.qr(Xk)
        beta = rng.standard_normal(p_k)
        E = sigma * rng.standard_normal((reps, n))
        Y = Xk @ beta + E
        resid = Y - (Y @ Q) @ Q.T  # (I - H) y, with H = Q Q'
        rss = (resid ** 2).sum(1) / sigma ** 2
        fitted_part = ((E @ Q) ** 2).sum(1) / sigma ** 2  # e' H e / sigma^2
        results[p_k] = rss
        lab.row(f"p = {p_k}: mean RSS / sigma^2", f"{rss.mean():.2f}   (n - p = {n - p_k}, n = {n})")
        se = np.sqrt(2 * (n - p_k) / reps)
        assert abs(rss.mean() - (n - p_k)) < 4 * se, "the residual projection has n - p unit eigenvalues"
        assert abs(fitted_part.mean() - p_k) < 4 * np.sqrt(2 * p_k / reps), "and the fitted part has the other p"
    rss = results[2]
    naive, unbiased = (rss / n).mean(), (rss / (n - 2)).mean()
    lab.row("p = 2: RSS / n and RSS / (n - p), in units of sigma^2", f"{naive:.3f} and {unbiased:.3f}   (theory {1 - 2 / n:.3f} and 1)")
    ks = stats.kstest(rss, stats.chi2(n - 2).cdf)
    lab.row("p = 2: RSS / sigma^2 against chi-squared(38)", f"variance {rss.var():.1f} (theory {2 * (n - 2)})   KS p-value {ks.pvalue:.2f}")
    assert abs(naive - (1 - 2 / n)) < 0.02 and abs(unbiased - 1) < 0.02
    assert abs(rss.var() / (2 * (n - 2)) - 1) < 0.15 and ks.pvalue > 1e-3, "a chi-squared with n - p degrees of freedom"

    # 3. Conditioning: forming X'X squares the condition number.
    kx, kxx = np.linalg.cond(X), np.linalg.cond(X.T @ X)
    lab.row("condition numbers", f"kappa(X) = {kx:.0f}   kappa(X'X) = {kxx:.3g} = kappa(X)^2")
    assert np.isclose(kxx, kx ** 2, rtol=1e-4)
    lab.note = ("A projection's eigenvalues are 0 and 1, and degrees of freedom count the ones: the residuals live in "
                "n - p dimensions, so RSS / (n - p), not RSS / n, is centred on sigma^2.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    grid = np.linspace(10, 75, 300)
    ax[0].hist(rss, bins=45, density=True, color=labs.BLUE, alpha=0.6, label="2,000 simulated RSS / sigma^2, p = 2")
    ax[0].plot(grid, stats.chi2(n - 2).pdf(grid), color=labs.GOLD, label="chi-squared, 38 df")
    ax[0].axvline(n - 2, color=labs.GOLD, ls="--", lw=1)
    ax[0].axvline(n, color=labs.RED, ls="--", lw=1, label="n = 40")
    ax[0].set(title="Residual sum of squares on forty families", xlabel="RSS / sigma^2", ylabel="density",
              xlim=(10, 100))
    ax[0].legend(loc="upper right")
    ps = np.array(sorted(results))
    ax[1].plot([0, 12], [n, n - 12], color=labs.GOLD, label="n - p")
    ax[1].axhline(n, color=labs.RED, ls="--", lw=1, label="n")
    ax[1].errorbar(ps, [results[k].mean() for k in ps], yerr=[results[k].std() for k in ps], fmt="o", color=labs.BLUE,
                   capsize=3, label="simulated mean, with one SD of RSS / sigma^2")
    ax[1].set(title="Every fitted column uses up one dimension", xlabel="columns in the design, p",
              ylabel="RSS / sigma^2", xlim=(0, 12))
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Draw the errors from a centred exponential instead of a normal. Which survives: the mean of RSS / sigma^2, or its chi-squared shape?
  2. Add a column that is the mid-parent height in inches (the same variable in other units). What happens to the rank, the trace of H and the condition number?
  3. Compare kappa(X) before and after centring the mid-parent heights, and solve both by ols.normal_equations in float32. How many digits does each keep?

Problems, with solutions

Try each problem before opening its solution.

1. The complementary projection. Show that if \(P\) is a projection, so is \(I - P\), and that \(P(I - P) = 0\). What are the eigenvalues of \(I - P\)?

Solution
  • It is a projection. (I − P)² = I − 2P + P² = I − P, and (I − P)ᵀ = I − P.
  • The two are orthogonal. P(I − P) = P − P² = 0.
  • Eigenvalues. If Pv = λv with λ ∈ {0, 1}, then (I − P)v = (1 − λ)v. So the eigenvalues of I − P are also 0 and 1, with the roles swapped. Hence rank(I − P) = n − rank P.

2. tr H = p. Show that \(\operatorname{tr}(H) = p\) for \(H = X(X^\top X)^{-1}X^\top\) by cycling the trace.

Solution

tr(X(XᵀX)⁻¹Xᵀ) = tr((XᵀX)⁻¹XᵀX) = tr(I_p) = p, by cycling X from the front to the back.

3. E s² = σ². Let \(\mathbf x\) have common mean \(\mu_0\mathbf 1\) and covariance \(\sigma^2 I_n\). Use \(E[\mathbf x^\top A\mathbf x] = \operatorname{tr}(A\Sigma) + \boldsymbol\mu^\top A\boldsymbol\mu\) to show \(E\, s^2 = \sigma^2\).

Solution

(n − 1)s² = xᵀ(I − J/n)x. Apply E[xᵀAx] = tr(AΣ) + μᵀAμ with Σ = σ²I and μ = μ₀1:

  • tr((I − J/n)σ²) = σ²(n − 1);
  • (I − J/n)1 = 0, so the mean term vanishes.

So E[(n − 1)s²] = (n − 1)σ², and E s² = σ². No normality is needed.

4. An ellipse. Find the eigenvalues and eigenvectors of \(\begin{pmatrix} 2 & 1 \ 1 & 2 \end{pmatrix}\), and sketch the ellipse \(\mathbf x^\top A^{-1}\mathbf x = 1\).

Solution

For A = [[2, 1], [1, 2]]:

  • eigenvalue 3 with eigenvector (1, 1)/√2;
  • eigenvalue 1 with eigenvector (1, −1)/√2.

The ellipse xᵀA⁻¹x = 1 has semi-axes √3 along (1, 1) and 1 along (1, −1), tilted at 45°.

5. Sherman–Morrison. Verify the Sherman–Morrison formula by multiplying it out.

Solution

Multiply (A + uvᵀ) by A⁻¹ − A⁻¹uvᵀA⁻¹/(1 + vᵀA⁻¹u):

I + uvᵀA⁻¹ − [uvᵀA⁻¹ + u(vᵀA⁻¹u)vᵀA⁻¹]/(1 + vᵀA⁻¹u) = I + uvᵀA⁻¹ − u(1 + vᵀA⁻¹u)vᵀA⁻¹/(1 + vᵀA⁻¹u) = I.

This needs 1 + vᵀA⁻¹u ≠ 0.

6. Σ(zᵢ − z̄)² ~ χ²_{n−1}. For \(\mathbf z \sim N(\mathbf 0, I_n)\), show that \(\sum_i (z_i - \bar z)^2 \sim \chi^2_{n-1}\) using the projection \(I - \tfrac1n J\).

Solution

Σ(zᵢ − z̄)² = zᵀ(I − J/n)z. Here I − J/n is a projection (symmetric and idempotent, since J² = nJ), with trace n − 1 and so rank n − 1. By chapter 11, zᵀPz ~ χ²_{rank P} for z ~ N(0, I).

Notes and sources

Where it comes back

Idea Returns in
projections, n − p, leverage 8, 12, 13, 30
Schur complements, conditional covariance 5, 25
the spectral theorem, Mahalanobis, PCA 5, 31
the SVD, low rank, ridge 19, 31, 32, 52
Cochran's theorem, t and F 8, 12, 13
matrix calculus, information 9, 22, 23
Woodbury, Kronecker structure 25, 38, 39
conditioning, QR 21, 23

Sources

  • The hat matrix. D. C. Hoaglin & R. E. Welsch, "The hat matrix in regression and ANOVA", The American Statistician 32 (1978).
  • Spectral theorem. A.-L. Cauchy (1829); later Sylvester and Hilbert. The proof sketched on screen is the variational one (maximize uᵀAu on the sphere).
  • Mahalanobis. P. C. Mahalanobis, "On the generalised distance in statistics" (1936).
  • Generalized variance. S. S. Wilks (1932).
  • SVD. C. Eckart & G. Young, "The approximation of one matrix by another of lower rank", Psychometrika 1 (1936).
  • Pseudoinverse. E. H. Moore (1920); R. Penrose, "A generalized inverse for matrices", Proc. Camb. Phil. Soc. 51 (1955). Ridge: A. Hoerl & R. Kennard (1970).
  • Nearest correlation matrix. N. J. Higham, IMA J. Numer. Anal. 22 (2002).
  • Woodbury. M. Woodbury (1950); J. Sherman & W. Morrison (1950).
  • Frisch–Waugh–Lovell. R. Frisch & F. Waugh (1933); M. Lovell (1963).
  • Cochran. W. G. Cochran, "The distribution of quadratic forms in a normal system" (1934).
  • Independence of x̄ and s². R. C. Geary (1936) characterizes the normal by it.
  • Cholesky. A.-L. Cholesky's method, published posthumously by Benoît (1924).
  • Numerics.
    • J. von Neumann & H. Goldstine (1947).
    • J. H. Wilkinson, Rounding Errors in Algebraic Processes (1963).
    • G. Golub, "Numerical methods for solving linear least squares problems" (1965).
    • B. P. Welford (1962).
    • L. Trefethen & D. Bau, Numerical Linear Algebra (1997).
  • Textbooks.
    • D. Harville, Matrix Algebra From a Statistician's Perspective (1997).
    • S. Searle & A. Khuri, Matrix Algebra Useful for Statistics (2nd ed., 2017).
    • J. Magnus & H. Neudecker, Matrix Differential Calculus (3rd ed., 2019).
    • G. Seber, A Matrix Handbook for Statisticians (2008).
    • G. Strang, Introduction to Linear Algebra.
About this partfrom its README

Part 4 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage I, Bachelor's: Foundations. This part is the toolkit every later part reaches into.

It opens with the hat matrix H = X(XᵀX)⁻¹Xᵀ of a full-column-rank regression on the World's families. Because H is a projection, its eigenvalues can only be 0 and 1. From that one fact come degrees of freedom, the n − p of the residual variance, χ² quadratic forms, Student's t, regression and the analysis of variance.

Every identity on screen is checked numerically in compute.py, and every distributional claim against a seeded simulation.

Built in this part: the projection lab (ProjectionLab in common.py). It is a turnable ℝ³, drawn with NSpace, that shows:

  • a column space;
  • a data vector, its projection and the residual;
  • the right angle between the residual and the column space.

It is used for centring (projection onto 1), for a plane spanned by two columns, and for Gram–Schmidt.

Chapter notes
# Chapter What it does Numbers (computed)
0 The hat matrix 40 World families. H as a heat map; H² = H ⇒ eigenvalues 0 and 1; tr H = p. 2,000 simulated data sets: E RSS = (n − p)σ². eigenvalues two 1s, 38 0s; RSS/σ² averages 37.95; RSS/n is 0.949σ² vs RSS/(n − p) 0.999σ²
1 Vectors as data A sample as a point in ℝⁿ; centring as projection onto 1 in the lab; why n − 1; the upgrade card for Part 1's r = cos θ, and slope = r s_y/s_x; the data matrix's two views. —
2 Projections P = A(AᵀA)⁻¹Aᵀ derived; the lab; Pythagoras; Gram–Schmidt and QR; eigenvalues of a projection; ANOVA as nested projections; leverage. 19.00 = 8.71 + 10.29; SS 3,736 = 946 + 2,790, R² = 0.253; leverages sum to 2
3 Trace tricks tr(AB) = tr(BA); E[xᵀAx] = tr(AΣ) + μᵀAμ (Monte Carlo); MSE = tr Cov + bias²; rank = trace; tr and det of Σ. 13.456 exact vs 13.481 MC; det S = 1,677 = λ₁λ₂
4 The spectral theorem Statement and proof sketch; ellipses of the families' covariance; the Rayleigh quotient around the circle; Mahalanobis distance and whitening; power iteration. λ = 85.06, 19.71; 3.75% outside the χ²₂ 95% circle; power iteration converges in about 5 steps
5 Positive semidefinite matrices Covariances are PSD; an impossible "correlation" matrix, repaired by Higham's Dykstra-corrected alternating projections; Cholesky makes correlated normals; Var(Ax) = AΣAᵀ; the Loewner order. λ_min = −0.8 → nearest valid matrix with all correlations ±0.5; simulated r = 0.795 for target 0.8
6 The SVD Orthogonal maps and stretches on the unit circle (reflections allowed in general); Mᵀ M; Eckart–Young; low-rank approximations of the World's population map; PCA as the SVD of the centred data. errors match √(Σ_{k>r} σ²_k) exactly; first PC 81%
7 Generalized inverses Minimum-norm solution of x₁ + 2x₂ = 4; Moore–Penrose; the dummy-variable trap and estimable contrasts; the ridge path converging to X⁺y. A⁺b = (0.8, 1.6); region difference 11.00 in every solution
8 Block matrices Schur complement; block inverse and determinant; Woodbury and Sherman–Morrison; Frisch–Waugh–Lovell on mother's height given father's; leave-one-out residuals eᵢ/(1 − hᵢᵢ). FWL 0.4552 = full-regression coefficient; LOO formula vs 40 refits: 1e−12; PRESS 3,105 vs RSS 2,790
9 Kronecker products and vec A ⊗ B; site × time covariance; vec(ABC) = (Cᵀ ⊗ A)vec B; eigenvalues are products; a simulated space–time field. max error 9e−16
10 Matrix calculus ∂aᵀx, ∂xᵀAx, least squares in three lines; the Hessian 2XᵀX; ∂ log det Σ = Σ⁻¹; the Gaussian MLE of Σ; score and Fisher information for μ. Σ̂_MLE for 400 families
11 Quadratic forms in normal vectors zᵀPz ~ χ²_rank; 20,000 simulations of zᵀHz and zᵀ(I − H)z; Cochran's theorem (1934); noncentral χ² and power; independence of x̄ and s² (normal) vs strong dependence (exponential); Student's t from projections. means 3.01 and 6.92; power 25% and 85% at ‖Pμ‖ = 2, 4; corr(x̄, s²) −0.002 vs 0.70
12 Conditioning and numerics 0.1 + 0.2; condition numbers; κ(XᵀX) = κ(X)²; normal equations vs QR on near-collinear columns (exact floating-point errors depend on the platform); centring a quadratic in height; catastrophic cancellation in the one-pass variance; how software solves least squares. at κ = 2×10⁷, error 0.17 vs 4×10⁻¹⁰; κ 6.2×10⁶ → 220 after centring; offset 10⁸: s² = 90.20 vs 93.26
13 Outro Recap, payoffs, problems, references, the Transcript, Part 5's question. —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: the hat matrix. H = X(XᵀX)⁻¹Xᵀ has eigenvalues 0 and 1 only, and that explains n − p.
  2. Vectors as data. A sample of n as a point in Rⁿ; centring as projection away from 1 (NSpace).
  3. Projections. Idempotent and symmetric; orthogonal complements; Gram–Schmidt and QR; P = A(AᵀA)⁻¹Aᵀ derived.
  4. Trace tricks. tr(AB) = tr(BA); E[xᵀAx] = tr(AΣ) + μᵀAμ; rank = trace for projections.
  5. The spectral theorem (sketched proof); quadratic forms as ellipsoids; the Rayleigh quotient.
  6. Positive semidefinite matrices. The Loewner order; Cholesky; square roots; covariance matrices are PSD.
  7. The SVD. From AᵀA; geometry (rotate, stretch, rotate); low-rank approximation (Eckart–Young).
  8. Generalized inverses. The Moore–Penrose pseudoinverse; minimum-norm solutions.
  9. Block matrices. The Schur complement; block inverses; determinants; Woodbury (Sherman–Morrison–Woodbury) and why it makes updating cheap.
  10. Kronecker products and vec. vec(ABC) = (Cᵀ ⊗ A)vec(B); the structured covariances of Parts 25 and 39.
  11. Matrix calculus. ∂(aᵀx), ∂(xᵀAx), ∂ log det Σ = Σ⁻¹, ∂ tr; the Gaussian MLE in one line.
  12. Quadratic forms in normal vectors. xᵀAx ~ χ² iff A is a projection (for x ~ N(0, I)); Cochran's theorem previewed (Part 8).
  13. Conditioning and numerics. Condition numbers; why never to invert XᵀX; floating point.
  14. Outro.

Built: a projection lab (rotate Rⁿ for n = 3, watch idempotence, eigenvalues and residuals). Books: Harville; Searle; Magnus & Neudecker; Seber A Matrix Handbook for Statisticians.

Build the film

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

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

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