Sparsity
How can you solve for a thousand unknowns from a hundred equations?
In 2004 Candes measures the Shepp-Logan phantom on 22 radial lines of its Fourier transform, a fifth of the coefficients. The minimum-energy reconstruction is 48% wrong; minimizing total variation recovers the image to numerical tolerance, because the image is sparse in its jumps. The part explains why by betting that most unknowns are zero. Ridge shrinks along the singular directions but leaves every coefficient nonzero; best subset is exact and intractable; the l1 ball is the smallest convex ball with corners, and the lasso's solution lands on one. The lasso is then computed (coordinate descent, LARS on the diabetes data), given relatives (elastic net, group, fused, adaptive, SCAD, MCP), tuned by cross-validation and stability selection, and given priors (Laplace, the horseshoe). Compressed sensing states when l1 recovery is exact, by the null space property and the Donoho-Tanner phase transition. The part turns on inference: naive intervals after selection cover 75%, and the debiased lasso and double selection repair them. It ends with matrix completion, where rank plays the role of sparsity.
What you need. Regression in matrix form (Part 23) and convex optimization at the level of Part 21 (subgradients, coordinate descent, duality).
- Hook
- Candès's phantom, 2004
- Mathematics
- ridge, ℓ1 geometry, coordinate descent and LARS, the penalty zoo, compressed sensing, debiased lasso, matrix completion
- Built
- statkit.sparse
What you will be able to do
Bachelor's
- Explain with the picture of a diamond and a disc why an l1 budget sets coefficients exactly to zero and an l2 budget does not.
- Apply soft, hard and ridge thresholding to a number and say which rule belongs to which penalty.
Master's
- Derive the lasso's KKT conditions and lambda_max, and compute a path by coordinate descent with warm starts.
- Compute ridge through the SVD and read its shrinkage factors and effective degrees of freedom.
- Construct a debiased lasso interval and a double-selection estimate, and say what each assumes.
PhD
- Prove that the null space property is necessary and sufficient for exact l1 recovery of every s-sparse vector.
- State the conditions (RIP, incoherence, the s log(p/s) sample count) under which the recovery theorems hold, and which of them the radial-line phantom does not satisfy.
Practice
- Choose lambda by cross-validation with every centring and scaling step refitted inside the folds, and report the one-SE model beside the minimum.
- Refuse to report least-squares intervals for variables a lasso selected, and say what to report in their place.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 14 min · Master's 54 min · PhD 59 min · Practice 19 min.
- 0Candès's phantomBachelor's4 min
- 1Upgrade: what Part 19 shrankBachelor's3 min
- 2RidgeMaster's5 min
- 3From l0 to l1Bachelor's4 min
- 4The lassoMaster's5 min
- 5Computing the pathMaster's4 min
- 6The penalty zooMaster's5 min
- 7Choosing lambdaPractice4 min
- 8Bayesian sparsityMaster's5 min
- 9Compressed sensingPhD5 min
- 10Inference after the lassoMaster's6 min
- 11Matrix completionMaster's5 min
- Recap, problems, and the road aheadAll tracks4 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.
Candès's phantomBachelor's4 min
In 2004 Emmanuel Candès was experimenting with a standard test image from medical imaging. He threw away most of its Fourier coefficients and asked a computer to rebuild the image from the few that were left, with a particular convex optimization. The error came back zero: not small, zero. He assumed there was a bug. There was none. With Justin Romberg and Terence Tao he developed recovery theory under specified measurement and sparsity conditions. This deterministic radial-mask example is a numerical demonstration, not a universal corollary of a random-measurement theorem. Sixteen thousand unknowns, about three thousand four hundred equations, and an exact answer. This part explains how that is possible.
The setting matters. A magnetic resonance scanner does not take a photograph. It measures the Fourier coefficients of the image, the amplitudes of waves of every frequency and direction, one line of what radiologists call k-space at a time. Every line costs time, and time in a scanner is expensive, and hard for a child who must hold still. So the practical question is: how few Fourier coefficients can we measure and still get the image?
The test image is the Shepp–Logan phantom of 1974, a cartoon of a cross-section of the head: ellipses for the skull, the brain, and a few small features. A hundred and twenty-eight pixels square. In its Fourier domain we measure only twenty-two lines through the centre, like spokes of a wheel: about a fifth of the coefficients. The other four fifths are simply unknown.
The obvious reconstruction sets every unmeasured coefficient to zero and inverts. Among all images consistent with the measurements, it is the one with the least energy, the least-squares answer of Part 12 for an underdetermined system. It is poor: streaks radiate from every edge, the small features are smeared, and the error is forty-eight percent.
Candès's reconstruction asks a different question. Among all images that agree with the measured coefficients, find the one with the smallest total variation: the sum, over pixels, of the size of the jump to their neighbours. This measures contrast-weighted local jumps, not just unweighted edge length. Solving that convex problem iteratively, the streaks fade and the error falls: nineteen percent, four, two tenths of a percent, then one part in a hundred thousand, and finally about one part in ten billion in this numerical run. This is accuracy to numerical tolerance, not a proof of literal zero error.
Why can it work? The image has sixteen thousand pixels, many of them nonzero: far more unknowns than equations. But the image is simple in another sense. Only about five percent of horizontal neighbours differ: it is sparse in its jumps. And each Fourier coefficient is a weighted sum over the whole image, so every measurement carries information about every jump. Sparsity in one basis, measurements spread out in another: that combination is what lets a few equations determine many unknowns. Chapter nine makes it precise.
Statistics meets the same problem constantly. In a gene-expression study there may be twenty thousand genes measured on a hundred patients. A regression of an outcome on all of them has infinitely many exact fits, each meaningless. The way out is what Hastie, Tibshirani and Friedman call the bet on sparsity: assume that only a few coefficients matter, and use a method that finds them. Other structures, such as smoothness, low rank or many small effects, can support different methods; the sparse assumption must be assessed.
Numbers: 20.6% of k-space; 48% vs 1.6 × 10⁻¹⁰
1Upgrade: what Part 19 shrankBachelor's3 min
Part 19 met ridge regression and the lasso. Ridge shrinks every coefficient towards zero; the lasso shrinks and sets some exactly to zero, by soft thresholding; and cross-validation chooses how much. It quietly assumed more observations than variables, and it treated the fitted coefficients as the end of the story. This part drops both assumptions. With far more variables than observations, when does the lasso find the true variables? How is its whole path computed, and its penalty chosen? And how can we attach honest confidence intervals to coefficients that were selected by looking at the data?
The problem, precisely. A linear model with more coefficients than observations. X transpose X has rank at most n, so it is singular and the normal equations have no unique solution. Add any vector from the null space of X to a solution and the fit is unchanged: a family with dimension p minus the rank of X; exact interpolation requires the outcome to lie in its column space, and nothing in the data prefers one to another. The rescue is an assumption: that only s of the coefficients are nonzero, with s much smaller than n. Identifying which coefficients matter also needs a suitable design and sufficiently strong signals; identical columns can prevent unique support identification.
A counting argument says how much data that needs. If s of p coefficients are nonzero, there are p choose s possible supports. Naming one takes about s log of p over s bits. And the theory of this part shows that, with the right method, the number of observations needed grows like s log of p over s: linearly in the number of true effects, only logarithmically in the number of candidates. With twenty thousand genes and ten that matter, that is about seventy-six: seventy-six is an order-of-magnitude count, not a clinical sample-size guarantee. Constants, noise, signal strength and design conditions also matter.
Every method in this part adds a penalty to the least-squares loss. Penalize the squared length of beta and you get ridge regression: stable and generically dense; individual coordinates can cross zero, but it does not create a selection threshold. Penalize the number of nonzero coefficients and you get best subset selection: sparse, but computationally intractable. Penalize the sum of absolute values and you get the lasso: sparse, and convex. The next three chapters take them in turn.
Numbers: s log(p/s) ≈ 76
2RidgeMaster's5 min
Arthur Hoerl was a chemical engineer at DuPont in the early 1960s, fitting response surfaces to process data. His predictors were nearly collinear, and least-squares coefficients swung to absurd values with small changes in the data. His remedy was to add a small constant to the diagonal of X transpose X before inverting it. The name came from the ridge-shaped surfaces he had studied. With Robert Kennard he published the theory in Technometrics in 1970: biased estimation for nonorthogonal problems.
In modern terms, ridge regression minimizes the residual sum of squares plus lambda times the squared length of beta, with the predictors standardized and the outcome centred. Setting the gradient to zero, the solution is X transpose X plus lambda times the identity, inverted, times X transpose y. For any positive lambda that matrix is invertible, even when there are more variables than observations: ridge always has a unique answer.
The diabetes data of Efron, Hastie, Johnstone and Tibshirani: four hundred and forty-two patients, ten baseline measurements, and a measure of disease progression a year later. Total cholesterol and LDL cholesterol correlate point nine. Least squares gives them coefficients of minus thirty-eight and plus twenty-three per standard deviation: a large contrast between two nearly identical measurements, sensitive to noise in that weakly identified contrast; these data alone do not establish the true coefficient values. Ridge with a modest lambda of ten brings them to minus eleven and almost two, while body-mass index and log triglycerides barely move.
The singular value decomposition shows what ridge does. The fitted values are a sum over principal directions of the data, each projection shrunk by d squared over d squared plus lambda. Directions with large singular values, where the data vary a lot, are hardly touched. The trace of the hat matrix, the effective degrees of freedom, is the sum of those factors: it falls from the rank of X towards zero as lambda grows, equal to p here because the design has full column rank. The directions with small singular values are shrunk most, and they are exactly the ones where least squares is noisiest, since the variance of an estimate along direction j is sigma squared over d j squared.
For the diabetes data the singular values run from forty-two down to about two, a condition number of twenty-two. With lambda ten, nine directions keep more than three quarters of their size and the last keeps barely a quarter. With lambda a thousand, everything shrinks a lot. That last, weakest direction is essentially the difference between total cholesterol and LDL: a contrast whose least-squares uncertainty is large.
Hoerl and Kennard's ridge trace: every coefficient as lambda grows, plotted here against the effective degrees of freedom. At the right, ten degrees of freedom, least squares; at the left, everything shrunk to zero. The wild pair, total cholesterol and LDL, collapses towards zero almost at once; the others shrink smoothly and in proportion. And an individual coefficient can cross zero at a finite lambda. Ridge has no threshold that holds it at zero over a range, so its path does not generally perform variable selection.
Ridge is also Bayesian. Give the coefficients independent normal priors with variance tau squared. The posterior mean is exactly the ridge estimate, with lambda equal to the noise variance over the prior variance: the less you believe in large effects, the more you shrink. The posterior is normal, so its mean, median and mode all coincide. That will not be true for the lasso's prior in chapter eight.
Hoerl and Kennard proved something striking. The squared bias of ridge grows from zero like lambda squared, while the total variance falls from the least-squares value. At lambda equal to zero the bias term is flat but the variance is already falling, so the derivative of the mean squared error is negative. For a fixed full-column-rank design and positive noise variance, each true coefficient vector has some risk-improving positive lambda. That oracle choice depends on the unknown coefficients; this is not one fixed lambda that dominates least squares uniformly.
So ridge is unique, stable, and very good when there are many small effects. But it is generically dense, without a thresholded region of exact zeros. With twenty thousand genes the ridge model still has twenty thousand terms, and says nothing about which ones matter. For these separable convex penalties, a corner at zero permits a thresholded zero region. Hard constraints and nonconvex counting penalties provide other selection mechanisms. The next chapter finds the right one.
Numbers: −37.7/+22.7 → −11.3/+1.8; condition number 22
3From l0 to l1Bachelor's4 min
From counting to absolute values. The most natural sparse method is best subset selection: among all models with at most k variables, take the one with the smallest residual sum of squares. Its constraint counts nonzero coefficients, written as the zero norm, though it is not really a norm. When the columns are orthonormal it is easy: keep the k largest least-squares coefficients and zero the rest, hard thresholding. In general, the columns interact, and the worst-case search is combinatorial, although bounds, pruning and mixed-integer methods can avoid enumerating every subset.
The count of subsets doubles with every variable. Ten variables give a thousand subsets; thirty give a billion; the sixty-four candidate terms of the quadratic diabetes model of chapter seven give eighteen quintillion, five hundred and eighty-five years at a billion fits a second. Twenty thousand genes is beyond counting. Clever algorithms help: Furnival and Wilson's leaps and bounds of 1974 reaches about forty variables, and modern mixed-integer solvers reach the hundreds. But Balas Natarajan proved in 1995 that sparse approximation is NP-hard in general. We need a different idea.
Look at the unit balls of the q-norms, the sum of absolute values to the power q. For q equal to two, the circle of ridge regression. As q falls, the ball pinches in towards the axes. For q at least one, the balls are convex; below one, they are not. As q goes to zero, these bounded unit balls approach the axis segments with amplitude at most one. The unbounded zero-count constraint alone would include whole axes. And q equal to one is the boundary case: the first q where corners appear on the axes, and the last where the ball is still convex.
So the trade is this. The zero norm gives sparsity but no convexity, so optimization is combinatorial. The two norm gives convexity but no sparsity. The one norm gives both. Replacing the count by the sum of absolute values gives the lasso, proposed by Robert Tibshirani in 1996, and at the same time, as basis pursuit, by Scott Chen, David Donoho and Michael Saunders for signal processing.
In three dimensions the one-norm ball is an octahedron. Its six vertices lie on the axes: each has a single nonzero coordinate. Its twelve edges have two nonzero coordinates, and only its eight faces have three. An expanding loss contour can first touch a low-dimensional face, producing zeros. Which face is reached depends on the data, design and budget; geometry alone does not guarantee that most coordinates vanish.
There is a precise sense in which one is the right choice. Take the axis segments of the bounded one-coordinate set, whose extreme points are the signed unit vectors. Their convex hull is exactly the one-norm ball. And on the box where every coordinate is at most one in size, the absolute value lies below the indicator of being nonzero. In fact, on that box, the one norm is the largest convex function that never exceeds the count: its convex envelope. This convex-envelope statement applies on the specified unit box; rescaling or removing that bound changes the comparison.
Numbers: 2⁶⁴ subsets, 585 years
4The lassoMaster's5 min
Leo Breiman's nonnegative garrote of 1995 shrank each least-squares coefficient by a nonnegative factor, with the factors constrained to a budget. Robert Tibshirani, then at Toronto, simplified the idea in 1996: put the budget directly on the sum of absolute values of the coefficients. He called it the lasso, the least absolute shrinkage and selection operator. It caught on slowly, because it needed quadratic programming for every value of the budget. Only when fast path algorithms arrived, between 2002 and 2007, did it become the workhorse it is now.
The absolute value has no derivative at zero, but it has a subgradient: the sign where it is smooth, and anything between minus one and one at the kink. A convex function is minimized where zero is in its subdifferential, Part 21's condition. Read off for each coordinate: if a coefficient is nonzero, the correlation of its variable with the residual is pinned at exactly plus or minus lambda. If it is zero, that correlation is at most lambda in size. Every active variable is equally correlated with what remains; every inactive one has no larger absolute residual inner product; equality can occur at a knot.
Two consequences. Setting beta to zero in the conditions, the lasso returns all zeros exactly when every variable's correlation with the outcome is at most lambda. So the path starts at lambda max, the largest of those correlations. As lambda decreases, under generic non-tied conditions, variables enter at successive knots, each when its correlation with the current residual catches up. For the diabetes data, body-mass index enters first, then log triglycerides.
With orthonormal columns the problem separates into one small problem per coefficient, where z j is the least-squares estimate. Minimize a half the squared distance to z plus lambda times the absolute value. The answer is soft thresholding: move z towards zero by lambda, and stop at zero. Ridge instead divides by one plus lambda, shrinking in proportion; best subset keeps or kills, hard thresholding at root two lambda.
The three rules side by side, with lambda one. Ridge halves every estimate and is zero exactly when that scalar estimate is zero, without a thresholded interval. Best subset keeps an estimate untouched or kills it, with a jump at root two: unstable, since a tiny change in the data can flip a variable in or out. The lasso is zero inside a band of half-width lambda and shifted towards zero by lambda outside it. It is continuous and sparse at once, the compromise; its price is that even large effects are shrunk by lambda, a bias that chapter six's penalties repair.
Part 19's picture, now with correlated predictors. The dot is the least-squares estimate and the ellipses are contours of the loss. The lasso's constraint is the diamond. Grow the ellipses from the dot until they first touch it: they touch at the corner on the horizontal axis, so the second coefficient is exactly zero. The ridge disc of the same radius is touched at a point where both coefficients are nonzero. Corners make zeros.
A few facts about the solution. The fitted values are always unique, since the loss is strictly convex in them, even when the coefficients are not. For a design in general position the coefficients are unique too, and at most min of n and p are nonzero: this support bound uses general position. With duplicate columns, nonunique coefficient solutions can have more nonzeros. And, beautifully, under fixed design, Gaussian noise and a fixed penalty, the fit degrees of freedom equal the expected active-set rank, or the expected nonzero count in general position, a result of Hui Zou, Trevor Hastie and Robert Tibshirani from Stein's lemma. The nonzero count can estimate degrees of freedom in that fixed-penalty setting, adding one for an unpenalized intercept. Choosing the penalty from the data introduces further tuning complexity.
The lasso does two jobs with one tuning parameter: it selects variables and it shrinks their coefficients. A lambda large enough to remove every noise variable also biases the real effects; the simple shift by lambda is specific to orthonormal coordinates. A lambda small enough to leave the real effects nearly unbiased lets noise variables in. The fixes separate the jobs: refit the selected variables with a smaller penalty, the relaxed lasso; reweight the penalty by a first estimate, the adaptive lasso; or bend the penalty so that large coefficients are not penalized at all. Chapter six.
Numbers: corner (1.5, 0) vs (1.42, 0.47)
5Computing the pathMaster's4 min
Part 21's coordinate descent is the method of choice. Hold every coefficient but one fixed and form the partial residual. The best value of the free coefficient is the soft threshold of its correlation with that residual: the orthonormal formula, one coordinate at a time. Each update costs order n if the residual is kept current. And it converges to the minimum because the non-smooth part of the objective is separable across coordinates, a theorem of Paul Tseng.
Three tricks make it fast. Warm starts: solve for a decreasing grid of lambdas, starting each from the previous solution, which is already close. Active sets: once the nonzero coefficients settle, sweep only those, and check the rest occasionally. Strong rules: discard in advance any variable using a strong-rule heuristic based on its previous residual inner product, then check every discarded variable against KKT and restore any violations. Together, in Friedman, Hastie and Tibshirani's glmnet, they can make full paths fast on favorable problems; the cost depends on dimensions, conditioning, sparsity and the convergence tolerance.
The path itself can be computed exactly. Efron, Hastie, Johnstone and Tibshirani's least angle regression of 2004 starts at zero and finds the variable most correlated with the outcome. Rather than fitting it fully, it moves the fit along that variable only until a second variable has just as large a correlation with the residual. Then it moves along the direction that keeps the two correlations tied, decreasing together. In general that is the equiangular vector of the active set, making equal angles with the signed, standardized active columns. When a third variable catches up, it joins, and so on.
Why does this have anything to do with the lasso? The lasso's optimality conditions say the active correlations are all equal to lambda, with the signs of their coefficients. LARS keeps exactly those correlations tied as they decrease. The only difference: a lasso coefficient cannot cross zero while its variable stays active, because its sign would contradict its correlation. So when a coefficient hits zero, drop that variable. With that one modification LARS traces the entire lasso path exactly. It is piecewise linear in lambda, with a knot wherever a variable enters or leaves.
The whole lasso path for the diabetes data, with each variable's coefficient against the fraction of the least-squares coefficients' total size that the budget allows. Eleven knots, dashed, where a variable enters or leaves. Between knots every coefficient moves in a straight line. At the far right the budget no longer binds and the lasso is least squares.
The order of events. Body-mass index enters first, then log triglycerides, then blood pressure: the strongest predictors of progression. HDL cholesterol enters fourth, and then, late in the path, its coefficient shrinks back to zero and it leaves, before returning one knot later. Pure least angle regression, without the lasso modification, keeps HDL throughout; that drop is the only difference between the two paths on these data. All of this reproduces the first figure of the 2004 paper.
LARS needs only p steps for its pure form, about the cost of one least-squares fit. The lasso path can take additional drop and re-entry steps, twelve steps for these ten variables; in general it can be much longer. A third variant, forward stagewise regression, takes tiny steps along the most correlated variable and turns out to be closely related to boosting, which Part 34 explains. In practice, coordinate descent on a grid of lambdas is simpler and extends to logistic, Poisson and Cox models, which LARS does not. Both give the same answer where both apply.
Numbers: 12 steps; HDL leaves at 0.81
6The penalty zooMaster's5 min
First problem: when two predictors are nearly identical, the lasso tends to pick one and drop the other, and which one it picks can flip with a small change in the data. Hui Zou and Trevor Hastie's elastic net of 2005 mixes the lasso penalty with a little ridge. The ridge part is strictly convex, so identical predictors get identical coefficients: the grouping effect. And unlike the lasso, the elastic net can select more variables than there are observations, which matters for genes that act in correlated pathways.
Three near-copies of one signal, correlated point nine six, and three pure noise variables. Along the lasso path, one copy enters first and takes most of the effect, a second follows, and the third stays at zero for most of the path. Along the elastic-net path all three enter together and share the effect almost equally, a more evenly shared association. It does not identify separate causal effects of near-duplicate predictors.
Second problem: some variables only make sense together, like the dummy variables of one categorical factor or the basis functions of one spline. Ming Yuan and Yi Lin's group lasso penalizes the Euclidean length of each group's coefficient vector, without squaring it. In coordinates with each group orthonormalized, the block update is a soft threshold: shrink the whole group's vector towards zero, and set it exactly to zero if it is short enough. So whole groups enter or leave together. Add an ordinary lasso term and you also get sparsity within the selected groups.
Third: sparsity need not be in the coefficients themselves. The fused lasso penalizes the absolute differences between neighbouring values. The solution is piecewise constant, with only a few jumps. Two-dimensional total variation is the analogous gradient penalty. The hook uses the isotropic sum of gradient magnitudes, rather than a separate absolute penalty for each directional difference, introduced for image denoising by Rudin, Osher and Fatemi in 1992. It is computed by Part 21's ADMM, or exactly, in one dimension, by dynamic programming.
Two hundred noisy readings of a signal with three steps, like copy-number changes along a chromosome. The true steps in gold. The fused lasso finds the jumps and flattens the noise between them, cutting the error from point five five to point two three. Its plateaus are slightly shrunk towards their neighbours, the usual price of an absolute-value penalty.
Fourth problem: the lasso's bias on large effects. Hui Zou's adaptive lasso weights each coefficient's penalty by the inverse of a first-stage estimate. Variables that looked strong are barely penalized, so their estimates are nearly unbiased. Variables that looked weak are penalized heavily and removed. Zou proved an oracle property: asymptotically it selects exactly the true variables and estimates them as efficiently as if the true model were known. The asymptotics hide a lot, as chapter ten will show.
Or bend the penalty itself. Jianqing Fan and Runze Li's SCAD of 2001 behaves like the lasso near zero, bends quadratically, and becomes flat beyond a times lambda. Cun-Hui Zhang's minimax concave penalty, MCP, does the same more simply. Flat means zero penalty derivative beyond the threshold, reducing shrinkage of large estimates. This is not a guarantee of finite-sample unbiasedness after selection, while small ones are still set to zero, and the thresholding rule stays continuous: Fan and Li's three requirements. The price is convexity: there can be local minima. In practice coordinate descent from the lasso solution works well, as Patrick Breheny and Jian Huang showed.
Their thresholding rules for an orthonormal design. The lasso's soft threshold stays a distance lambda below the diagonal forever. SCAD starts as the soft threshold, then climbs back to the diagonal, which it meets at three point seven. MCP climbs more steeply and meets the diagonal at three. Large estimates are left alone.
A comparison: two hundred data sets, a hundred observations, two hundred correlated predictors, eight true effects between a half and one, with a common base lambda for lasso, SCAD and MCP; the adaptive lasso uses a separately rescaled weighted penalty. This is an illustrative tuning comparison, not an optimally matched contest. All four find about seven of the eight true variables. The lasso also includes nearly three false ones, and gets the support exactly right three percent of the time. The adaptive lasso cuts the estimation error by three quarters. MCP includes fewer than half a false variable on average and is exactly right a third of the time. Bending the penalty separates selection from shrinkage.
Numbers: MCP 0.40 false vs lasso 2.74
7Choosing lambdaPractice4 min
There are several ways to choose lambda. Theory suggests a level proportional to the noise standard deviation times root two log p over n, just above the size of the largest pure-noise correlation, but it needs sigma. Mallows's C p, or Stein's unbiased risk estimate, uses chapter four's fact that the degrees of freedom are the number of nonzeros. K-fold cross-validation, Part 19's tool, picks the lambda with the smallest held-out prediction error. And the one standard error rule picks the most heavily penalized model whose error is within one standard error of the minimum.
A harder test: the quadratic model of the LARS paper, built from the standardized diabetes variables. Ten main effects, forty-five pairwise interactions and nine squares, sixty-four candidate terms for four hundred and forty-two patients. Exhaustively enumerating every subset would take chapter three's five hundred and eighty-five years at that hypothetical rate; pruning and integer solvers can do better. The lasso path takes a fraction of a second.
Ten-fold cross-validated error along the path, with a descriptive band based on fold variability. Overlapping training folds mean this is not a calibrated confidence band. Large lambdas on the right, where the model is empty. The minimum keeps fifteen of the sixty-four terms. The one standard error rule moves right to the simplest model whose error is within a standard error of the minimum, and keeps eleven. Either way the prediction error is about half that of predicting the mean for everyone.
The one standard error model's eleven terms. Five main effects: sex, body-mass index, blood pressure, HDL and log triglycerides. And six terms of curvature and interaction, such as age with sex and body-mass index with blood pressure. The core is the same as in chapter five's linear model; the quadratic terms add modest refinements.
Cross-validation measures prediction error, and that is all it can measure. For prediction, the lasso likes a small lambda, which shrinks the real effects less, and it pays for that by admitting doubtful variables. So the cross-validated lambda is not consistent for selection: there are asymptotic regimes where it continues including noise variables, as Nicolai Meinshausen and Peter Bühlmann, and independently Chenlei Leng, Yi Lin and Grace Wahba, showed in 2006. The lesson: decide whether you want predictions or a list of variables, and tune for that.
For selection, Meinshausen and Bühlmann's stability selection of 2010 is more reliable. Draw half the data at random, run the lasso path, and repeat many times. For each variable and each lambda, record the share of subsamples in which it was selected. Keep the variables whose selection probability reaches a high threshold, such as point eight, somewhere on the path. Their expected false-selection bound also requires noise-variable exchangeability and a base procedure no worse than random selection. For a whole lambda region, q counts the union selected per subsample. The diabetes paths are descriptive stability estimates, not a verified false-selection guarantee.
Stability paths for the quadratic diabetes model: the twelve terms selected most often, against lambda. Eleven reach the threshold of point eight in this simulation: six main effects, and five quadratic terms: age with sex, age with LDL, sex with body-mass index, body-mass index with blood pressure, and glucose squared. Other terms have lower selection frequencies on this chosen path. This measures stability of association, not which variables truly cause the outcome.
In short. To predict, cross-validate. To select, use stability selection, or a nonconvex penalty whose selection is less tied to shrinkage. To make claims about individual coefficients, with intervals, you need the tools of chapter ten. And always report how many variables were selected and how stable that selection was.
Numbers: 15 / 11 terms; 11 stable
8Bayesian sparsityMaster's5 min
Ridge was a normal prior. The lasso has a prior too: independent Laplace, or double exponential, distributions on the coefficients. The negative log posterior is the residual sum of squares plus lambda times the one norm. So the lasso estimate is the posterior mode, as Tibshirani noted in his original paper. Trevor Park and George Casella's Bayesian lasso of 2008 writes the Laplace distribution as a scale mixture of normals and samples the whole posterior by Gibbs sampling.
But the Laplace prior is not a sparse prior. It is continuous, so the posterior probability that any coefficient is exactly zero is zero. In the independent normal-means problem, the posterior mean has the sign of a nonzero observation and is zero at a zero observation. A general correlated regression needs a separate statement. And vectors drawn from the prior have every coordinate nonzero. The lasso's zeros come from taking a mode of a distribution with a sharp peak, not from any belief that most effects are zero. Exact posterior zeros need a point mass. Continuous shrinkage priors can instead concentrate strongly near zero.
One observation y, normal around theta with standard deviation one, and three answers. The Laplace prior's posterior mode is the soft threshold. Its posterior mean is a smooth curve: never zero except at zero, and still a full unit below the diagonal for large y. Neither sparse nor unbiased. The horseshoe prior's posterior mean does what we want: it flattens small observations almost to zero and leaves large ones almost untouched.
The horseshoe of Carlos Carvalho, Nicholas Polson and James Scott is also a scale mixture of normals, but with half-Cauchy distributions on both a local scale for each coefficient and a global scale shared by all. The global scale, learned from the data, pulls everything towards zero when most effects are null. The local scales have tails so heavy that a coefficient with real signal can resist the global pull; negligible tail shrinkage is an asymptotic property, not guaranteed finite-signal detection.
The name comes from this picture. Given its local scale, the posterior mean of a coefficient is one minus kappa times the observation, where kappa is the shrinkage factor. Under the horseshoe, with tau equal to one, kappa has a beta one-half, one-half distribution, shaped like a horseshoe: mass piles up near one, total shrinkage for noise, and near zero, no shrinkage for signals. The Laplace prior's shrinkage factor has almost no mass near zero, so even large signals are always shrunk.
A sparse normal-means problem: two hundred means, ten equal to five and the rest zero, one noisy observation of each. The first sixty are shown. Grey dots are the observations; gold dashes the truth. The Bayesian lasso's posterior means, by Gibbs sampling, shrink the signals noticeably and leave every null slightly nonzero. The horseshoe's posterior means sit almost on the truth: nulls near zero, signals near five.
Total squared error. The raw observations make an error of about two hundred, one for each mean. Soft thresholding at Donoho and Johnstone's universal threshold, root two log p, removes the nulls but shrinks every signal by three and a quarter. The Bayesian lasso does better, and the horseshoe has the smallest error in this one seeded experiment, having learned a small global scale from the data.
The most honest sparse prior puts a point mass at zero: a spike for the null effects and a slab for the real ones. Toby Mitchell and John Beauchamp proposed it in 1988, and Edward George and Robert McCulloch's stochastic search made it computable in 1993. It gives exact zeros and a posterior probability that each variable is included, at the cost of averaging over two to the p models. The horseshoe is a continuous shrinkage alternative, with no point mass at zero. Neither posterior inference nor computation has a universal winner. Part 53 proves when such posteriors concentrate on the truth.
Numbers: SSE 203 / 86 / 74 / 31
9Compressed sensingPhD5 min
Strip the statistics away: noiseless measurements y equal A x, with fewer measurements than unknowns and an s-sparse x. Searching for the sparsest solution finds x whenever any two s columns of A are independent, but that search is the intractable one. Minimizing the one norm subject to the equations is a linear program, basis pursuit. The question of compressed sensing is when the tractable answer equals the intractable one.
A test. Two hundred unknowns, ten of them nonzero spikes in gold, and only sixty random measurements, each a Gaussian-weighted sum of all two hundred. Basis pursuit returns the ten spikes exactly, and zeros everywhere else. The least-norm solution, ridge's answer as lambda goes to zero, spreads the energy over every coordinate, with an error of about eighty-five percent of the signal's size.
The exact condition is short to derive. Every solution of the equations is x plus a vector h in the null space of A. By the triangle inequality, with S the support of x, the one norm of x plus h is at least the one norm of x, minus the part of h on S, plus the part of h off S. So if every nonzero null vector has less mass on S than off it, x is the unique minimizer. Requiring that for every set of size s is the null space property, and it is both necessary and sufficient for basis pursuit to recover every s-sparse vector.
A more usable condition is the restricted isometry property of Candès and Tao: A nearly preserves the length of every sparse vector. If the isometry constant at level two s is below root two minus one, the null space property follows, and more: recovery is stable. For basis-pursuit denoising constrained by a residual norm at most epsilon, with actual noise norm at most epsilon, the error is bounded by the noise plus the best sparse-approximation tail under those RIP conditions. Checking the property for a given matrix is itself NP-hard. The rescue is randomness.
A matrix with independent Gaussian entries satisfies the restricted isometry property with high probability as soon as the number of measurements is a constant times s log of p over s: the count from chapter one. Uniformly random Fourier rows give related sparse-vector guarantees with extra logarithms. They do not directly certify the fixed radial mask or gradient-sparse TV phantom in the hook. The proof combines concentration of measure for a single sparse vector with a union bound over all supports, and Part 51 does it in full.
How sharp is it? For each combination of measurements per unknown, delta, and sparsity per measurement, rho, twenty random problems with a hundred unknowns. Green means all twenty trials recovered to solver tolerance; red means none did. Finite trial counts do not give probabilities exactly one or zero. The white curve is David Donoho and Jared Tanner's asymptotic phase transition, from the combinatorial geometry of random polytopes. With half as many measurements as unknowns, the asymptotic weak threshold is about point three nine n spikes for typical random supports and signs, not a uniform guarantee over every sparse signal. And the change from success to failure is abrupt: a phase transition, like water freezing.
The phantom shows the same transition. Its reconstruction error, on a log scale, against the number of radial lines measured. Minimum energy improves slowly and is still forty percent wrong at thirty lines. Minimum total variation is twenty-eight percent wrong at twelve lines, four percent at sixteen, and exact, to eight decimal places, at twenty-two. These few deterministic masks show a sharp numerical improvement for this phantom. They do not establish a universal threshold or an asymptotic phase transition.
What the transition looks like. With eight lines, total variation produces a blocky cartoon with the wrong shapes. With twelve, the structure is there but the small features are wrong. With twenty-two, every ellipse is exactly right. This instrument, the phantom, is this part's build.
Real measurements are noisy, and then exact recovery becomes stable recovery: the error is proportional to the noise. The lasso is the natural noisy version of basis pursuit. The difference for statistics is that we rarely choose the design matrix; it is given to us, correlated and unrandom. The restricted isometry property is replaced by weaker restricted eigenvalue conditions. Under them, Part 52 proves that the lasso estimates s coefficients from n observations with error of order s log p over n, the oracle inequality.
Numbers: ρ(0.5) = 0.386; 16 lines 3.7%, 22 exact
10Inference after the lassoMaster's6 min
The most common practice after a lasso is to take the selected variables, refit them by least squares, and report the usual t-intervals, as if the model had been chosen in advance. But a variable is selected precisely when its estimate happened to look large. So, given that it was selected, its estimate is biased away from zero: the winner's curse of Part 33. Worst of all, noise variables are selected exactly when they look real, so their intervals usually exclude zero, the true value.
One data set: a hundred observations, two hundred predictors, true effects of one, one, a half, a half, a quarter and a quarter, and zeros elsewhere. The first eight coefficients are shown. The truth in gold. The lasso, at the standard theoretical lambda, keeps only the four strongest; least squares on those gives the red intervals, and says nothing about the rest. The debiased lasso, next, gives an estimate and interval for every coefficient, in green, selected or not.
Over a thousand data sets, the lasso selects about five and a half variables. Of all the naive intervals reported, only seventy-five percent cover the truth, against a promised ninety-five. For the false positives, a quarter. The weak effect of a quarter is selected only twenty-three percent of the time, and when it is, its estimate averages point three four: the winner's curse in action.
The debiased lasso adds back what the penalty took away. Take the lasso estimate and add a correction: an approximate inverse of the covariance applied to the correlation of X with the lasso residuals. If theta were the exact inverse, this would be one Newton step from the lasso to least squares. The result, scaled by root n, is a normal term plus a remainder that vanishes, as shown independently by Sara van de Geer, Peter Bühlmann, Ya'acov Ritov and Ruben Dezeure, and by Cun-Hui and Stephanie Zhang, and by Adel Javanmard and Andrea Montanari. The small remainder needs design, tail, precision-estimation and variance-estimation conditions as well as sufficiently strong sparsity, such as s log p over root n tending to zero.
Where does the approximate inverse come from? From Part 31's neighbourhood regression: a lasso of x j on all the other columns. Its residual variance, plus a penalty term, is tau j squared. Then row j of the inverse covariance is one over tau squared on the diagonal and minus the coefficients over tau squared elsewhere, the formula Part 31 used for graphs. The standard error follows from the variance of the normal term.
For the weak effect of a quarter, the debiased estimates from all thousand data sets form a normal histogram, centred at point two four, and their intervals cover ninety-five and a half percent of the time. The naive estimates exist only for the two hundred and thirty-one data sets where the lasso selected the variable, and their histogram is chopped off below: selection keeps only the lucky draws.
A related problem in causal work. We want the effect alpha of a treatment d, with many possible confounders X that affect both the treatment and the outcome. A lasso of the outcome on the treatment and the controls tends to drop confounders whose direct effect on the outcome is small, because the treatment, correlated with them, absorbs their effect. The result is Part 23's omitted-variable bias. Alexandre Belloni, Victor Chernozhukov and Christian Hansen's double selection runs two lassos, the outcome on the controls and the treatment on the controls, and keeps the union. A causal interpretation still requires exogeneity and adequate controls; this cannot repair unmeasured confounding.
A simulation with five confounders, each moving the treatment by point six and the outcome directly by point two, among a hundred candidate controls. Single selection keeps almost no controls, point one five on average. Its estimate averages point seven one instead of point five, and its intervals cover nine percent of the time. Double selection finds the confounders through the treatment equation, estimates point four nine, and covers ninety-four percent. Part 36's double machine learning generalizes the idea.
On the Board. Naive post-lasso intervals: broken, seventy-five percent. Their Monte Carlo margin uses a thousand independent datasets, accounting for correlated selected intervals and a random number of intervals per dataset. The debiased lasso: kept, for the weak effect and for a null coefficient alike. Single selection: broken, nine percent. Double selection: kept.
One subtlety remains: which target? The true coefficient in the full model, or the coefficient of a variable in whatever model was selected? Debiasing aims at the true coefficient and relies on sparsity. Richard Berk and colleagues' post-selection inference, and Jason Lee and colleagues' exact selective inference, can target selected-model coefficients without a sparse full-model assumption, under their Gaussian design and noise conditions. The interval cost depends on the selection and target. Part 56 develops both.
Numbers: 75.1% vs 95.6%; 9.2% vs 94.2%
11Matrix completionMaster's5 min
In 2006 Netflix offered a million dollars to anyone who could improve its film recommendations by ten percent. The data were a matrix of four hundred and eighty thousand users by seventeen thousand seven hundred films, with about one percent of the entries known: the ratings users had actually given. The task was to fill in the rest. The prize was won in 2009 by a team whose methods had, at their core, low-rank factor models: the idea that tastes are described by a few hidden dimensions.
Suppose the full matrix has low rank: each user's ratings a combination of a few taste profiles. Then its identifiable rank-r dimension is r times m plus k minus r, removing factorization redundancies, far fewer than its m times k entries, and a fraction of the entries might determine the rest. The direct problem, the matrix of smallest rank that agrees with the known entries, is NP-hard. And look at it this way: the rank is the number of nonzero singular values, the zero norm of the vector of singular values. It is chapter three's problem in disguise.
The same relaxation works. Replace the rank by the nuclear norm, the sum of the singular values, their one norm. Maryam Fazel showed in 2002 that it is the convex envelope of rank on the unit operator-norm ball, paralleling the bounded-box count relaxation. Fit the observed entries with a nuclear-norm penalty: a matrix lasso. Its proximal step is the matrix version of soft thresholding: take the SVD and soft-threshold the singular values.
Rahul Mazumder, Trevor Hastie and Robert Tibshirani's SoftImpute is almost a one-line algorithm. Fill the missing entries with the current guess. Take the singular value decomposition. Soft-threshold the singular values to get the next guess. Repeat. It is like EM from Part 22, with imputation and shrinkage alternating, and like the lasso it is computed along a decreasing sequence of lambdas with warm starts.
A simulated example: a hundred and twenty by ninety matrix of rank four, a corner of which is shown with brightness for the value. We observe thirty percent of the entries, each with noise; the hatched cells are missing. Brightness uses a common scale, clipped at plus and minus six. SoftImpute fills them in. The pattern returns, and the relative error against latent truth on untouched test cells is about twenty-seven percent. Lambda was selected by noisy validation-cell error, without using test cells or latent truth for tuning.
The SoftImpute path, from a large lambda on the right, where the answer is the zero matrix, to small. The gold numbers are the rank of each fit. The fitted rank is four at lambda fifteen, with validation mean squared error about one point five eight. The smallest validation error is about point five eight at lambda three, which keeps the four large singular values less shrunk and lets in a few tiny extra ones: the lasso's bias trade-off, again.
The singular values tell the story. The four true ones are recovered, each shrunk by fifteen to twenty percent. The extra ones are an order of magnitude smaller, so the fit is nearly rank four. And as with the lasso, refitting or reweighting can reduce shrinkage at a possible variance cost, the matrix versions of chapter six's remedies.
The theory mirrors chapter nine. Emmanuel Candès and Benjamin Recht proved in 2009 that if the number of observed entries is a constant times the rank times the dimensions, up to logarithms, entries are sampled uniformly at random, and the matrix satisfies the theorem's incoherence conditions, with singular vectors spread over rows and columns, then nuclear-norm minimization recovers the matrix exactly with high probability. For uniform recovery from few randomly sampled entries, concentration can obstruct recovery: a matrix that is zero except for one entry cannot be recovered unless that entry is observed. Part 52 returns to low-rank recovery with noise.
Numbers: validation chooses λ = 3; test error 27.4%; fitted rank 23
Recap, problems, and the road aheadAll tracks4 min
Part thirty-two in twelve lines. The phantom came back exactly from a fifth of its Fourier coefficients. With more unknowns than equations we need structure; sparsity is one useful choice. Ridge stabilizes but never selects. On a unit coordinate box, the one norm is the convex envelope of counting. The lasso's optimality conditions pin active correlations at lambda, and its zeros come from corners. Least angle regression computes the exact path, on which HDL drops out and returns. The elastic net shares among correlated variables, the group lasso selects groups, the fused lasso finds jumps, and MCP removes the bias on large effects. Cross-validation predicts well; stability selection selects well. Both Laplace and horseshoe are continuous priors; the horseshoe provides stronger near-zero shrinkage, not exact posterior zeros. The null space property and the restricted isometry property explain compressed sensing, with its sharp phase transition. Naive intervals after the lasso cover seventy-five percent; debiased ones cover ninety-five. And matrix completion is the lasso of singular values.
Two promises for later. This part claimed that the lasso recovers sparse signals from about s log p over s observations. It stated rates and conditions without proving them. Part 52 proves the lasso's oracle inequality, an error of order s log p over n under restricted eigenvalue conditions, and Martin Wainwright's primal–dual witness for exact support recovery.
And second: we saw a sharp phase transition in simulation and took Donoho and Tanner's curve on trust. Part 59's approximate message passing derives that curve from a one-line recursion, and gives the lasso's exact risk when p and n grow in proportion.
Where it comes back. Part 33 handles the thousands of tests that screening creates. Part 34 wraps lasso predictions in conformal intervals with guarantees. Part 36's double machine learning extends double selection. Part 50 proves that s log p over s is the best possible rate, and why sparse principal components may be computationally hard. Part 51 proves the restricted isometry property for random matrices. Part 52 proves the oracle inequalities and returns to low-rank recovery. And Part 56 develops inference after selection in full.
Six problems, with full solutions in the README. Ridge through the SVD; soft thresholding from the subgradient; where the lasso path begins; the null space property's sufficiency; why the independent normal-means Laplace posterior mean is nonzero for nonzero observations; and singular value thresholding as the nuclear norm's proximal map. Pause here if you want to try them.
The books this part follows: Hastie, Tibshirani and Wainwright's Statistical Learning with Sparsity; Bühlmann and van de Geer; Foucart and Rauhut on compressive sensing; and The Elements of Statistical Learning; with the papers from Hoerl and Kennard to Belloni, Chernozhukov and Hansen.
Thirty-two parts of sixty-five. We can find a few real effects among thousands of candidates, and say honestly how sure we are. But selecting variables means asking thousands of questions at once, and when you ask enough questions, chance will answer some of them. Part 33: which answers are real? Thousands of questions.
Where it goes next. Selecting variables means asking thousands of questions (Part 33); double selection becomes double machine learning in Part 36; the RIP for random matrices is proved in Part 51, the lasso's oracle inequality in Part 52, selective inference in Part 56, and the phase transition is derived by AMP in Part 59.
Key results
The part's results in one place, for revision.
Try it
Lab 32 · Basis pursuit, least norm, and the phase transition
Measure a 10-sparse vector of length 200 with 60 random combinations and solve for it by minimum l1 norm and by minimum l2 norm; then, with half as many equations as unknowns, raise the sparsity until l1 recovery fails and compare the breaking point with the Donoho-Tanner curve.
python -m videos.stats.labs 32
needs numpy, scipy, matplotlib · download lab32.py ·
source on GitHubp = 200, n = 60, s = 10: relative error of minimum l1 9.1e-14 (theory: exact)
relative error of minimum l2 87% (expected sqrt(1 - n/p) = 84%)
nonzero entries (above 1e-6) l1: 10 l2: 200 truth: 10
Donoho-Tanner breaking point at n/p = 0.5 s/n = 0.386
s/n = 0.1 (s = 5): exact recoveries in 20 trials 100%
s/n = 0.2 (s = 10): exact recoveries in 20 trials 100%
s/n = 0.3 (s = 15): exact recoveries in 20 trials 100%
s/n = 0.4 (s = 20): exact recoveries in 20 trials 50%
s/n = 0.5 (s = 25): exact recoveries in 20 trials 0%
s/n = 0.6 (s = 30): exact recoveries in 20 trials 0%
s/n = 0.7 (s = 35): exact recoveries in 20 trials 0%
The l1 solution is the sparse truth to solver precision while the l2 solution spreads over every coordinate; with n = p/2, recovery switches from nearly always to nearly never around s/n = 0.39.
The code (65 lines; it asserts its own result)
"""Lab 32: recover a sparse vector from too few equations by l1 and by l2, and find where l1 stops working."""
import numpy as np
from videos.coursekit import labs
from explainer.stats.kit import sparse
TITLE = "Basis pursuit, least norm, and the phase transition"
GOAL = ("Measure a 10-sparse vector of length 200 with 60 random combinations and solve for it by minimum l1 norm and by "
"minimum l2 norm; then, with half as many equations as unknowns, raise the sparsity until l1 recovery fails and "
"compare the breaking point with the Donoho-Tanner curve.")
TASKS = [
"Add noise of SD 0.05 to y and replace basis pursuit by sparse.lasso_cd on standardized columns. How does the error grow with the noise?",
"Change delta from 0.5 to 0.25 in the phase experiment. Where does sparse.phase_curve put the new breaking point, and do the trials agree?",
"Make the nonzero entries all +1 instead of random signs, and add the constraint x >= 0 to the linear program. Does the transition move?",
]
P, DELTA = 100, 0.5
RHOS = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
p, n, s = 200, 60, 10
A = rng.standard_normal((n, p)) / np.sqrt(n)
x = np.zeros(p)
x[rng.choice(p, s, replace=False)] = rng.choice([-1.0, 1.0], s) * rng.uniform(1, 2, s)
y = A @ x
x1 = sparse.basis_pursuit(A, y)
x2 = np.linalg.pinv(A) @ y # the minimum-energy solution
err1, err2 = (np.linalg.norm(v - x) / np.linalg.norm(x) for v in (x1, x2))
lab.row("p = 200, n = 60, s = 10: relative error of minimum l1", f"{err1:.1e} (theory: exact)")
lab.row("relative error of minimum l2", f"{err2:.0%} (expected sqrt(1 - n/p) = {np.sqrt(1 - n / p):.0%})")
lab.row("nonzero entries (above 1e-6)", f"l1: {int(np.sum(np.abs(x1) > 1e-6))} l2: {int(np.sum(np.abs(x2) > 1e-6))} truth: {s}")
assert err1 < 1e-6, "basis pursuit recovers a 10-sparse vector from 60 Gaussian measurements"
assert abs(err2 - np.sqrt(1 - n / p)) < 0.1 and np.allclose(A @ x2, y), "least norm fits the data and misses the signal"
rho_star = float(sparse.phase_curve([DELTA])[0])
rate = sparse.phase_grid(P, [DELTA], RHOS, reps=20, rng=rng)[:, 0]
lab.row("Donoho-Tanner breaking point at n/p = 0.5", f"s/n = {rho_star:.3f}")
for r, ok in zip(RHOS, rate):
lab.row(f"s/n = {r:.1f} (s = {int(round(r * DELTA * P))}): exact recoveries in 20 trials", f"{ok:.0%}")
assert abs(rho_star - 0.386) < 0.005, "the curve's value at delta = 0.5"
assert rate[RHOS <= 0.2].min() >= 0.9 and rate[RHOS >= 0.6].max() <= 0.1, "success below the curve, failure above"
cross = RHOS[np.argmax(rate < 0.5)]
assert 0.3 <= cross <= 0.5, "the empirical 50% point brackets the asymptotic curve"
lab.note = ("The l1 solution is the sparse truth to solver precision while the l2 solution spreads over every "
"coordinate; with n = p/2, recovery switches from nearly always to nearly never around s/n = 0.39.")
fig, ax = labs.figure(2, size=(11, 4.2))
idx = np.arange(p)
ax[0].vlines(idx, 0, x2, color=labs.RED, lw=1, label=f"minimum l2 (error {err2:.0%})")
ax[0].plot(idx[x != 0], x[x != 0], "o", ms=8, mfc="none", color=labs.MUTED, label="truth (10 nonzero)")
ax[0].plot(idx[np.abs(x1) > 1e-6], x1[np.abs(x1) > 1e-6], ".", ms=7, color=labs.GOLD, label=f"minimum l1 (error {err1:.0e})")
ax[0].set(title="200 unknowns from 60 equations", xlabel="coordinate", ylabel="value", ylim=(-2.4, 3.4))
ax[0].legend(loc="upper center", ncol=3, fontsize=8)
ax[1].plot(RHOS, rate, "o-", color=labs.BLUE, label="basis pursuit, 20 trials each (p = 100, n = 50)")
ax[1].axvline(rho_star, color=labs.GOLD, ls="--", label=f"Donoho-Tanner: s/n = {rho_star:.3f}")
ax[1].set(title="Exact recovery against sparsity, n/p = 0.5", xlabel="sparsity s/n", ylabel="share of exact recoveries",
ylim=(-0.05, 1.45))
ax[1].legend(loc="upper right")
lab.fig = fig
return lab
Now change it
- Add noise of SD 0.05 to y and replace basis pursuit by sparse.lasso_cd on standardized columns. How does the error grow with the noise?
- Change delta from 0.5 to 0.25 in the phase experiment. Where does sparse.phase_curve put the new breaking point, and do the trials agree?
- Make the nonzero entries all +1 instead of random signs, and add the constraint x >= 0 to the linear program. Does the transition move?
Problems, with solutions
Try each problem before opening its solution.
1. Ridge through the SVD. Show that ridge's fitted values are \(\sum_j u_j\, d_j^2/(d_j^2 + \lambda)\, u_j^\top y\) and that \(\mathrm{df}(\lambda) = \sum_j d_j^2/(d_j^2 + \lambda)\).
Solution
With X = UDVᵀ, XᵀX + λI = V(D² + λI)Vᵀ, so β̂_λ = V(D² + λI)⁻¹DUᵀy. The fit is Xβ̂_λ = UD(D² + λI)⁻¹DUᵀy = Σ_j u_j d_j²/(d_j² + λ) u_jᵀy. The hat matrix H_λ = U diag(d_j²/(d_j² + λ)) Uᵀ has trace Σ_j d_j²/(d_j² + λ).
2. Soft thresholding. Derive the soft-threshold solution of \(\min_b \tfrac12(b - z)^2 + \lambda|b|\) from the subgradient condition.
Solution
The function f(b) = ½(b − z)² + λ|b| is strictly convex, and 0 ∈ ∂f(b) = b − z + λ∂|b|.
- If b > 0, then b = z − λ, which needs z > λ.
- If b < 0, then b = z + λ, which needs z < −λ.
- If b = 0, then z ∈ λ[−1, 1], i.e. |z| ≤ λ.
Together, b = sign(z)(|z| − λ)₊.
3. Where the path begins. Show that \(\hat\beta = 0\) solves the lasso iff \(\lambda \ge \|X^\top y\|_\infty / n\).
Solution
At β = 0 the gradient of the loss is −Xᵀy/n, and the subdifferential of λ‖β‖₁ is λ[−1, 1]ᵖ. So 0 ∈ −Xᵀy/n + λ[−1, 1]ᵖ iff |x_jᵀy|/n ≤ λ for every j, i.e. λ ≥ ‖Xᵀy‖∞/n. By convexity, a point satisfying the optimality condition is a minimizer.
4. The null space property. Prove: if \(\|h_S\|_1 < \|h_{S^c}\|_1\) for every \(0 \ne h \in \mathrm{null}(A)\), basis pursuit recovers every \(x\) supported on \(S\).
Solution
Let x be supported on S. Any other feasible point is z = x + h with 0 ≠ h ∈ null(A). Then ‖z‖₁ = ‖x_S + h_S‖₁ + ‖h_{S^c}‖₁ ≥ ‖x_S‖₁ − ‖h_S‖₁ + ‖h_{S^c}‖₁ > ‖x_S‖₁ = ‖x‖₁, using the reverse triangle inequality and then the hypothesis. So x is the unique minimizer.
5. The Laplace posterior mean. For \(\theta \mid y\) with \(y \sim N(\theta, 1)\) and a Laplace(\(\lambda\)) prior, show \(E(\theta \mid y) \ne 0\) for \(y \ne 0\).
Solution
The posterior density is π(θ | y) ∝ exp(−(y − θ)²/2 − λ|θ|), and the mean is
E(θ | y) = ∫θ π / ∫π. Write the numerator as ∫θ e^{−(y−θ)²/2} e^{−λ|θ|} dθ. For y > 0, pair θ with −θ: the
integrand at θ > 0 exceeds the magnitude at −θ, because e^{−(y−θ)²/2} > e^{−(y+θ)²/2} when yθ > 0. So the
numerator is strictly positive. Likewise it is negative for y < 0, so E(θ | y) ≠ 0 whenever y ≠ 0. (The
closed form in laplace_posterior_mean writes the posterior as a mixture of two truncated normals.)
6. Singular value thresholding. Show that the prox of \(\lambda\|Z\|_*\) soft-thresholds the singular values of \(Z\) (use von Neumann's trace inequality).
Solution
Minimize ½‖Z − W‖²_F + λ‖Z‖_*. Write W = UΣVᵀ. For any Z with singular values s, von Neumann's inequality gives ⟨Z, W⟩ ≤ Σ s_iσ_i. So ½‖Z − W‖² ≥ ½Σ(s_i − σ_i)², with equality when Z shares W's singular vectors. The problem therefore reduces to min_s Σ[½(s_i − σ_i)² + λs_i] over s_i ≥ 0. The solution is s_i = (σ_i − λ)₊, so the minimizer is Z = U(Σ − λI)₊Vᵀ.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| thousands of tests after screening | 33 |
| conformal intervals around sparse fits | 34 |
| double machine learning | 36 |
| Fano bounds and s log(p/s); sparse PCA's barrier | 50 |
| concentration and the RIP for random matrices | 51 |
| oracle inequalities; support recovery; low-rank recovery | 52 |
| posterior contraction for sparse priors | 53 |
| selective inference and PoSI | 56 |
| AMP, state evolution and the phase transition | 59 |
| the Coverage Board | every part; 65 |
Glossary
- Sparsity; support; the bet on sparsity; s log(p/s): few nonzero coefficients, which ones, and how much data finding them needs.
- Ridge; shrinkage factor; effective degrees of freedom; ridge trace: ℓ2 penalization and its anatomy.
- Best subset; ℓ0; hard thresholding; convex envelope: counting and its tightest convex relaxation.
- Lasso; subgradient; KKT conditions; soft thresholding; λ_max: ℓ1 penalization and its optimality conditions.
- Coordinate descent; warm start; active set; strong rule; LARS; equiangular vector; forward stagewise: how the path is computed.
- Elastic net; grouping effect; group lasso; fused lasso; total variation; adaptive lasso; oracle property; SCAD; MCP: the penalty zoo.
- One-SE rule; selection consistency; stability selection; selection probability: choosing λ for prediction or selection.
- Laplace prior; Bayesian lasso; horseshoe; shrinkage factor κ; spike-and-slab: Bayesian sparsity.
- Basis pursuit; null space property; restricted isometry property; phase transition; incoherence: compressed sensing.
- Winner's curse; naive post-selection inference; debiased lasso; nodewise regression; double selection; PoSI: inference after selection.
- Nuclear norm; singular value thresholding; SoftImpute; matrix completion: sparsity of the spectrum.
Sources
- Ridge and subsets.
- A. Hoerl & R. Kennard, Technometrics 12 (1970); A. Hoerl, Chem. Eng. Prog. 58 (1962).
- G. Furnival & R. Wilson, Technometrics 16 (1974); B. Natarajan, SIAM J. Comput. 24 (1995).
- D. Bertsimas, A. King & R. Mazumder, Ann. Stat. 44 (2016).
- The lasso and its computation.
- L. Breiman, Technometrics 37 (1995); R. Tibshirani, JRSS B 58 (1996).
- S. Chen, D. Donoho & M. Saunders, SIAM J. Sci. Comput. 20 (1998).
- B. Efron, T. Hastie, I. Johnstone & R. Tibshirani, Ann. Stat. 32 (2004).
- J. Friedman, T. Hastie, H. Höfling & R. Tibshirani, Ann. Appl. Stat. 1 (2007); J. Friedman, T. Hastie & R. Tibshirani, J. Stat. Softw. 33 (2010).
- R. Tibshirani et al., JRSS B 74 (2012) (strong rules); P. Tseng, JOTA 109 (2001).
- H. Zou, T. Hastie & R. Tibshirani, Ann. Stat. 35 (2007); R. Tibshirani, EJS 7 (2013).
- Penalties.
- H. Zou & T. Hastie, JRSS B 67 (2005); M. Yuan & Y. Lin, JRSS B 68 (2006).
- R. Tibshirani, M. Saunders, S. Rosset, J. Zhu & K. Knight, JRSS B 67 (2005); L. Rudin, S. Osher & E. Fatemi, Physica D 60 (1992); N. Johnson, JCGS 22 (2013).
- H. Zou, JASA 101 (2006); J. Fan & R. Li, JASA 96 (2001); C.-H. Zhang, Ann. Stat. 38 (2010).
- P. Breheny & J. Huang, Ann. Appl. Stat. 5 (2011); N. Simon, J. Friedman, T. Hastie & R. Tibshirani, JCGS 22 (2013).
- Tuning. N. Meinshausen & P. Bühlmann, Ann. Stat. 34 (2006), JRSS B 72 (2010); C. Leng, Y. Lin & G. Wahba, Stat. Sinica 16 (2006).
- Bayes.
- T. Park & G. Casella, JASA 103 (2008); C. Carvalho, N. Polson & J. Scott, Biometrika 97 (2010).
- E. Makalic & D. Schmidt, IEEE SPL 23 (2016); T. Mitchell & J. Beauchamp, JASA 83 (1988); E. George & R. McCulloch, JASA 88 (1993).
- Compressed sensing.
- E. Candès, J. Romberg & T. Tao, IEEE Trans. IT 52 (2006); D. Donoho, IEEE Trans. IT 52 (2006).
- E. Candès & T. Tao, IEEE Trans. IT 51 (2005); E. Candès, C. R. Acad. Sci. 346 (2008).
- A. Cohen, W. Dahmen & R. DeVore, JAMS 22 (2009); R. Baraniuk et al., Constr. Approx. 28 (2008).
- M. Rudelson & R. Vershynin, CPAM 61 (2008); D. Donoho & J. Tanner, Phil. Trans. A 367 (2009); D. Donoho, A. Maleki & A. Montanari, PNAS 106 (2009).
- L. Shepp & B. Logan, IEEE Trans. Nucl. Sci. 21 (1974); A. Chambolle & T. Pock, JMIV 40 (2011).
- Inference.
- S. van de Geer, P. Bühlmann, Y. Ritov & R. Dezeure, Ann. Stat. 42 (2014); C.-H. Zhang & S. Zhang, JRSS B 76 (2014).
- A. Javanmard & A. Montanari, JMLR 15 (2014); A. Belloni, V. Chernozhukov & C. Hansen, Rev. Econ. Stud. 81 (2014).
- R. Berk, L. Brown, A. Buja, K. Zhang & L. Zhao, Ann. Stat. 41 (2013); J. Lee, D. Sun, Y. Sun & J. Taylor, Ann. Stat. 44 (2016).
- Matrices.
- M. Fazel, PhD thesis, Stanford (2002); E. Candès & B. Recht, Found. Comput. Math. 9 (2009); E. Candès & T. Tao, IEEE Trans. IT 56 (2010).
- B. Recht, JMLR 12 (2011); R. Mazumder, T. Hastie & R. Tibshirani, JMLR 11 (2010); R. Bell & Y. Koren, SIGKDD Explorations 9 (2007).
- Books.
- T. Hastie, R. Tibshirani & M. Wainwright, Statistical Learning with Sparsity (2015).
- P. Bühlmann & S. van de Geer, Statistics for High-Dimensional Data (2011).
- S. Foucart & H. Rauhut, A Mathematical Introduction to Compressive Sensing (2013).
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning (2nd ed., 2009).
About this partfrom its README
Part 32 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the twelfth part of Stage III, Master's. Part 31 ended with variables outnumbering observations. This part asks how to solve for many unknowns from few equations, by betting that most of them are zero:
- ridge, the ℓq family and the lasso;
- the lasso's computation and tuning;
- its relatives and its Bayesian counterparts;
- compressed sensing;
- honest inference after selection;
- matrix completion.
Its instrument is the phantom (PhantomPanel): an image panel of greyscale pixels for the Shepp–Logan phantom, its
k-space mask and its reconstructions, on a common scale. Its kit is statkit.sparse.
It opens with Candès's 2004 experiment (Candès, Romberg & Tao 2006). The modified Shepp–Logan phantom (128 × 128) is measured on 22 radial lines of its Fourier transform, 20.6% of the coefficients:
- the minimum-energy (zero-filled) reconstruction has a relative error of 48.2%;
- minimum total variation, by Chambolle–Pock, recovers it to numerical tolerance in this example: errors 19.2%, 4.6%, 0.22%, 1.2 × 10⁻⁵ and 1.6 × 10⁻¹⁰ after 20, 100, 400, 1,500 and 4,000 iterations;
- only 4.6% of horizontal neighbours differ: the image is sparse in its jumps.
From there the part covers:
-
The upgrade of Part 19, the p > n problem and the s log(p/s) count (≈ 76 for p = 20,000, s = 10).
-
Ridge (Hoerl & Kennard 1970) on the diabetes data of Efron, Hastie, Johnstone & Tibshirani (2004): 442 patients, 10 baseline variables.
- Total cholesterol and LDL correlate 0.90; least squares gives them −37.7 and +22.7 per SD; ridge (λ = 10) gives −11.3 and +1.8.
- Singular values 42.2 … 1.95 (condition number 21.7). Shrinkage factors at λ = 10 are 0.99 … 0.78, 0.28; at λ = 1,000 they are 0.64 … 0.004.
- The weakest direction is −0.71·tc + 0.56·ldl + …; the ridge trace against df.
- Ridge as a normal prior with fixed variances; Hoerl and Kennard's existence theorem (dMSE/dλ at 0 = −2σ²Σd_j⁻⁴ < 0).
-
From ℓ0 to ℓ1.
- Best subset and hard thresholding; 2⁶⁴ = 1.8 × 10¹⁹ subsets (585 years at 10⁹ fits a second); Natarajan's NP-hardness (1995).
- The ℓq balls; the octahedron; ℓ1 as the convex envelope of ℓ0 on the box.
-
The lasso (Tibshirani 1996).
- The KKT conditions; λ_max = ‖Xᵀy‖∞/n.
- Soft, hard and ridge thresholding; the diamond touching at a corner (1.5, 0) where the disc touches at (1.42, 0.47).
- Uniqueness and support bounds under general position; Gaussian fixed-design, fixed-λ df = E rank(X_active), equal to the expected nonzero count under general position (Zou, Hastie & Tibshirani 2007); the bias of λ.
-
Computing the path. Coordinate descent with warm starts, active sets and strong rules (glmnet). LARS and its lasso modification. On the diabetes data:
- the order of entry is BMI, log triglycerides, blood pressure, HDL, sex, glucose, total cholesterol, TC/HDL, LDL, age;
- HDL drops out at s = 0.810 and returns at 0.827, the only difference from pure LARS;
- at s = 1, OLS on unit-norm columns: (−10.0, −239.8, 519.8, 324.4, −792.2, 476.7, 101.0, 177.1, 751.3, 67.6), matching the paper's Table 1.
-
The penalty zoo.
-
Elastic net. With three near-copies (correlation 0.96), the lasso takes two in turn and the elastic net shares the effect.
-
Group lasso (block soft thresholding); fused lasso (RMSE 0.23 against 0.55 raw on a three-step signal); adaptive lasso; SCAD and MCP and their thresholding rules.
-
Support recovery: 200 data sets, n = 100, p = 200, eight effects of 0.5–1, AR(0.5) design, base λ = 1.1√(2 log p/n) for lasso/SCAD/MCP, with a separately rescaled adaptive penalty:
Penalty True found (of 8) False included Exact support ‖β̂ − β‖² lasso 7.02 2.74 3.0% 1.45 adaptive lasso 7.71 2.75 8.5% 0.32 SCAD 7.07 1.88 8.0% 1.28 MCP 7.16 0.40 32.5% 0.78
-
-
Choosing λ on the LARS paper's 64-term quadratic model (main effects, interactions, squares of the standardized variables).
- 10-fold CV: the minimum (λ = 3.02) keeps 15 terms with CV MSE 2,957, against 5,943 with none. The one-SE rule (λ = 5.42) keeps 11: sex, BMI, BP, HDL, LTG, age×sex, age×BP, age×glucose, BMI×BP, BMI² and glucose².
- CV is not selection-consistent.
- Stability selection (60 half-samples) finds 11 terms with Π ≥ 0.8 on the stated path: sex, BMI, BP, HDL, LTG, glucose, age×sex, age×LDL, sex×BMI, BMI×BP and glucose².
-
Bayesian sparsity.
-
The lasso is the Laplace posterior mode. In independent normal means, its posterior mean is nonzero for nonzero observations (zero at y=0), with asymptotic large-observation shrinkage rather than literal thresholding; the Bayesian lasso (Park & Casella 2008).
-
The horseshoe (Carvalho, Polson & Scott 2010) and its Beta(½, ½) shrinkage.
-
200 normal means, 10 at 5:
Estimate Total squared error observations 203 universal soft threshold (3.26) 86 Bayesian lasso 74 horseshoe (τ̂ ≈ 0.21) 31 -
Spike-and-slab.
-
-
Compressed sensing.
-
Basis pursuit against least norm, for p = 200, n = 60 Gaussian measurements and s = 10. ℓ1 is exact (7.7 × 10⁻¹³); ℓ2 has 85% error.
-
The null space property, derived; RIP (Candès & Tao 2005); random matrices need n ≳ s log(p/s).
-
The empirical phase transition (p = 100, 20 trials per cell) against Donoho–Tanner's curve, with ρ(0.5) = 0.386.
-
The phantom against the number of radial lines:
Lines Fraction measured Minimum energy Minimum TV 4 3.1% 73.5% 74.4% 8 6.9% 66.2% 57.9% 12 10.7% 59.4% 27.7% 16 14.2% 56.0% 3.7% 22 20.6% 48.2% 1.4 × 10⁻⁸ 30 27.3% 41.8% 8.9 × 10⁻¹¹
-
-
Inference after the lasso.
- Naive post-lasso intervals; the winner's curse. With n = 100, p = 200 and λ = √(2 log p/n), the 0.25 effect is selected 23% of the time, with mean estimate 0.34 when selected.
- The debiased lasso with nodewise regression (van de Geer, Bühlmann, Ritov & Dezeure 2014; Zhang & Zhang 2014; Javanmard & Montanari 2014).
- Double selection (Belloni, Chernozhukov & Hansen 2014): single selection estimates 0.71 and double selection 0.49, for α = 0.5.
- PoSI and selective inference, pointing to Part 56.
-
Matrix completion.
- The Netflix Prize; the nuclear norm as the convex envelope of rank (Fazel 2002).
- SoftImpute (Mazumder, Hastie & Tibshirani 2010) on a 120 × 90 rank-4 matrix with 30% of its entries observed with noise. Noisy validation cells choose λ = 3; latent-truth relative error on untouched test cells is 27.4%. Singular values 133, 113, 93, 70 become 114, 96, 76, 57; the next are 8 and 6.
- Candès & Recht's recovery theorem; incoherence.
Data:
- the diabetes data (Efron et al. 2004, as distributed with scikit-learn) are the Museum's;
- the phantom is Shepp & Logan's (1974) in Toft's modified form;
- the rest are seeded simulations.
Built in this part:
statkit.sparse(explainer/stats/kit/sparse.py), checked intests/test_stats_kit_sparse.py:- Ridge and lasso: ridge by the SVD; the lasso, elastic net and adaptive lasso by coordinate descent along a warm-started path; KKT checks; the exact LARS and LARS-lasso paths.
- Other penalties: soft, hard, SCAD and MCP rules and their coordinate descent; the group lasso.
- Tuning: CV with the one-SE rule; stability selection.
- Bayesian sparsity: Laplace and horseshoe shrinkage profiles; Gibbs samplers for the Bayesian lasso and the horseshoe.
- Compressed sensing: basis pursuit by LP; the Donoho–Tanner curve and empirical phase grid; the Shepp–Logan phantom, radial masks and TV recovery.
- Inference and matrices: naive post-selection OLS, the debiased lasso, single and double selection; SoftImpute.
- The Museum gains
diabetes(). - The phantom (
PhantomPanelinexplainer/stats/viz.py).
The Coverage Board gains five rows. 95% intervals, 1,000 data sets each:
| Method | Setting | Achieved | Verdict |
|---|---|---|---|
| naive post-lasso CIs, every selected variable | n = 100, p = 200, 6 true effects (5,651 intervals) | 75.1% | broken |
| debiased lasso | β_j = 0.25 | 95.6% | kept |
| debiased lasso | β_j = 0 | 95.7% | kept |
| single selection, treatment effect | n = 100, p = 100, 5 confounders | 9.2% | broken |
| double selection, treatment effect | same | 94.2% | kept |
Naive intervals for false positives cover 0 only 25% of the time. For the 0.25 effect, given that it is selected, they cover 92%.
Scientific scope and repairs: the radial Fourier/TV phantom is a deterministic, noiseless numerical example, not a uniform guarantee from a random-measurement theorem. The reported 4.6% counts horizontal neighbor differences. A fraction of sampled complex Fourier coefficients does not count independent real equations because conjugate pairs repeat information. TV weights jumps by contrast; panel brightness is clipped to the displayed common range. Sparse recovery needs design and signal/noise assumptions, not merely an order-of-magnitude s log(p/s) count. Alternatives such as smoothness, low rank and dense regularization are available when sparsity is unsuitable.
Ridge is generically dense; individual coefficients can cross zero at finite lambda. It does not create the lasso's thresholded zero region. Effective degrees of freedom start at rank(X), and the oracle MSE-improvement argument requires a full-column-rank design and positive noise variance. Its improving lambda can depend on unknown beta; this is not uniform dominance by one fixed penalty. The lambda=10 table now uses that exact value, rather than the nearest path-grid point. The convex-envelope comparison uses a bounded coordinate box. Group thresholding uses orthonormalized group coordinates. Flat SCAD/MCP derivatives reduce shrinkage but do not guarantee finite-sample unbiasedness after selection. Correlated designs do not shrink each coefficient by one common lambda shift.
Every main-effect and polynomial-feature centering/scaling operation is now fitted inside its CV training fold, with validation transformed by those parameters. The absolute lambda grid is predetermined (80 down to 0.08); validation outcomes do not set its maximum. Half-sample stability analysis also refits those transformations. CV fold standard errors and the one-SE rule are descriptive heuristics, not confidence bands. Support consistency is not generally guaranteed by prediction tuning. Stability error bounds require assumptions including exchangeable noise and a suitable base selector; for a whole lambda region q counts the per-subsample union. The observed mean union size is 37.65, not the eleven retained stable terms, and no verified false-discovery guarantee is claimed for the diabetes data.
The coefficient-error comparison now uses beta multiplied by each simulated design column's original SD, matching the standardized coefficient target. The adaptive procedure has a separately rescaled weighted penalty; these are illustrative tuning choices rather than an optimally matched comparison. The pooled selected-interval coverage Board now uses independent-dataset ratio-estimator MCSE: 0.005668 across 1,000 datasets, allowing dependent intervals and a random number selected (5,651 total). The other rows report one interval per dataset. Debiasing and double-selection claims include design, precision-estimation, variance and exogeneity assumptions; neither fixes unobserved confounding. The red estimate histogram is explicitly conditional on selection.
Both Laplace and horseshoe are continuous priors without point mass at zero. The horseshoe mean curve now uses endpoint-resolved quadrature checked independently in kappa coordinates. Its simulation uses four independent chains, each with 25,000 retained draws after 5,000 warmup iterations. The global-scale Rhat is 1.00170, bulk ESS 1,618 and tail ESS 2,988; these check the global scale and between-chain mean stability, not every latent variable. Its SSE is 31.48 in this one seeded experiment, not a universal ranking. The Bayesian-lasso Gibbs approximation is compared with its independent closed-form normal-means mean.
Matrix completion no longer tunes on hidden latent truth: 3,260 cells train the fits, 1,610 noisy validation cells choose lambda and 5,930 untouched cells evaluate the selected fit. Every SoftImpute path fit is checked for convergence; the selected rank is 23 with four dominant singular values, not an exactly rank-four fit. Missing cells have a separate hatch, and brightness saturation at ±6 is disclosed. Exact noiseless recovery theory requires the stated random-entry sampling and incoherence conditions; observational recommender ratings need not satisfy them.
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | Candès's phantom | 20.6% of k-space; 48% vs 1.6 × 10⁻¹⁰ |
| 1 | Upgrade: what Part 19 shrank | s log(p/s) ≈ 76 |
| 2 | Ridge | −37.7/+22.7 → −11.3/+1.8; condition number 22 |
| 3 | From ℓ0 to ℓ1 | 2⁶⁴ subsets, 585 years |
| 4 | The lasso | corner (1.5, 0) vs (1.42, 0.47) |
| 5 | Computing the path | 12 steps; HDL leaves at 0.81 |
| 6 | The penalty zoo | MCP 0.40 false vs lasso 2.74 |
| 7 | Choosing λ | 15 / 11 terms; 11 stable |
| 8 | Bayesian sparsity | SSE 203 / 86 / 74 / 31 |
| 9 | Compressed sensing | ρ(0.5) = 0.386; 16 lines 3.7%, 22 exact |
| 10 | Inference after the lasso | 75.1% vs 95.6%; 9.2% vs 94.2% |
| 11 | Matrix completion | validation chooses λ = 3; test error 27.4%; fitted rank 23 |
| 12 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Candès's phantom (2004; Candès, Romberg & Tao 2006).
- Upgrade card (Part 19).
- Ridge (Hoerl & Kennard 1970). SVD shrinkage; ridge as a prior.
- From ℓ0 to ℓ1. ℓq balls morphing in 3D.
- The lasso (Tibshirani 1996). KKT; soft-thresholding; the octahedron (
L1Geometry). - Computing it. Coordinate descent (Part 21); LARS and the path.
- The penalty zoo. Elastic net, group, fused, adaptive, SCAD, MCP.
- Choosing λ. CV; stability selection.
- Bayesian sparsity. The Laplace prior's mean is not sparse; the horseshoe.
- Compressed sensing. RIP and null-space properties (stated; proved in Part 51); the phantom (Built).
- Inference after the lasso. Naive (Board); debiased lasso; double selection (Belloni, Chernozhukov & Hansen 2014).
- Matrix completion. The nuclear norm; SoftImpute.
- Outro. Upgrade cards for Parts 52 and 59.
Built: statkit.sparse; the phantom.
Build the film
python -m videos.stats.stats32.compute # the part's numbers, into .cache/stats32
python tools/build.py stats32 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats32 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats32. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats32.compute # once (a few minutes)
python tools/build.py stats32 -q l # fast 480p preview
python tools/build.py stats32 # 1080p30 -> renders/stats32.mp4
python tools/qa_scene.py stats32 Compressed
python tools/lecture_length.py stats32 --floor 50