Multivariate Analysis
What structure hides in many correlated variables measured at once?
The part opens with a table and no map: the road distance between every pair of the World's 200 towns. Torgerson's classical scaling double-centres the squared distances into a Gram matrix, takes two eigenvectors, and rebuilds the island; the same method on 21 European cities picks out the table entries worth checking against their sources. From there the classical toolkit is built on the sample covariance matrix: Mahalanobis distance on Fisher's versicolors, the Wishart law by Bartlett's decomposition, Hotelling's T-squared as the best single t-test, and MANOVA's four statistics. Principal components, factor analysis of the 24 tests and canonical correlation look for low-dimensional structure; discriminant analysis and clustering look for groups, known and unknown; zeros of the precision matrix draw a graph of conditional independence. The part turns when the number of variables grows with the sample: the chi-squared calibration of T-squared rejects 72% of true nulls at p = 40, the exact F holds, and Bai and Saranadasa's test keeps its power by dropping the inverse covariance. It ends on the promise that Part 52 drops the assumption of fixed p altogether.
What you need. Linear algebra at the level of Part 4 (eigenvectors, the SVD, projections) and the multivariate normal of Part 5.
- Hook
- a map from a table of distances
- Mathematics
- Wishart, Hotelling, PCA, factor analysis, CCA, LDA, MDS, clustering and mixtures, graphical models
- Built
- statkit.multi
What you will be able to do
Bachelor's
- Rebuild a map from a table of distances by classical scaling, and say what the size of the negative eigenvalues tells you.
- Read a scree plot and a biplot, and explain why standardizing the variables changes the principal components.
Master's
- Derive Hotelling's T-squared from the union-intersection principle and convert it to its exact F statistic.
- Fit and compare PCA, maximum-likelihood factor analysis with varimax, CCA, LDA and QDA, and a Gaussian mixture by EM, and state what each one maximizes.
- Compute partial correlations from the precision matrix and read a graphical lasso path.
PhD
- Prove Bartlett's decomposition of the Wishart distribution and the Eckart-Young theorem by Weyl's inequality.
- Explain why the chi-squared calibration of T-squared fails when p/n does not vanish, and state what the Marchenko-Pastur law says about the sample eigenvalues.
Practice
- Report a discriminant or clustering analysis with leave-one-out error or the adjusted Rand index, and say why a mixture's BIC is not proof of the number of groups.
- Check p against n before inverting a sample covariance matrix, and switch to the exact F or a test without the inverse when they are comparable.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 23 min · Master's 46 min · PhD 54 min · Practice 27 min.
- 0A map from distancesBachelor's5 min
- 1The data matrixBachelor's4 min
- 2WishartPhD4 min
- 3Hotelling's T-squared and MANOVAMaster's4 min
- 4Principal componentsBachelor's5 min
- 5Factor analysisMaster's7 min
- 6Canonical correlationMaster's4 min
- 7Discriminant analysisPractice4 min
- 8ClusteringBachelor's5 min
- 9Graphical modelsMaster's4 min
- 10A high-dimensional warningPhD4 min
- 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 map from distancesBachelor's5 min
Suppose you are given no map at all, only a table: the distance by road between every pair of towns. Can you rebuild the map? In 1952 the psychologist Warren Torgerson showed how, for a very different purpose: people judge how similar things feel, and he wanted to place those judgements as points in a space whose distances match them. This part is about the structure hidden in many variables, and this is its first and most visual example.
The World has two hundred towns on its island. Roads join each town to its four nearest neighbours, and every road winds, ten to thirty percent longer than the straight line. The road distance between two towns is the length of the shortest route through the network: nineteen thousand nine hundred distances in all. A typical shortest route is about one point four four times the straight-line distance, because it zigzags through the network. Now throw the map away and keep only the table.
The trick is the cosine rule. A squared distance is two squared lengths minus twice an inner product. Subtract the row means and the column means of the squared distances and add back the grand mean, double-centring, and multiply by negative one half: the lengths cancel, leaving a matrix of inner products about the centroid. If the distances come from real points, that matrix is X times X transpose, Part 4's Gram matrix. So its top eigenvectors, scaled by root eigenvalue, are the coordinates: the best positive semidefinite rank-two Gram approximation in Frobenius norm, up to rotation and reflection. It need not minimize distance stress.
Here is the map classical scaling builds from the table alone. It comes out in an arbitrary orientation, so rotate, reflect and scale it onto the truth, Procrustes's fit. The gold rings mark where the towns really are. The island shape comes back, with a root mean squared error of about point five five on an island ten across. The residual lines show where road geometry distorts it. Two dimensions capture about eighty-five percent of the positive eigenvalue mass. Negative eigenvalues show these road distances are not exactly Euclidean; their absolute sum is about fourteen percent of the positive sum.
Real data: the Cambridge Encyclopaedia road-distance table between twenty-one European cities, two hundred and ten numbers. Classical scaling, with signs oriented using known Stockholm and Lisbon geography; north is not inferred from distances alone. Two dimensions hold eighty-seven percent of the structure. And the map of Europe appears: Lisbon and Gibraltar in the south-west, Stockholm in the north, Athens far to the south-east, Paris, Brussels and Cologne clustered in the middle, with positions reconstructed from distances, and the orientation supplied separately.
The pairs the map fits worst are instructive. Cologne to Geneva: the table says one thousand six hundred and sixty-two kilometres, the map about seven hundred. That is an entry worth checking against the source, but a low-dimensional residual alone does not prove a recording error. Athens to Rome: eight hundred kilometres in the table, seventeen hundred on the map. The table and a two-dimensional Euclidean approximation disagree. Routes, geography and model compression can all contribute; no route history is established here. A multivariate summary is also a check on the data that went into it.
How good is a map overall? This normalized raw distance stress compares map distances with table distances, dividing by the squared table distances. For Europe it is point oh nine, under this definition. Other stress conventions use different denominators, so named rating cutoffs do not transfer automatically. Roger Shepard and Kruskal went further, with nonmetric scaling: find a map whose distances are in the same order as the dissimilarities, ignoring their actual values. That is what psychologists needed, because people can say which two colours seem more alike, but not by how much.
The lesson of the map: a table of many numbers can have few real dimensions. Eigenvectors find them, here and again and again in this part: in scaling, principal components, factor analysis and canonical correlation. The covariance matrix and its inverse carry the geometry of the data. And when there are almost as many variables as observations, the classical toolkit breaks, which chapter ten makes precise.
Numbers: towns RMSE 0.55; Europe 87%, Cologne–Geneva 1,662 vs 713
1The data matrixBachelor's4 min
Part 5 introduced the object: the data matrix, n rows of units by p columns of variables. Its column means form the mean vector. The sample covariance matrix is the cross-product of the centred data over n minus one: p variances and p times p minus one over two covariances. Scaling by the standard deviations gives the correlation matrix. Almost everything in this part is a function of these two summaries.
The reference model is the multivariate normal, whose density depends on x only through a quadratic form in the inverse covariance. Its contours are ellipsoids, with axes along the eigenvectors of sigma and lengths proportional to the root eigenvalues. The quadratic form itself has a chi-squared distribution with p degrees of freedom: in the right coordinates it is a sum of p independent squared standard normals. And the sample mean and covariance, with divisor n, are the Gaussian maximum likelihood estimates when the fitted covariance is positive definite.
That quadratic form is Prasanta Chandra Mahalanobis's distance of 1936: the distance from x to the centre, measured with the inverse covariance. For uncorrelated variables with unit variance, this squared distance is ordinary Euclidean distance squared. It is unchanged by any change of units or any invertible linear transformation of the variables. It measures distance in units of the data's own spread in each direction: along the long axis of the cloud, a long way is not far.
There is a cleaner way to see it. Multiply the centred data by the inverse square root of the covariance. The new variables are uncorrelated with unit variance: the cloud has been made round, or whitened. And the Mahalanobis distance is just the ordinary Euclidean length of the whitened vector. Every Mahalanobis calculation is a Euclidean one in disguise. Whitening is not unique: the symmetric square root, the inverse Cholesky factor, or either followed by a rotation all work, because rotations do not change lengths.
The fifty versicolor irises from Fisher's paper, petal length against petal width. A circle of equal Euclidean distance ignores the shape of the cloud. The Mahalanobis contours follow it: ellipses at distance one and two, and in red a plug-in ninety-nine percent Gaussian reference contour, not an exact fitted coverage statement. Long petals tend to be wide, so the ellipse leans: a long, wide petal is ordinary, while a long, narrow one, at the same Euclidean distance, is unusual.
A multivariate normality check in one picture: the squared Mahalanobis distances of all fifty versicolors, using all four measurements. Plotted against chi-squared quantiles with four degrees of freedom they are roughly near the line. This radial diagnostic alone cannot establish joint normality. The largest is twelve and a half. Because mean and covariance are fitted to these same fifty flowers, the exact internal Gaussian marginal reference is a scaled beta, not chi-squared, and the distances are dependent. And the most outlying flower in this metric is not the one farthest from the mean in Euclidean terms: distance depends on direction.
A word on history. Mahalanobis designed his distance to compare body measurements of castes and communities in Bengal. Fisher's discriminant and the iris data appeared in the Annals of Eugenics, the journal of a movement whose aims this course does not share. The methods have long outlived those purposes, and the honest course is to use them while saying plainly where they came from. Mahalanobis also founded the Indian Statistical Institute and designed India's national sample surveys, a different legacy.
Numbers: max D² 12.5 vs cut 11.1
2WishartPhD4 min
Take m independent normal vectors with covariance sigma. The sum of their outer products has the Wishart distribution, found by John Wishart in 1928. The sample covariance, times n minus one, is Wishart with n minus one degrees of freedom and independent of the sample mean, the multivariate form of Part 8's theorem. In one dimension it is sigma squared times a chi-squared: the Wishart is the chi-squared of matrices.
Maurice Bartlett found the structure inside. Factor sigma by Cholesky. Then a Wishart matrix is L times A A transpose times L transpose, where A is lower triangular with chi-distributed diagonal, degrees of freedom falling by one down the diagonal, and independent standard normals below it. One consequence: the determinant, the generalized variance, is a product of independent chi-squareds. Statkit draws Wisharts this way.
A check, with three variables and ten degrees of freedom, twenty thousand draws. The average matrix divided by ten approximates sigma with Monte Carlo error; the mean entries are displayed with their standard errors. The variances of its entries match the theory too: two m sigma one one squared for a diagonal entry, and m times sigma one two squared plus sigma one one sigma two two for an off-diagonal one. The noise in an estimated covariance depends on the variances as well, which is why correlations are easier to compare than covariances.
The Wishart's main use is distribution theory. Every one-dimensional projection is a scaled chi-squared. From that, the next chapter's statistic, Hotelling's T squared, has an exact F distribution after rescaling, for any sample size. All of it needs the sample covariance to be invertible, which requires more observations than variables, chapter ten's warning.
The Wishart has an explicit density, a power of the determinant times an exponential of a trace. Its inverse is the conjugate prior for a normal covariance matrix, Part 26's language. With a flat prior on the unknown mean, independent of the covariance prior, integrating the mean gives an inverse-Wishart posterior: add n minus one to the degrees of freedom and the centered scatter to the scale matrix. But a single degrees-of-freedom parameter controls how certain the prior is about every variance and every correlation at once, which is why modern practice, as in Stan, often prefers separate priors on the scales and on the correlation matrix.
A warning already visible here. Suppose the true covariance is the identity, all eigenvalues one. The sample covariance is unbiased entry by entry, but its eigenvalues are not: the largest is too big on average and the smallest too small. The sample eigenvalues fan out. When p grows with n, Vladimir Marchenko and Leonid Pastur showed in 1967 that they have a limiting density on an interval determined by gamma, p over n, for independent standardized noise with suitable moments. When gamma exceeds one there is also an atom at zero.
Fifty variables, a hundred observations, true covariance the identity. Every true eigenvalue is one. The sample eigenvalues run from point one to two point seven six. The limiting Marchenko–Pastur curve is a reference for this one finite draw, not a guarantee that every eigenvalue stays inside its asymptotic edges. So a principal component analysis of pure noise would report a dominant direction nearly three times the average: with many variables, large sample eigenvalues are not evidence of structure. Part 52 returns to this.
Numbers: Var W₁₁ 80.4 vs 80; MP edges [0.084, 2.926] (p/(n−1) for the centered covariance)
3Hotelling's T-squared and MANOVAMaster's4 min
Do two species differ in their mean measurements? The null hypothesis is a vector: equal means in all p coordinates. Running p separate t-tests raises Part 33's multiple-testing problem, and ignores the correlations between the variables. Bonferroni's correction is valid, but still ignores how variables combine. Harold Hotelling's 1931 answer is a single test that uses the inverse covariance.
The cleanest derivation is S. N. Roy's union–intersection principle. For any linear combination of the variables there is an ordinary two-sample t statistic. Maximize its square over all combinations: by Cauchy–Schwarz in the metric of S, the maximum is T squared. The maximizing combination is S inverse times the difference in means, which chapter seven will meet as Fisher's discriminant. So T squared rejects exactly when some linear combination of the variables shows a significant difference, with the threshold chosen to account for the search.
Versicolor against virginica, fifty flowers each. The four separate t statistics run from minus three to minus fourteen and a half in size: petal width alone gives t squared of two hundred and fourteen. The best linear combination gives t squared of three hundred and fifty-five: that is T squared. Converted to F with four and ninety-five degrees of freedom, eighty-six, a p-value of ten to the minus thirty. The combination separates the species far better than any single measurement.
Project every flower onto that best combination. The two species barely overlap. The weights have one sign on the two sepal measurements and the opposite sign on the two petal measurements; the overall sign is arbitrary. So the combination asks: how big are the petals relative to the sepals? Virginicas have big petals for their sepal size, something no single measurement expresses.
Inverting the test gives a confidence region: an ellipsoid around the sample mean, shaped by S. Projecting the ellipsoid onto any direction gives an interval for that linear combination of the means. And because the ellipsoid contains the truth with probability ninety-five percent, all of these intervals hold simultaneously, for every combination, even ones chosen after looking at the data. The price is width. If you only care about a few combinations chosen in advance, Bonferroni intervals can be narrower; the ellipsoid insures against every question you might ask.
With more than two groups, MANOVA generalizes analysis of variance. The between-group sum of squares becomes a matrix H, the within-group sum a matrix E. Their comparison lives in the eigenvalues of E inverse H: F-like ratios along a sequence of best directions. With three species and four variables there are two nonzero eigenvalues, and there is no unique best way to reduce two numbers to one test. Hence four classical statistics.
The four, on all three iris species. Wilks's lambda, a product; Pillai's trace; the Hotelling–Lawley trace; Roy's largest root. The eigenvalues are thirty-two and point two nine: almost all the separation lies in one direction. Wilks's lambda is point oh two three, an F of a hundred and ninety-nine, and statkit reproduces statsmodels' four statistics to every printed digit. As for which to use: Pillai's trace is often recommended for robustness in balanced designs, while Roy's root targets one dominant direction; neither is uniformly best.
Cautions. T squared and MANOVA assume the groups share one covariance matrix. George Box's M test checks that, but it is so sensitive to non-normality that its verdicts are hard to use. With many variables relative to observations, S inverse becomes unstable, chapter ten's subject. And a significant result invites the real question: which combination of variables differs? The eigenvectors answer it.
Numbers: T² 355.5; Wilks 0.0234
4Principal componentsBachelor's5 min
Karl Pearson in 1901 asked for the line closest to a cloud of points; Hotelling in 1933 asked for the linear combination with the largest variance. They are the same question. Maximize a transpose S a over unit vectors. A Lagrange multiplier, Part 21, gives S a equals lambda a: the answer is the top eigenvector, and its variance is the top eigenvalue. The second component is the best direction orthogonal to the first, and so on; the components are uncorrelated. The eigenvalues add up to the total variance, so each component's share is its eigenvalue over the trace.
In practice, take the singular value decomposition of the centred data, Part 4. The scores are U D, the loadings are the columns of V, and the variances are the squared singular values over n minus one; no covariance matrix need ever be formed. Carl Eckart and Gale Young proved in 1936 that truncating the decomposition gives the best rank-k approximation of the data in squared error. That is why Pearson's and Hotelling's questions agree: by Pythagoras, the plane that keeps the most variance is the plane closest to the points.
Principal components come from the eigenvectors of X transpose X, a p by p matrix. The hook's classical scaling took the eigenvectors of X X transpose, an n by n Gram matrix built from distances. Both are halves of one singular value decomposition, so when the distances are Euclidean the scaling coordinates are exactly the principal component scores. For exactly Euclidean distances this reconstructs PCA scores from unseen coordinates. Road distances are not exactly Euclidean, so the hook instead uses a positive Gram approximation.
The US arrests data: rates of murder, assault and rape per hundred thousand in each of the fifty states in 1973, with the percentage of the population living in cities, all standardized. The first component weights the three crimes almost equally: an overall arrest-rate score; arrests are a proxy, not measured crime incidence, sixty-two percent of the variance. The second is mostly the urban percentage, another quarter. Gabriel's biplot of 1971 draws variable arrows alongside scores. Here arrows are loadings multiplied by two point six for display, not unscaled reconstruction coordinates. Now each state can be read: California and Nevada are high on arrest rates and urbanization, North Dakota and Vermont low on both, Mississippi and the Carolinas high in murder for how rural they are.
Raymond Cattell's scree plot, named for the rubble at the foot of a cliff: the eigenvalues in order. Sixty-two, twenty-five, nine and four percent. Two components keep eighty-seven percent of the variance, so the biplot we just read is a faithful summary of four-dimensional data. After the second bar the drop flattens: the elbow.
A choice that matters. On the irises in raw centimetres, the first component holds ninety-two and a half percent of the variance, and it is mostly petal length, the measurement with the largest spread. Standardize the four variables first and the first component drops to seventy-three percent and weights them more evenly. Principal components depend on units, so analysing the covariance or the correlation matrix is a decision, not a detail. Mahalanobis distance was invariant to units; principal components are not.
How many components to keep? Henry Kaiser's rule keeps eigenvalues of the correlation matrix above one, a crude rule. Cattell's elbow is subjective. John Horn's parallel analysis of 1965 is better: compare each eigenvalue with the same eigenvalue from data of the same size with no structure at all. And chapter two told us what that comparison looks like: the largest eigenvalue of pure noise is near one plus root p over n, squared, not one. Kaiser's rule ignores this sample-noise spread and can overselect in high-dimensional noise models.
Four cautions. The sign of a component is arbitrary: a and minus a are equally good, and software disagrees. Components describe variance, not mechanisms. A direction of large variance need not be the one that predicts an outcome; regression on the first few components can throw away exactly the signal you wanted. And because variance is not robust, a single gross outlier can claim a whole component. Part 30's minimum covariance determinant gives a robust covariance to decompose instead.
Numbers: 62% + 25%; iris 92.5% raw vs 73% standardized
5Factor analysisMaster's7 min
In 1904 Charles Spearman noticed that children's marks in very different subjects, classics, French, music, all correlated positively. He proposed that each mark is one general factor, which he called g, plus a part specific to the test. In the 1930s Louis Thurstone allowed several factors, and introduced the idea of rotating them to make them interpretable. What g is, and whether it is anything at all, has been argued for a century, often bitterly. The statistics can settle less than either side has wished: a factor model describes a pattern of covariance, and does not by itself show that a factor is a real thing.
The model: each of p observed scores is a mean, plus loadings times k unobserved factors, plus an independent error specific to that score. Then the covariance is L L transpose plus a diagonal: every correlation between two tests runs through the common factors. Each variance splits into a communality, the part shared with other tests, and a uniqueness. The model is economical: with twenty-four tests and four factors, there are a hundred and twenty coefficients, minus six rotational redundancies: a hundred and fourteen covariance parameters versus three hundred.
One fact shapes everything that follows. Rotate the loadings by any orthogonal matrix and the implied covariance does not change. So the data determine the loadings only up to rotation, and the analyst chooses a rotation to make them interpretable. Estimation is by maximum likelihood, Derrick Lawley's in 1940 and Karl Jöreskog's practical algorithm of 1967, minimizing this discrepancy between the model and the sample correlations over the uniquenesses. And Bartlett's corrected likelihood-ratio statistic tests whether k factors suffice.
The classic data: Karl Holzinger and Frances Swineford gave twenty-four tests to a hundred and forty-five schoolchildren in a Chicago suburb, as documented in Harman's table. Spatial tests like cubes and flags; verbal tests like paragraph comprehension; speeded tests like addition and counting dots; memory tests like word and number recognition. All but one of the two hundred and seventy-six correlations are positive; their average is point three. The first eigenvalue of the correlation matrix is eight point one, a third of the total: Spearman's pattern, a strong general factor.
How many factors? Bartlett's test, for one to five. One factor is rejected with a p-value of ten to the minus thirty-three: a general factor alone does not explain these correlations. Two and three factors are rejected too. Four factors give a p-value of point oh two two, so even four are rejected at five percent; five factors give point one three. Four are retained here for an interpretable illustration, not as a model accepted by the five-percent test. But with a large enough sample, a fixed misspecified model can be rejected; the test is a guide to how much structure the data can support, not a verdict on the truth.
The four-factor loadings, as a heat map: twenty-four tests down, four factors across, brighter for a larger absolute loading; the heat map omits signs. As estimated, the first factor loads on every test, between a third and three quarters: that is Spearman's g. Now rotate by Henry Kaiser's varimax criterion of 1958, the rotation that makes the squared loadings in each column as spread out as possible. Each test now loads mostly on one factor, and the factors can be named: verbal, speed, spatial, memory. Nothing about the fit changed. The two pictures imply exactly the same covariance matrix. Rotation changes the description within the same four-factor model. It cannot turn four factors into one: the one-factor model was rejected. These rotations do not uniquely identify named psychological or causal entities.
A child's factor scores must be estimated. Godfrey Thomson's regression scores are the conditional expectation of the factors given the tests under the joint Gaussian model. Bartlett's scores are a weighted least-squares fit of the loadings to the child's results, conditionally unbiased given the factors when the loadings have full rank; regression scores instead minimize mean squared error under the model. Neither recovers the factors exactly; with finitely many tests and positive uniquenesses there is posterior uncertainty left, an old and much argued point. And the rotation need not be orthogonal. Oblique rotations such as promax let the factors correlate with each other, which for abilities is usually more realistic; a second-order factor analysis of those correlations brings back a general factor.
A warning sign to watch for. Sometimes the likelihood pushes a uniqueness to zero, so that one test is explained entirely by the factors. Unconstrained algorithms can even return a negative variance. These are Heywood cases, after H. B. Heywood's paper of 1931. They signal too many factors, too small a sample, or a wrong model. The four-factor fit here has no active lower uniqueness bound: the fitted uniquenesses lie between about a quarter and four fifths. This constrained optimizer checks the specified numerical floor, not every possible Heywood solution.
Factor analysis and principal components are often confused. Components are a rotation of the data; factors are a model. Components explain total variance; factors explain covariance, the off-diagonal part, and set each test's specific variance apart. Component scores are exact linear combinations of the data; factor scores must be estimated. And maximum likelihood factor analysis is equivariant under rescaling with free uniquenesses: fitted covariance and loadings rescale, while the fit criterion is preserved; PCA generally changes. When the uniquenesses are small and similar the two give much the same answer; when they are not, they can differ a great deal.
Numbers: k = 4, p = 0.022; varimax: four named factors
6Canonical correlationMaster's4 min
Sometimes the variables come in two blocks: a country's demography, and its economy. Hotelling asked in 1936 for the linear combination of one block and the linear combination of the other that are as highly correlated as possible. When the second block is a single variable, this is just the multiple correlation of regression, Part 12's R. After the first pair comes the best pair uncorrelated with it, and so on, up to the smaller of the two block sizes.
The answer is, once more, a singular value decomposition. Whiten each block by its own covariance and form the cross-covariance between the whitened blocks. Its singular values are the canonical correlations, and its singular vectors, unwhitened, are the canonical weights. Under joint Gaussian assumptions and nonsingular within-block covariance, Bartlett's large-sample statistic tests whether all correlations after the k-th are zero.
The data are Arlie Sterling's savings data, made famous by Belsley, Kuh and Welsch: fifty countries, averaged over the 1960s. One block is demographic: the percentage of the population under fifteen and over seventy-five. The other is economic: the aggregate savings rate, disposable income per head, and its growth rate. The question comes from Franco Modigliani's life-cycle hypothesis: people save in middle age and draw down savings when young or old, so a country's age structure should be linked to its savings.
The first pair of canonical variates, one dot per country. Their correlation is point eight two. The demographic variate runs from young populations on the left to old ones on the right. The economic variate runs from poor to rich. At the top right, the old, rich countries of Western Europe and North America; at the bottom left, young, poor ones. Age structure and the economy move together, strongly.
To interpret a canonical variate, correlate it with the original variables. The first demographic variate is almost exactly minus the share under fifteen and plus the share over seventy-five. The first economic variate is mostly income, with savings contributing. The first canonical correlation is overwhelmingly significant. The second, point three seven, has an unadjusted approximate p-value of point oh four; interpreting several sequential tests also raises multiplicity questions. Use these structure correlations, not the raw weights: when the variables in a block are correlated, as under-fifteen and over-seventy-five are, the weights can have surprising signs.
A geometric reading. Each block of centred data spans a subspace of n-dimensional space. The canonical correlations are the cosines of the principal angles between those two subspaces, found by Camille Jordan in 1875. The first angle is the smallest angle between any vector in one subspace and any vector in the other. Here thirty-four degrees, then sixty-nine. And a caution: when p plus q approaches n, two random subspaces nearly intersect, so the first canonical correlation approaches one by chance alone.
With many variables in either block, canonical correlation overfits: the first correlation creeps towards one even when the blocks are unrelated. The cures echo chapter ten. Add a ridge to each block's covariance before inverting it. Or ask for sparse weights, with only a few non-zero. Or maximize covariance with unit-length weights instead of correlation, which needs no covariance inverse: Herman Wold's partial least squares, widely used in chemistry and genomics.
Step back and a family appears. Principal components are the SVD of the data. Canonical correlation is the SVD of the whitened cross-covariance. Discriminant analysis, next, is canonical correlation between the measurements and a set of group indicators. And correspondence analysis, Jean-Paul Benzécri's method, is the SVD of a contingency table's standardized residuals. One decomposition underlies them all.
Numbers: r = 0.82, 0.37; 34°, 69°
7Discriminant analysisPractice4 min
Fisher's question in 1936: which linear combination of the measurements best separates groups we already know? He maximized the between-group variance relative to the within-group variance. The answer is an eigenvector of W inverse B, MANOVA's eigenproblem from chapter three. With two groups it is W inverse times the difference in means, the direction that maximized Hotelling's t. C. R. Rao extended the idea to many groups in 1948: with g groups there are up to g minus one discriminant directions.
There is also a probabilistic route. Suppose each group is normal with its own mean and covariance. If the covariances are equal, the log odds of one group against another are linear in x, and the Bayes classifier draws straight boundaries: linear discriminant analysis, and for two groups it uses Fisher's direction, with the threshold also depending on priors and losses. Let each group have its own covariance and the boundaries become quadratic. QDA estimates g times as many covariance parameters, a trade between bias and variance, Part 19's theme.
Linear discriminant analysis and logistic regression both produce log odds that are linear in x, but they get there differently. LDA models how the measurements are distributed within each group. Logistic regression, Part 24, models the probability of the group given the measurements, and nothing else. If the data really are normal with a common covariance, Bradley Efron showed in 1975 that LDA is more efficient, with the relative efficiency depending on separation and the precise model, rather than a fixed sample-size saving. If they are not, LDA's extra assumptions can mislead it, while logistic regression avoids the predictor-distribution model if its conditional logit is correctly specified. Neither method is uniformly safer.
All hundred and fifty irises projected onto Rao's two discriminant directions. The first direction carries ninety-nine percent of the separation; the second adds almost nothing. Setosa sits far away on its own; versicolor and virginica overlap a little at their edges.
In two dimensions the rules can be drawn. Petal length and width, with the regions LDA assigns to each species. Its boundaries are straight lines. QDA's boundaries curve, bending around the tighter setosa cloud and the wider virginica one. Leaving out each flower in turn, LDA misclassifies four percent and QDA three: with only two variables, the extra flexibility is affordable.
With all four measurements, both rules misclassify three of the hundred and fifty flowers they were fitted to. Leaving each flower out, LDA still errs on three, while QDA errs on four: its twenty extra covariance parameters do not improve this leave-one-out count. One mistake of difference is not evidence of a universal ranking. The gap between training and held-out error is Part 19's lesson, and it grows quickly with the number of variables.
The history, as promised. The botanist Edgar Anderson collected the irises, mostly on the Gaspé Peninsula in Quebec, to study how species evolve. Fisher used them to illustrate the discriminant, in a 1936 paper in the Annals of Eugenics, a journal Fisher edited, and eugenic questions were among the applications he had in mind. Rao's multi-group extension grew from Mahalanobis's measurements of Indian castes. Today the method is a standard baseline classifier, used in everything from medical diagnosis to face recognition.
Numbers: 99.1% on LD1; LOO 2.0% vs 2.7%
8ClusteringBachelor's5 min
Discriminant analysis needs the groups to be known. Clustering looks for groups nobody labelled. The k-means objective: choose k centres and an assignment of points to them to minimize the total squared distance from each point to its centre. Stuart Lloyd's algorithm, written at Bell Labs in 1957 and published only in 1982, alternates: with the assignment fixed, the best centres are the cluster means; with the centres fixed, the best assignment sends each point to its nearest centre. Neither step can increase the objective, so the algorithm stops, at a Lloyd fixed point with consistent tie handling, not necessarily the global optimum, which is why it is run from many starts.
Petal length and width again, this time without species labels, and a deliberately bad start: two of the three centres among the small setosa petals. Assign each flower to its nearest centre, move each centre to its cluster's mean, and repeat. The middle centre is pulled out of the setosas and up towards the versicolors, and the within-cluster sum of squares falls from three hundred and twenty-eight to thirty-one. After nine rounds nothing changes. The clusters match the species well, an adjusted Rand index of point eight nine, though nobody told the algorithm the species existed.
A model makes the method clearer. Suppose each flower belongs to one of k unseen groups, each normal with its own mean and covariance: Part 22's Gaussian mixture. The E-step computes each point's probability of belonging to each group, and the M-step re-estimates the means, covariances and proportions with those weights. Force all covariances to be the same tiny sphere and the probabilities become zeros and ones: k-means is EM with hard assignments, as the zero-variance limit with positive fixed weights away from ties; classification EM at a fixed variance also retains assignment and weight terms.
A three-component normal mixture fitted by EM to all four measurements, shown on the petals. The ellipses are each component's two-standard-deviation contour. Unlike k-means, the components can lean and stretch, following the shape of each species. The adjusted Rand index against the true species, where one means perfect agreement and zero is the expectation under a fixed-margin random-partition reference, is point nine for the mixture and point seven three for k-means on the same four variables.
Mixtures have pitfalls of their own. Put one component on a single point and shrink its covariance: the likelihood goes to infinity. The unconstrained global maximum does not exist. Our finite fits use a declared diagonal covariance ridge of one millionth; they are checked numerical local fits. Relabelling the components gives k factorial identical maxima, label switching, which matters for Bayesian mixtures. EM can settle at a stationary point, saddle or boundary behavior, so it is run from many starts, as k-means is. In practice the covariances are regularized or supplied with a suitable prior; the exact objective and convergence still need checking.
That index deserves a word. The adjusted Rand index of Lawrence Hubert and Phipps Arabie counts pairs of points that two partitions treat alike, corrected for the agreement expected by chance. Cluster labels are arbitrary, so it compares partitions, not names. One means the same partition, zero is chance-level expectation under that fixed-margin reference; negative values are possible. And we could only compute it because the species were known. In a real clustering problem there is no answer key.
How many clusters? The k-means objective always falls as k grows, so one looks for an elbow, here at two or three. The fitted regularized mixture gives Part 28's BIC as a useful heuristic; mixture singularities limit its regular-model derivation. It is lowest at two, not three: versicolor and virginica overlap enough that one stretched component describes them about as well as two. There are three species, but this model and criterion prefer two components. That does not establish the true number of density modes or biological groups. A cluster is a region of high density, not a natural kind.
Cautions. K-means returns the requested partition even from structureless data; some density algorithms may instead label points as noise. Rescaling a variable changes k-means's answer, because it changes the distances. There are other notions of cluster: hierarchical trees that merge points step by step, density-based methods that find connected regions, and spectral methods that cut a similarity graph. Whether a cluster is real is a statistical question: at the least, check its resampling stability and relevance to the task. Stability alone does not prove a natural kind or a unique true partition.
Numbers: ARI 0.89 / 0.90 / 0.73; BIC picks 2
9Graphical modelsMaster's4 min
In the twenty-four tests every pair is correlated, but a correlation mixes direct and indirect association. Partial correlation measures residual linear association after adjustment: regress both variables on all the others and correlate what is left. All of them at once come from the inverse covariance, the precision matrix: minus each entry over the root of the two diagonal entries. For the tests the average correlation is point three, but sixty percent of their absolute values are below point one. Word classification and word meaning correlate point five three; given the other twenty-two tests, their partial correlation is zero to two decimals.
For normal data, a zero in the precision matrix means more than a zero partial correlation: it means the two variables are independent given all the others. Draw an edge between every pair whose entry is non-zero and you have a Gaussian graphical model. The graph can be read: if every path from one set of variables to another passes through a third set, the first two are independent given the third. Arthur Dempster in 1972 called the problem of choosing the zeros covariance selection.
The twenty-four tests as nodes, coloured by the factor each loads on most. Draw every estimated partial correlation as an edge, thicker for larger values: two hundred and seventy-six edges. A hairball. Unpenalized estimated partial correlations are generally not exactly zero, so the plain inverse covariance gives a complete graph that says nothing.
The graphical lasso adds a penalty on the absolute values of the off-diagonal entries to the normal log likelihood. Without the penalty the maximizer is S inverse, the hairball. Jerome Friedman, Trevor Hastie and Robert Tibshirani showed in 2008 that it can be solved one column at a time, each column a lasso regression of one variable on the others, by coordinate descent. The absolute-value penalty sets entries exactly to zero, and larger lambda generally makes a sparser graph, although individual edges need not form a nested path. Why the absolute value produces exact zeros is the subject of Part 32.
A simpler route to the same graph. Regress each variable on all the others. The regression coefficients are proportional to the precision matrix's entries, so a zero coefficient is a missing edge. Nicolai Meinshausen and Peter Bühlmann ran a separate lasso for each variable and drew an edge when the coefficient was non-zero, in one regression or in both. They proved it recovers the right graph with high probability under conditions that Part 52 makes precise.
The graphical lasso with a large penalty, lambda point five: sixteen edges. Lower it to point four: forty-five. And point three: ninety-seven. The strongest direct links appear within the factor groups, and the verbal tests form a tight clique. Edges between groups run mostly through the reasoning tests, like deduction and series completion, which draw on several abilities at once. The factor model and the graph are two descriptions of the same correlations: one by latent shared variation, one by conditional links.
Reading such a graph. An absent edge represents conditional independence in the fitted Gaussian model. Estimation and tuning can miss or add population edges. A present edge is not a cause: the graph has no arrows. The penalty trades edges against reliability, and is chosen by cross-validation, BIC, or by keeping only the edges that survive resampling. Graphs with arrows come in Part 36, and what data alone can say about causal direction in Part 62.
Numbers: 276 → 97 → 45 → 16 edges
10A high-dimensional warningPhD4 min
The two-sample T squared has two calibrations. For fixed p and growing n it is approximately chi-squared with p degrees of freedom. For independent Gaussian samples with the same positive definite covariance and p below the total sample size minus one, a rescaled version is exactly F. These agree when p is small. When p grows in proportion to n, the chi-squared approximation fails: the small eigenvalues of S from chapter two blow up S inverse and inflate T squared. And once p reaches the total sample size minus one, S is singular and T squared does not exist at all.
A simulation. Two samples of fifty from the same normal distribution, so every rejection is false, two thousand times at each number of variables. With the chi-squared calibration, the false-rejection rate is five percent at two variables, ten at ten, a third at twenty-five, and seventy-two percent at forty. The exact F calibration holds five percent all the way, as it must for normal data. And a test that does not invert S at all, Bai and Saranadasa's, stays near six percent.
On the Board, as sizes. The chi-squared calibration is kept at two variables, and broken at twenty-five and forty. The exact F is kept at forty, and so is Bai–Saranadasa, a little above five percent but within the Board's tolerance. The method that was fine for decades of small-p textbook problems fails without warning when the variables multiply.
Zhidong Bai and Hewa Saranadasa's idea of 1996 is to stop inverting S. Use the plain squared distance between the mean vectors, minus its expected value under the null. That is unbiased for the squared distance between the true means. Standardized by an estimate of its standard deviation, it is asymptotically normal as p and n grow together. It requires moment and spectral conditions for its asymptotic calibration, but no covariance inverse, including when p exceeds n.
The second cure is to shrink. Mix the sample covariance with a multiple of the identity. That pulls the sample eigenvalues back towards their average, undoing the fanning-out of chapter two. Olivier Ledoit and Michael Wolf showed in 2004 how to estimate the best mixing weight from the data themselves. For a positive mixing weight and positive trace the estimate is positive definite; conditioning still depends on the weight and spectrum. Such regularization can support prediction when p exceeds n. Substituting it in T squared does not preserve the classical exact F law. It is Part 25's idea of borrowing strength, applied to a matrix.
Validity is not enough; what about power? Shift every coordinate's mean by point one five standard deviations, so more variables means more total signal. Bai–Saranadasa's power climbs steadily, from a third to ninety-five percent. The exact T squared's climbs at first, then collapses. At ninety variables it has nine denominator F degrees of freedom, despite estimating a ninety-by-ninety covariance, and its power is sixteen percent against ninety-five. Estimating S inverse costs more than it gains.
The lesson of this chapter. The classical multivariate toolkit is built on S inverse, and S is unreliable whenever the ratio of variables to observations is not small. Sample eigenvalues spread out, canonical correlations approach one by chance, and discriminant rules overfit. There are three cures: do without the inverse, as Bai and Saranadasa did; shrink the covariance towards something simpler; or assume that most of the structure is zero, as the graphical lasso did. That last idea, sparsity, is the next part. The full theory of high dimensions comes in Parts 51, 52 and 59.
Numbers: χ² size 72% at p = 40; power 0.16 vs 0.95
Recap, problems, and the road aheadAll tracks3 min
Part thirty-one in twelve lines. Classical scaling rebuilt a map from nothing but road distances, and identified entries whose residuals warrant source checking. Mahalanobis distance measures distance in the data's own units. The Wishart distribution is the chi-squared of covariance matrices. Hotelling's T squared is the largest t squared over all linear combinations, and MANOVA's four statistics summarize one eigenproblem. Principal components are the SVD of the data, and depend on its units. Orthogonal rotations within the same four-factor model preserve its covariance; a one-factor model is a different restriction. Canonical correlation linked age structure to income across fifty countries. Discriminant analysis misclassified two percent of the irises, and clustering, without labels, found two components preferred by this regularized mixture BIC, not two biological species. For a Gaussian population, zeros in its inverse covariance mean conditional independence, and the graphical lasso finds them. And when the number of variables grows with the sample, the chi-squared calibration fails and methods that avoid S inverse take over.
A promise for later. This part treated the sample covariance as a good estimate of the true one, and read structure from its top eigenvectors. That quietly assumed the number of variables stays fixed while the sample grows. Part 52 drops the assumption. With random-matrix theory it shows exactly where sample eigenvalues fall, and proves that a real component weaker than a sharp threshold is invisible to principal components, under the specified high-dimensional spiked-model asymptotics.
Where it comes back. Part 32 explains the graphical lasso's penalty, and sparsity in general. Part 33 tests thousands of correlated hypotheses. Part 36 matches treated and control units by Mahalanobis distance. Part 41 returns to latent variables, as measurement error. Part 52 proves the Marchenko–Pastur law and studies spiked covariance models, and Part 50 shows why sparse principal components may be computationally hard. Part 59 redoes classical tests when p and n grow together, and Part 60 makes covariance estimation robust in high dimensions.
Six problems, with full solutions in the README. Why double-centring recovers the Gram matrix; the union–intersection derivation of T squared; the Eckart–Young theorem; the invariance of canonical correlations; zeros of the precision matrix as zero regression coefficients; and why Lloyd's algorithm stops. Pause here if you want to try them.
The books this part follows: T. W. Anderson's classic text; Mardia, Kent and Bibby; Muirhead's distribution theory; Jolliffe on principal components; Lauritzen on graphical models; and The Elements of Statistical Learning; with the papers from Pearson to Friedman, Hastie and Tibshirani.
Thirty-one parts of sixty-five. We can find structure in many correlated variables, and we know when the classical tools stop working. The graphical lasso set most of a matrix to zero, and that was what made it work. Part 32 asks how far that idea goes: how can you solve for a thousand unknowns from a hundred equations? Sparsity.
Where it goes next. The graphical lasso's penalty returns as sparsity in Part 32, and thousands of correlated tests in Part 33; Mahalanobis matching returns in Part 36; the Marchenko-Pastur law, the spiked model and Ledoit-Wolf shrinkage are proved in Part 52, and proportional asymptotics in Part 59.
Key results
The part's results in one place, for revision.
Try it
Lab 31 · Hotelling's T-squared when p approaches n
Draw two samples of 50 from the same p-variate normal two thousand times for p = 2, 10, 25 and 40, and compare the size of the two-sample T-squared test under its chi-squared and its exact F calibration with the size theory predicts.
python -m videos.stats.labs 31
needs numpy, scipy, matplotlib · download lab31.py ·
source on GitHubclassical scaling from exact distances: RMSE of the map 3.0e-15 (theory 0)
p = 2: size at 5% chi-squared 5.3% (theory 5.6%) exact F 4.5% (theory 5.0%)
p = 10: size at 5% chi-squared 9.0% (theory 10.2%) exact F 4.3% (theory 5.0%)
p = 25: size at 5% chi-squared 32.5% (theory 32.7%) exact F 4.8% (theory 5.0%)
p = 40: size at 5% chi-squared 71.8% (theory 71.9%) exact F 4.5% (theory 5.0%)
With two samples of 50 the chi-squared calibration is a fixed-p approximation: it rejects one true null in three at p = 25 and most of them at p = 40, while the exact F holds its 5% throughout.
The code (75 lines; it asserts its own result)
"""Lab 31: test equal mean vectors as the number of variables grows, and see which calibration of T-squared survives."""
import numpy as np
from scipy import stats
from videos.coursekit import labs
from explainer.stats.kit import multi
TITLE = "Hotelling's T-squared when p approaches n"
GOAL = ("Draw two samples of 50 from the same p-variate normal two thousand times for p = 2, 10, 25 and 40, and compare "
"the size of the two-sample T-squared test under its chi-squared and its exact F calibration with the size "
"theory predicts.")
TASKS = [
"Shift every coordinate of the second sample by 0.15 and add multi.bai_saranadasa. At which p does it overtake the exact F in power?",
"Give the two samples different covariance matrices (multiply one sample by 2). Does the exact F keep its 5%?",
"Replace the normal draws by t with 5 degrees of freedom. Which calibration is hurt more at p = 2, and at p = 40?",
]
N1 = N2 = 50
PS = (2, 10, 25, 40)
def chi2_size(p, m=N1 + N2 - 2, alpha=0.05):
"""The exact size of 'reject when T2 exceeds the chi-squared_p critical value': T2 is a multiple of an F."""
return float(stats.f.sf(stats.chi2.ppf(1 - alpha, p) * (m - p + 1) / (p * m), p, m - p + 1))
def run(seed=0):
rng = np.random.default_rng(seed)
reps = 2000
lab = labs.Lab()
# the opening claim first: classical scaling is exact for Euclidean distances
towns = rng.uniform(0, 10, (40, 2))
D = np.linalg.norm(towns[:, None] - towns[None], axis=2)
mds = multi.classical_mds(D)
rmse = multi.procrustes(towns, mds["X"])["rmse"]
lab.row("classical scaling from exact distances: RMSE of the map", f"{rmse:.1e} (theory 0)")
assert rmse < 1e-8 and mds["negative_share"] < 1e-10, "a Euclidean distance table is reproduced exactly"
size_chi, size_f, t2 = {}, {}, {}
for p in PS:
out = [multi.hotelling_two(rng.standard_normal((N1, p)), rng.standard_normal((N2, p))) for _ in range(reps)]
size_chi[p] = np.mean([o["p_chi2"] < 0.05 for o in out])
size_f[p] = np.mean([o["p"] < 0.05 for o in out])
t2[p] = np.array([o["T2"] for o in out])
lab.row(f"p = {p:>2}: size at 5%", f"chi-squared {size_chi[p]:.1%} (theory {chi2_size(p):.1%}) "
f"exact F {size_f[p]:.1%} (theory 5.0%)")
se = np.sqrt(max(chi2_size(p) * (1 - chi2_size(p)), 0.05 * 0.95) / reps)
assert abs(size_chi[p] - chi2_size(p)) < 4 * se, "the chi-squared calibration's size is the F tail it implies"
assert abs(size_f[p] - 0.05) < 4 * np.sqrt(0.05 * 0.95 / reps), "the exact F keeps its level at every p"
assert size_chi[2] < 0.08 and size_chi[40] > 0.6, "fine at p = 2, broken at p = 40"
lab.note = ("With two samples of 50 the chi-squared calibration is a fixed-p approximation: it rejects one true null "
"in three at p = 25 and most of them at p = 40, while the exact F holds its 5% throughout.")
fig, ax = labs.figure(2, size=(11, 4.2))
grid = np.arange(1, 61)
ax[0].plot(grid, [chi2_size(p) for p in grid], color=labs.RED, label="chi-squared calibration, theory")
ax[0].plot(PS, [size_chi[p] for p in PS], "o", color=labs.RED, label="chi-squared calibration, simulated")
ax[0].plot(PS, [size_f[p] for p in PS], "s", color=labs.GREEN, label="exact F, simulated")
ax[0].axhline(0.05, color=labs.MUTED, ls="--", label="nominal 5%")
ax[0].set(title="Size of the two-sample test, n1 = n2 = 50", xlabel="number of variables p",
ylabel="share of true nulls rejected")
ax[0].legend()
p, m = 40, N1 + N2 - 2
xs = np.linspace(0, np.quantile(t2[p], 0.995), 300)
c = p * m / (m - p + 1)
ax[1].hist(t2[p], bins=60, range=(0, xs[-1]), density=True, color=labs.BLUE, alpha=0.6, label="2,000 simulated T-squared")
ax[1].plot(xs, stats.chi2.pdf(xs, p), color=labs.RED, label="chi-squared with 40 df")
ax[1].plot(xs, stats.f.pdf(xs / c, p, m - p + 1) / c, color=labs.GREEN, label="scaled F(40, 59)")
ax[1].axvline(stats.chi2.ppf(0.95, p), color=labs.RED, ls=":", lw=1.2)
ax[1].set(title="p = 40: the null law of T-squared", xlabel="T-squared", ylabel="density")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Shift every coordinate of the second sample by 0.15 and add multi.bai_saranadasa. At which p does it overtake the exact F in power?
- Give the two samples different covariance matrices (multiply one sample by 2). Does the exact F keep its 5%?
- Replace the normal draws by t with 5 degrees of freedom. Which calibration is hurt more at p = 2, and at p = 40?
Problems, with solutions
Try each problem before opening its solution.
1. Double-centring. Show that \(B = -\tfrac12 J D^{(2)} J\) equals \(X_0 X_0^\top\) when \(D\) holds the Euclidean distances between the rows of \(X\).
Solution
Let x_i be the rows of X and X₀ = JX the centred rows x̃_i. Then d²_ij = ‖x̃_i‖² + ‖x̃_j‖² − 2x̃_iᵀx̃_j, so D⁽²⁾ = a1ᵀ + 1aᵀ − 2X₀X₀ᵀ with a_i = ‖x̃_i‖². Since J1 = 0, J(a1ᵀ)J = 0 and J(1aᵀ)J = 0. Hence −½JD⁽²⁾J = J X₀X₀ᵀ J = X₀X₀ᵀ, because JX₀ = X₀.
2. Union–intersection. Show that \(\max_a t^2(a) = \tfrac{n_1 n_2}{n_1 + n_2} d^\top S^{-1} d\), \(d = \bar x_1 - \bar x_2\), attained at \(a \propto S^{-1} d\).
Solution
Let c = n₁n₂/(n₁ + n₂) and d = x̄₁ − x̄₂. Then t²(a) = c(aᵀd)²/(aᵀSa). Write b = S^{1/2}a. Then aᵀd = bᵀS^{−1/2}d, and Cauchy–Schwarz gives (aᵀd)² ≤ ‖b‖²·‖S^{−1/2}d‖² = (aᵀSa)(dᵀS⁻¹d). So t²(a) ≤ c·dᵀS⁻¹d = T², with equality iff b ∝ S^{−1/2}d, i.e. a ∝ S⁻¹d.
3. Eckart–Young. Prove Eckart–Young for the Frobenius norm: the best rank-\(k\) approximation of \(X_0\) truncates its SVD.
Solution
Let X₀ = UDVᵀ and let B have rank ≤ k. By Weyl's inequality for singular values, σ_{i+k}(X₀) ≤ σ_i(X₀ − B) + σ_{k+1}(B) = σ_i(X₀ − B). So ‖X₀ − B‖²_F = Σ_i σ_i(X₀ − B)² ≥ Σ_i σ_{i+k}(X₀)² = Σ_{j>k} d_j². The truncated SVD attains this.
4. Invariance of canonical correlations. Show that the canonical correlations are invariant to invertible linear maps of \(x\) and of \(y\) separately.
Solution
Replace x by Ax + a and y by By + b, with A and B invertible. Then for any weights, corr(αᵀ(Ax), βᵀ(By)) = corr((Aᵀα)ᵀx, (Bᵀβ)ᵀy). As α and β range over all vectors, so do Aᵀα and Bᵀβ. The sequence of constrained maxima, each uncorrelated with the earlier variates (also invariant), is therefore the same.
5. Zeros of the precision matrix. Show that \(\theta_{ij} = 0\) iff the coefficient of \(x_j\) is zero in the regression of \(x_i\) on all the others.
Solution
Partition x = (x_i, x_{−i}). For the normal, E(x_i | x_{−i}) = μ_i + Σ_{i,−i}Σ_{−i,−i}⁻¹(x_{−i} − μ_{−i}). By the block-inverse formula, the i-th row of Θ = Σ⁻¹ gives Θ_{i,−i} = −θ_ii Σ_{i,−i}Σ_{−i,−i}⁻¹. So the regression coefficient of x_j is β_ij = −θ_ij/θ_ii, which is zero iff θ_ij = 0. For the normal, the conditional distribution of x_i given the rest then does not involve x_j: conditional independence.
6. Lloyd's algorithm stops. Show that \(k\)-means's objective never increases under Lloyd's two steps, and that it stops in finitely many.
Solution
With the assignment fixed, Σ_{i∈C_j}‖x_i − c‖² is minimized by the mean (its gradient is 2Σ(c − x_i)), so the update step cannot increase the objective. With the centres fixed, sending each point to its nearest centre minimizes each term separately. So the objective is non-increasing. There are finitely many partitions of n points into k groups. If ties are broken consistently, a strict decrease is needed to change the partition, so no partition repeats and the algorithm stops in finitely many steps, at a Lloyd fixed point. This is not necessarily a global optimum; tie and empty-cluster handling must be specified.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| sparsity; the graphical lasso's penalty | 32 |
| thousands of correlated tests | 33 |
| Mahalanobis matching | 36 |
| latent variables and measurement error | 41 |
| sparse PCA's computational barrier | 50 |
| Marchenko–Pastur; the spiked model; Ledoit–Wolf | 52 |
| proportional asymptotics | 59 |
| robust covariance in high dimensions | 60 |
| the Coverage Board | every part; 65 |
Glossary
- Classical (metric) scaling; Gram matrix; double-centring; Procrustes; stress; nonmetric scaling: maps from distances and how well they fit.
- Mahalanobis distance; whitening: distance in the data's own units; the transformation that makes it Euclidean.
- Wishart; Bartlett decomposition; inverse-Wishart; Marchenko–Pastur law: the distribution of a sample covariance, its triangular structure, its conjugate prior, and its eigenvalues when p/n → γ.
- Hotelling's T²; union–intersection; simultaneous confidence ellipsoid: the multivariate t-test and its intervals.
- MANOVA; H and E; Wilks, Pillai, Hotelling–Lawley, Roy: between- and within-group matrices and four summaries of E⁻¹H.
- Principal component; loading; score; scree plot; biplot; parallel analysis: directions of greatest variance and how to read and count them.
- Factor; loading; communality; uniqueness; rotation (varimax, oblique); Heywood case; factor score: the latent factor model and its vocabulary.
- Canonical correlation; canonical variate; structure correlation; principal angle; PLS: the best-correlated pairs of combinations of two blocks.
- LDA; QDA; discriminant direction; leave-one-out error: classifying into known groups.
- k-means; Lloyd's algorithm; Gaussian mixture; EM; BIC; adjusted Rand index: finding unknown groups and judging them.
- Partial correlation; precision matrix; Gaussian graphical model; covariance selection; graphical lasso; neighbourhood selection: conditional independence and its graph.
- Bai–Saranadasa test; Ledoit–Wolf shrinkage: tools that survive p comparable to n.
Sources
- Scaling.
- W. Torgerson, Psychometrika 17 (1952); G. Young & A. Householder, Psychometrika 3 (1938).
- R. Shepard, Psychometrika 27 (1962); J. Kruskal, Psychometrika 29 (1964).
- J. Gower, Biometrika 53 (1966); J. Hartigan, Clustering Algorithms (1975).
- Distance and distribution.
- P. C. Mahalanobis, Proc. Nat. Inst. Sci. India 2 (1936).
- J. Wishart, Biometrika 20A (1928); M. Bartlett, Proc. Roy. Soc. Edinburgh 53 (1933).
- V. Marchenko & L. Pastur, Mat. Sb. 72 (1967).
- Tests.
- H. Hotelling, Ann. Math. Stat. 2 (1931); S. N. Roy, Ann. Math. Stat. 24 (1953).
- S. Wilks, Biometrika 24 (1932); K. C. S. Pillai, Ann. Math. Stat. 26 (1955); G. Box, Biometrika 36 (1949).
- Z. Bai & H. Saranadasa, Statistica Sinica 6 (1996).
- Structure.
- K. Pearson, Phil. Mag. 2 (1901); H. Hotelling, J. Educ. Psych. 24 (1933), Biometrika 28 (1936).
- C. Eckart & G. Young, Psychometrika 1 (1936); K. Gabriel, Biometrika 58 (1971).
- R. Cattell, Multivar. Behav. Res. 1 (1966); J. Horn, Psychometrika 30 (1965).
- C. Spearman, Amer. J. Psych. 15 (1904); L. Thurstone, Multiple-Factor Analysis (1947).
- D. Lawley, Proc. Roy. Soc. Edinburgh 60 (1940); K. Jöreskog, Psychometrika 32 (1967).
- H. Kaiser, Psychometrika 23 (1958); H. B. Heywood, Proc. Roy. Soc. A 134 (1931).
- C. Jordan, Bull. SMF 3 (1875).
- H. Wold (1966); D. Witten, R. Tibshirani & T. Hastie, Biostatistics 10 (2009).
- Groups.
- R. A. Fisher, Ann. Eugen. 7 (1936); E. Anderson, Bull. Amer. Iris Soc. 59 (1935).
- C. R. Rao, JRSS B 10 (1948); B. Efron, JASA 70 (1975).
- S. Lloyd, Bell Labs memo (1957), IEEE Trans. Inf. Theory 28 (1982).
- D. Arthur & S. Vassilvitskii, SODA (2007); A. Dempster, N. Laird & D. Rubin, JRSS B 39 (1977).
- L. Hubert & P. Arabie, J. Classification 2 (1985).
- Graphs.
- A. Dempster, Biometrics 28 (1972); N. Meinshausen & P. Bühlmann, Ann. Stat. 34 (2006).
- J. Friedman, T. Hastie & R. Tibshirani, Biostatistics 9 (2008).
- O. Ledoit & M. Wolf, J. Multivar. Anal. 88 (2004).
- Data.
- K. Holzinger & F. Swineford, Supplementary Educational Monographs 48 (1939); H. Harman, Modern Factor Analysis (3rd ed., 1976).
- A. Sterling, Unpublished BS thesis, MIT (1977); D. Belsley, E. Kuh & R. Welsch, Regression Diagnostics (1980); R. McNeil, Interactive Data Analysis (1977).
- Books.
- T. W. Anderson, An Introduction to Multivariate Statistical Analysis (3rd ed., 2003).
- K. Mardia, J. Kent & J. Bibby, Multivariate Analysis (1979).
- R. Muirhead, Aspects of Multivariate Statistical Theory (1982).
- I. Jolliffe, Principal Component Analysis (2nd ed., 2002).
- S. Lauritzen, Graphical Models (1996).
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning (2nd ed., 2009).
About this partfrom its README
Part 31 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the eleventh part of Stage III, Master's. Part 30 survived bad data in one dimension. This part asks what structure hides in many correlated variables at once:
- distance and the Wishart distribution;
- tests of mean vectors (Hotelling's T², MANOVA);
- low-dimensional structure (principal components, factor analysis, canonical correlation);
- groups, known and unknown (discriminant analysis, clustering);
- graphs of conditional independence;
- what goes wrong when the number of variables p grows with the sample size n.
Its instrument is the map from distances (DistanceMap): a map rebuilt from a table of distances, drawn over the
truth with its residuals. Its kit is statkit.multi.
It opens with the World's 200 towns:
- roads join each town to its four nearest neighbours, each road 10–30% longer than straight, giving 19,900 shortest-route distances;
- a typical route is 1.44 times the straight line;
- classical scaling (Torgerson 1952), Procrustes-rotated onto the truth, rebuilds the island with an RMSE of 0.55 on an island 10 units across;
- two dimensions hold 84.7% of the positive eigenvalue mass; the absolute negative sum is 13.95% of the positive sum because roads are not straight;
- from exact Euclidean distances the error is 10⁻¹⁵.
Then the Cambridge Encyclopaedia road distances between 21 European cities. Two dimensions hold 86.8%, the stated normalized raw distance stress is 0.090. The orientation uses known Stockholm/Lisbon geography; north is not learned from distances alone. The worst-fitting pairs:
| Pair | Table (km) | Map (km) |
|---|---|---|
| Cologne–Geneva | 1,662 | 713 |
| Athens–Rome | 817 | 1,725 |
| Lisbon–Lyons | 1,178 | 1,714 |
These are entries worth checking against their sources. A low-rank map residual alone cannot establish a transcription error or historical route mode.
From there the part covers:
-
The data matrix.
- x̄, S, R; the multivariate normal and its ellipsoids; whitening.
- Mahalanobis distance (1936) on Fisher's 50 versicolors. The χ²₄ QQ plot is a rough radial diagnostic, not a test that establishes joint normality. The largest D² is 12.5. Because mean and covariance are fitted to the same observations, its exact Gaussian marginal reference is a scaled beta; the distances are dependent. The most outlying flower by Mahalanobis distance (index 18) is not the farthest by Euclid (index 48).
-
Wishart (1928) and Bartlett's decomposition (1933).
- With p = 3 and m = 10, 20,000 Bartlett draws give E W/m with displayed Monte Carlo standard errors, Var W₁₁ = 80.4 against 2mσ₁₁² = 80, and Var W₁₂ = 26.6 against 26.4.
- The inverse-Wishart prior and its update after integrating an independently flat unknown-mean prior: IW(ν+n−1, Ψ+(n−1)S).
- The fanning-out of sample eigenvalues. With p = 50, n = 100 and Σ = I they run from 0.10 to 2.76, inside the Marchenko–Pastur edges [0.084, 2.926] (p/(n−1) for the centered covariance).
-
Hotelling's T² (1931), by Roy's union–intersection principle (1953). Versicolor against virginica:
Statistic Value univariate t (sepal length, sepal width, petal length, petal width) −5.63, −3.21, −12.60, −14.63 T² 355.5 F on (4, 95) df 86.1 p 9.5 × 10⁻³¹ the best combination's t 18.85, with t² = T² -
The simultaneous confidence ellipsoid.
-
MANOVA on all three species. The eigenvalues of E⁻¹H are 32.19 and 0.285:
Statistic Value Wilks's Λ 0.02344 (F = 199.1 on 8 and 288 df) Pillai's trace 1.192 Hotelling–Lawley trace 32.48 Roy's largest root 32.19 -
statkit matches statsmodels to every printed digit.
-
-
Principal components (Pearson 1901; Hotelling 1933).
- The SVD and Eckart–Young (1936); classical scaling as PCA.
- US arrests (1973), standardized: 62.0, 24.7, 8.9 and 4.3% of the variance.
- PC1 loadings are (0.54, 0.58, 0.28, 0.54), an overall arrest-rate score; arrests are a proxy, not crime incidence.
- PC2 loadings are (−0.42, −0.19, 0.87, 0.17), mostly urbanization.
- Gabriel's biplot.
- Units matter. On the irises the first component holds 92.5% raw but 73.0% standardized.
- Choosing the number of components: Kaiser, the scree plot and parallel analysis (Horn 1965).
-
Factor analysis (Spearman 1904; Thurstone; Lawley 1940; Jöreskog 1967) on Holzinger and Swineford's 24 tests (n = 145).
- 275 of 276 off-diagonal correlations are positive (one is −0.075), averaging 0.30. The first eigenvalue is 8.14 of 24 (then 2.10, 1.69, 1.50, 1.03).
- Bartlett's LR test p-values for k = 1–5 factors: 2.3 × 10⁻³³, 2.0 × 10⁻¹³, 5.1 × 10⁻⁵, 0.022 and 0.128.
- The unrotated first factor loads on every test (0.34–0.75).
- Varimax (Kaiser 1958) gives verbal (tests 5–9), speed (10–13), spatial (1–4) and memory (14–19) factors with the same Σ.
- Uniquenesses run from 0.24 to 0.78, with no active numerical lower-bound flag (the constrained optimizer is checked for convergence).
- Factor scores (Thomson, Bartlett); oblique rotation; FA against PCA.
-
Canonical correlation (Hotelling 1936) on the savings data (50 countries, the 1960s).
- Demography (pop15, pop75) against the economy (savings rate, income per head, income growth).
- r₁ = 0.825 (Bartlett p = 7 × 10⁻¹¹) and r₂ = 0.365 (p = 0.037).
- Structure correlations: pop15 −0.98 and pop75 +0.97; income +0.95 and savings +0.49.
- The principal angles are 34.4° and 68.6°.
- Regularized and sparse CCA; PLS.
-
Discriminant analysis (Fisher 1936; Rao 1948).
- The first discriminant carries 99.1% of the separation.
- On petal length and width, LDA's lines and QDA's curves have leave-one-out errors of 4.0% and 3.3%.
- On all four measurements, the training error is 2.0% for both. Leave-one-out, LDA stays at 2.0% and QDA rises to 2.7%.
- LDA against logistic regression (Efron 1975). The history is acknowledged.
-
Clustering.
- Lloyd's k-means (1957) from a bad start: 9 rounds, WSS 328 → 31.4, ARI 0.89 on the petals.
- k-means as hard EM. A full-covariance Gaussian mixture has ARI 0.90, against k-means's 0.73 on all four variables.
- The WSS elbow. BIC for k = 1–6 is 830, 574, 581, 622, 666 and 685, so it prefers two clusters.
- Mixture pitfalls; the adjusted Rand index.
-
Graphical models.
- Partial correlations from Σ⁻¹. For the 24 tests, 60% are below 0.1. Word classification and word meaning correlate 0.53 but have partial correlation 0.00.
- Dempster's covariance selection (1972). The graphical lasso (Friedman, Hastie & Tibshirani 2008) gives 164, 135, 133, 97, 45 and 16 edges at λ = 0.05, 0.1, 0.2, 0.3, 0.4 and 0.5. The verbal clique appears first.
- Neighbourhood selection (Meinshausen & Bühlmann 2006).
-
A high-dimensional warning.
-
The chi-squared calibration fails as p/n grows; the exact F holds.
-
Bai–Saranadasa (1996) drops S⁻¹; Ledoit–Wolf shrinkage.
-
Power with a 0.15-SD shift in every coordinate:
p exact T² (F) Bai–Saranadasa 10 0.27 0.34 25 0.41 0.53 40 0.45 0.72 90 0.16 0.95
-
Data:
- Cambridge Encyclopaedia European road distances (1990), Fisher's irises (Anderson 1935; Fisher 1936), Holzinger and Swineford's 24 tests (1939, via Harman 1976), the savings data (Sterling 1977; Belsley, Kuh & Welsch 1980) and US arrests (McNeil 1977) are the Museum's;
- the towns are the World's;
- the rest are seeded simulations.
Built in this part:
statkit.multi(explainer/stats/kit/multi.py), checked intests/test_stats_kit_multi.py:- Distances: classical MDS, Procrustes, Mahalanobis distance.
- Wishart and tests: Bartlett's Wishart sampler; one- and two-sample T²; Bai–Saranadasa; MANOVA (Wilks, Pillai, Hotelling–Lawley, Roy, with Rao's F).
- Structure: PCA; maximum-likelihood factor analysis with Bartlett's test and a Heywood flag; varimax; CCA with Bartlett's tests.
- Groups: LDA and QDA with leave-one-out error; k-means++ and Lloyd; Gaussian mixtures by EM with BIC; the adjusted Rand index.
- Graphs: partial correlations; the graphical lasso.
- The Museum gains
eurodist(),iris(),harman74(),lifecycle()andusarrests(). - The map from distances (
DistanceMapinexplainer/stats/viz.py).
The Coverage Board gains five rows. Size of the two-sample T² test at 5%, two samples of 50 from one normal, 2,000 data sets each:
| Method | Setting | Achieved | Verdict |
|---|---|---|---|
| T² with a χ²_p calibration | p = 2 | 5.4% | kept |
| T² with a χ²_p calibration | p = 25 | 32.5% | broken |
| T² with a χ²_p calibration | p = 40 | 72.2% | broken |
| T² with the exact F | p = 40 | 5.4% | kept |
| Bai–Saranadasa | p = 40 | 6.25% | kept |
At p = 10, the χ² calibration rejects 10.4% (not a Board row).
Part-specific numerical corrections: the undirected road graph samples one detour factor per unique physical edge, preventing reciprocal-neighbor CSR entries from being summed. The graphical lasso enforces an unpenalized diagonal as its stated off-diagonal objective requires; the six edge counts above are recomputed from that objective. The local factor optimizer checks convergence, and factor columns are explicitly assigned to the named test groups after varimax. Orthogonal rotation preserves a four-factor covariance; it cannot turn four factors into one. Four factors have p = 0.022 and are rejected at 5%; five give p = 0.128. Four are used for an illustrative interpretation, not accepted by that test.
The Gaussian-mixture implementation evaluates likelihood and responsibilities at the returned parameters and checks convergence in absolute likelihood change. Fits use a declared 1e−6 covariance ridge and multiple starts. Mixture BIC is a regularized local-fit heuristic, not a proof of two biological species or two density modes. K-means' small-variance connection assumes positive fixed mixture weights away from ties; deterministic assignment handling matters for finite termination.
The LDA/QDA four-variable covariance counts are 10 and 30, not 15 and 45. The one-error leave-one-out difference does not establish a general ranking. Shared-covariance Gaussian inference requires independent samples, nonsingular covariance and adequate degrees of freedom. MANOVA's displayed Rao F is an approximation in general. Partial correlation measures adjusted linear association; an estimated Gaussian graph is not verified population independence or a causal graph. PLS requires normalization of its weights. Covariance shrinkage is positive definite with positive weight and positive trace; plugging it into T² does not preserve the classical exact F law. At p = 90 with two samples of 50, the exact F denominator has 9 degrees of freedom, not 8.
Classical scaling minimizes Gram-matrix approximation error rather than distance stress. The Marchenko–Pastur curve is an asymptotic independent-noise reference; gamma above one also has a zero atom. Neither a finite eigenvalue plot nor parallel analysis guarantees recovered structure. The arrest biplot arrows are loadings multiplied by 2.6 for display, not unscaled reconstruction coordinates. Factor scores retain uncertainty with positive uniqueness, and oblique rotation uses LΦLᵀ + Ψ. Maximum-likelihood factor fitting is equivariant under unit changes with free uniquenesses; numerical loadings rescale.
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | A map from distances | towns RMSE 0.55; Europe 87%, Cologne–Geneva 1,662 vs 713 |
| 1 | The data matrix | max D² 12.5 vs cut 11.1 |
| 2 | Wishart | Var W₁₁ 80.4 vs 80; MP edges [0.084, 2.926] (p/(n−1) for the centered covariance) |
| 3 | Hotelling's T² and MANOVA | T² 355.5; Wilks 0.0234 |
| 4 | Principal components | 62% + 25%; iris 92.5% raw vs 73% standardized |
| 5 | Factor analysis | k = 4, p = 0.022; varimax: four named factors |
| 6 | Canonical correlation | r = 0.82, 0.37; 34°, 69° |
| 7 | Discriminant analysis | 99.1% on LD1; LOO 2.0% vs 2.7% |
| 8 | Clustering | ARI 0.89 / 0.90 / 0.73; BIC picks 2 |
| 9 | Graphical models | 276 → 97 → 45 → 16 edges |
| 10 | A high-dimensional warning | χ² size 72% at p = 40; power 0.16 vs 0.95 |
| 11 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: a map from distances (classical MDS, Torgerson 1952).
- The data matrix. Mahalanobis distance (1936).
- Wishart (1928). Bartlett's decomposition.
- Hotelling's T² (1931). Union–intersection (Roy 1953); MANOVA's four statistics.
- PCA (Pearson 1901; Hotelling 1933). Variance and low rank; biplots; scree plots.
- Factor analysis (Spearman 1904; Thurstone). Rotation and varimax; Heywood cases; FA vs PCA.
- CCA (Hotelling 1936). Principal angles.
- Discriminant analysis (Fisher 1936; Rao 1948). LDA and QDA; the history acknowledged.
- Clustering. k-means as hard EM; Gaussian mixtures by EM (Part 22); choosing k.
- Graphical models. Zeros of Σ⁻¹ as conditional independence; the graphical lasso (Friedman, Hastie & Tibshirani 2008).
- High-dimensional warning. T² as p/n grows (Board); Part 52.
- Outro.
Built: the map from distances; statkit.multi.
Build the film
python -m videos.stats.stats31.compute # the part's numbers, into .cache/stats31
python tools/build.py stats31 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats31 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats31. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats31.compute # once (a few minutes)
python tools/build.py stats31 -q l # fast 480p preview
python tools/build.py stats31 # 1080p30 -> renders/stats31.mp4
python tools/qa_scene.py stats31 Graphs
python tools/lecture_length.py stats31 --floor 50