Exercise: ridge, lasso & elastic net

Goal

By the end of this exercise you should be able to:

  • explain why ordinary least squares fails when predictors outnumber samples (\(p \gg n\)) or are collinear,
  • describe the penalized objective in words (squared miss + \(\lambda\) × penalty) and give the penalty for ridge, lasso, and elastic net,
  • compute a ridge estimate by hand on a tiny problem and see how \(\lambda\) shrinks it,
  • explain, from the geometry (circle vs diamond), why lasso zeros coefficients and ridge does not,
  • see in a demo that, for two correlated genes, lasso keeps one more or less at random while ridge shares the weight,
  • fit all three with glmnet in R, choose \(\lambda\) by cross-validation, and read off the selected genes.

Background

Ordinary least squares picks the coefficients with the smallest total squared miss (residual sum of squares, RSS). When \(p > n\) there are many perfect fits and no single answer; when predictors are collinear the coefficients are unstable (see Why penalize?).

Penalized regression adds a competing goal — keep the coefficients small. The computer picks the coefficients that make

squared miss + \(\lambda\) × penalty

as small as possible, with \(\lambda \ge 0\) the dial between the two goals.

Method penalty effect simple formula?
Ridge (L2) \(\sum_j\beta_j^2\) shrinks all; keeps all yes; with one predictor \(\hat\beta = \dfrac{\sum xy}{\sum x^2+\lambda}\)
Lasso (L1) \(\sum_j\lvert\beta_j\rvert\) shrinks; sets some to 0 no — the computer searches
Elastic net \(\alpha\times\) lasso penalty \(+\,(1-\alpha)\times\) ridge penalty grouped selection no

Key facts to keep in hand:

  • Standardize predictors before penalizing (glmnet does this); never penalize the intercept.
  • \(\lambda=0\) → ordinary least squares (OLS); \(\lambda\to\infty\) → all coefficients \(\to 0\).
  • Choose \(\lambda\) by cross-validation — never by training error, which just falls as \(\lambda\to0\).

In matrix notation ordinary least squares is \(\hat{\boldsymbol\beta}_{\text{OLS}} = \arg\min_{\boldsymbol\beta}\lVert\mathbf{y}-X\boldsymbol\beta\rVert^2 = (X^\top X)^{-1}X^\top\mathbf{y}\), which needs \(X^\top X\) to be invertible; when \(p > n\) or predictors are collinear it is singular (or nearly so). The penalized estimate is \(\arg\min_{\boldsymbol\beta}\ \lVert\mathbf{y}-X\boldsymbol\beta\rVert^2 + \lambda\cdot\text{penalty}(\boldsymbol\beta)\), and ridge has the closed form \(\hat{\boldsymbol\beta}_{\text{ridge}} = (X^\top X+\lambda I)^{-1}X^\top\mathbf{y}\): adding \(\lambda\) to the diagonal makes the matrix invertible again. Items B3 (matrix version in its solution) and B4 use this.

By hand

B1. Explain in one or two sentences why ordinary least squares has no unique solution when you have \(p = 3\) predictors but only \(n = 2\) samples. (Count the unknowns and the equations.)

B2. (ridge on a 1-D toy). Suppose after centring there is a single predictor with \(\sum x^2 = 4\) and \(\sum xy = 8\) (so the ordinary least squares slope is \(8/4 = 2\)). The 1-D ridge estimate is \[\hat\beta_{\text{ridge}}(\lambda) = \frac{\sum xy}{\sum x^2 + \lambda} = \frac{8}{4+\lambda}.\] Compute \(\hat\beta_{\text{ridge}}\) for \(\lambda = 0,\ 4,\ 12,\ \text{and as }\lambda\to\infty\). What happens to the coefficient as \(\lambda\) grows?

B3. (ridge with two uncorrelated predictors). Take two standardized predictors \(x\) and \(z\) that are uncorrelated, scaled so that \(\sum x^2 = \sum z^2 = 1\) and \(\sum xz = 0\), with \(\sum xy = 3\) and \(\sum zy = 1\). Because the predictors are uncorrelated, the 1-D formula from B2 applies to each coefficient separately: \(\hat\beta = \dfrac{\sum xy}{1+\lambda}\) for \(x\), and likewise for \(z\). (a) Find the ordinary least squares estimates (\(\lambda = 0\)). (b) Find the ridge estimates at \(\lambda = 1\). (c) By what factor was each coefficient shrunk? Did either become exactly zero?

B4. (optional) (collinearity and the diagonal). For a collinear design suppose \(X^\top X = \begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}\). (a) Show it is singular (its columns are parallel; row-reduce \([\,X^\top X \mid I\,]\) and see what happens) — so ordinary least squares cannot invert it. (b) Form \(X^\top X + \lambda I\) with \(\lambda = 1\) and find its inverse by row-reducing \([\,X^\top X + I \mid I\,]\). Is it now invertible? (c) In one sentence, connect this to the eigenvalue fact that adding \(\lambda I\) shifts every eigenvalue up by \(\lambda\) (recall Eigenvalues & eigenvectors).

B5. (the geometry). Sketch, in the \((\beta_1,\beta_2)\) plane: (a) the ridge budget region \(\beta_1^2+\beta_2^2\le t\) and the lasso budget region \(\lvert\beta_1\rvert+\lvert\beta_2\rvert\le t\); (b) a set of elliptical RSS contours centred at an ordinary least squares solution like \((2, 0.3)\). Argue from the picture which method is likely to return a solution with \(\beta_2 = 0\) exactly, and why the shape of the region is responsible.

B6. (reading a path plot). A lasso plot(fit, xvar="lambda") shows coefficient paths against \(\log\lambda\). As \(\lambda\) increases (moving right), do the coefficients get larger or smaller? What does it mean when a path hits the horizontal axis and stays there? At the far right, how many predictors does the model use?

B7. (choosing among the three). For each scenario, say whether you would start with ridge, lasso, or elastic net, and why: (a) 15 000 genes, 30 samples, you want a short panel to validate in the lab; (b) a handful of highly co-regulated genes that you believe are all biologically relevant and want to keep; (c) 15 000 genes, 30 samples, many correlated pathway modules, you want selection but stable to resampling.

Explore: the geometry, live

The first demo draws B5 for you. The grey ellipses are RSS contours around the ordinary least squares point (labelled OLS; drag it); the green region is the penalty region \(\alpha(|\beta_1|+|\beta_2|) + (1-\alpha)(\beta_1^2+\beta_2^2) \le t\), drawn at the budget \(t\) that the current \(\lambda\) leads to; the purple ellipse is the smallest RSS contour that touches it, and the touching point is the penalized estimate \(\hat{\boldsymbol\beta}\). The slider “corr” sets the correlation between the two (standardized) predictors, which tilts and stretches the ellipses. The right panel is the coefficient path: \(\hat\beta_1\) and \(\hat\beta_2\) against \(\lambda\), with the current \(\lambda\) dashed.

E1. Start from Reset (lasso, OLS point \(= (2, 0.6)\), corr \(= 0.4\)). Move \(\lambda\) slowly up from \(0.01\). At roughly which \(\lambda\) does \(\hat\beta_2\) become exactly \(0\), and where on the diamond is \(\hat{\boldsymbol\beta}\) from then on? At which \(\lambda\) is \(\hat\beta_1\) also \(0\)?

E2. Click Ridge at \(\lambda = 2\). Is either coefficient exactly zero? Push \(\lambda\) to \(100\) and look at the path panel: do the ridge paths ever reach zero?

E3. Back to Lasso at \(\lambda = 2\). Drag the OLS point around the first quadrant. For which ordinary least squares points does the solution stay on the \(\beta_1\) axis (\(\hat\beta_2 = 0\))? Does the same happen for ridge?

E4. Click Elastic net (\(\alpha = 0.5\)) with the reset settings. Compare the shape of the region and the path with the lasso: does elastic net still produce exact zeros, and does \(\hat\beta_2\) drop out at a smaller or larger \(\lambda\) than with the lasso?

The second demo is the resampling demo from Why penalize?, now with the lasso. Two genes with correlation 0.99 both truly matter: \(y = \text{gene 1} + \text{gene 2} + \text{noise}\), so the true coefficients are \((1, 1)\) (the cross). Each dot is one fit to a new training set of 20 samples; 50 sets. Orange is ordinary least squares, the other colour the penalized fit (\(\lambda = 5\)).

E5. (a) Read the note under the table: in how many of the 50 datasets does the lasso set one gene to exactly 0? Look at the dots on the axes: is it always the same gene? (b) Click OLS vs ridge. Is any coefficient exactly 0 now, and how wide is the range of \(\hat\beta_1\)? (c) What does this tell you about using lasso to decide which of two co-regulated genes matters? Which method from the lecture is meant to fix this?

E1. \(\hat\beta_2\) hits zero at \(\lambda \approx 1.7\). From then on \(\hat{\boldsymbol\beta}\) sits on the corner of the diamond on the \(\beta_1\) axis (the red mark), and the region shrinks along that axis as \(\lambda\) grows. \(\hat\beta_1\) reaches zero at \(\lambda \approx 4.5\); beyond that both coefficients are exactly \(0\) and the region has shrunk to the origin.

E2. No: at \(\lambda = 2\) ridge gives about \((0.70, 0.37)\), both nonzero, and the touching point is on the smooth circle, off the axes. At \(\lambda = 100\) both are tiny (about \(0.02\) and \(0.01\)) but still not zero; the ridge paths approach zero smoothly and never reach it.

E3. The solution stays on the \(\beta_1\) axis for a whole band of OLS points: roughly, whenever the ordinary least squares \(\beta_2\) is small compared with \(\beta_1\) (with \(\lambda = 2\), about \(\beta_2 < 0.7\) when \(\beta_1 = 2\)). Every ellipse centred in that band touches the diamond first at its corner. For ridge the touching point moves smoothly with the OLS point: there is no band of exact zeros. With correlated predictors, ridge can change direction as well as length, so an OLS point on an axis need not stay on it. Exact zeros can occur for special OLS points, but ridge does not produce the lasso’s region of sparse solutions.

E4. The elastic-net region is a diamond with rounded sides, but it keeps its corners on the axes, so it still produces exact zeros. Its \(|\beta|\) part only has weight \(\alpha = 0.5\), so the pull towards exactly zero is weaker and \(\hat\beta_2\) drops out later: at \(\lambda \approx 5.2\) instead of \(\approx 1.7\), and \(\hat\beta_1\) at \(\lambda \approx 9\) instead of \(\approx 4.5\).

E5. (a) In 27 of the 50 datasets the lasso sets one gene to exactly 0, and the dropped gene changes from dataset to dataset: some dots sit on the \(\beta_1\) axis, others on the \(\beta_2\) axis. All lasso estimates stay between 0 and about 2.3, so the wild ordinary least squares values (here \(\hat\beta_1\) from about \(-1.8\) to \(5.4\)) are tamed. (b) Ridge zeroes nothing: its dots form a tight blob around \((1, 1)\), \(\hat\beta_1\) from about 0.7 to 1.2 — the weight is shared between the two genes. (c) With near-duplicate genes the lasso’s choice of which gene to keep is decided by noise, so “gene 1 was selected, gene 2 was not” says nothing about which one matters. Elastic net adds a ridge part that makes correlated genes enter or leave together.

In R

We use glmnet. If needed, install it once with install.packages("glmnet"). The code below is illustrative — read it, then adapt it in the tasks.

Simulate a wide problem (\(p > n\))

library(glmnet)
set.seed(1)

n <- 40      # samples (patients)
p <- 200     # predictors (genes)  -> p > n
x <- matrix(rnorm(n * p), nrow = n, ncol = p)
colnames(x) <- paste0("gene", seq_len(p))

# only 5 genes truly drive the phenotype; the rest are noise
beta_true      <- rep(0, p)
beta_true[1:5] <- c(3, -2, 2, -1.5, 1)
y <- as.numeric(x %*% beta_true + rnorm(n))   # continuous phenotype

Fit ridge, lasso, elastic net

fit_ridge <- glmnet(x, y, alpha = 0)      # ridge:   keeps all genes
fit_lasso <- glmnet(x, y, alpha = 1)      # lasso:   sparse
fit_enet  <- glmnet(x, y, alpha = 0.5)    # elastic net

plot(fit_lasso, xvar = "lambda")           # watch coefficients enter/leave
print(fit_lasso)                           # Df = number of nonzero coefficients

Choose lambda by cross-validation, then read off the genes

set.seed(1)
cv_lasso <- cv.glmnet(x, y, alpha = 1, nfolds = 10)

plot(cv_lasso)                             # CV error vs log(lambda)
cv_lasso$lambda.min                        # minimum CV error
cv_lasso$lambda.1se                        # sparser model within 1 SE

beta <- coef(cv_lasso, s = "lambda.1se")   # sparse coefficient vector
selected <- rownames(beta)[which(beta != 0)]
selected                                   # includes "(Intercept)" + kept genes

Tasks

R1. Run the simulation block. Confirm the shape of x with dim(x) and check p > n.

R2. Fit fit_ridge and fit_lasso. Using predict(fit, type = "nonzero", s = 0.5) or the Df column of print(fit), compare how many genes each model keeps at a moderate \(\lambda\). Which one is sparse?

R3. Run cv.glmnet for lasso. Report lambda.min and lambda.1se, and extract the selected genes at lambda.1se. Did the model recover any of the 5 true genes (gene1…gene5)?

R4. Refit with alpha = 0 (ridge) via cv.glmnet, and coef(...) at lambda.1se. Confirm that essentially no coefficient is exactly zero (ridge keeps all predictors).

R5. Change the outcome to binary — y_bin <- as.integer(y > median(y)) — and fit cv.glmnet(x, y_bin, family = "binomial", alpha = 1). This is penalized logistic regression. Extract the selected genes the same way.

Hints

Each sample gives one equation (“the prediction for this sample equals its measured value”); each predictor’s coefficient is one unknown. With more unknowns (\(p\)) than equations (\(n\)), the system is underdetermined — infinitely many coefficient sets fit perfectly. See the solution-space discussion in Linear systems by hand.

Just plug into \(\hat\beta(\lambda) = \dfrac{8}{4+\lambda}\). The denominator grows with \(\lambda\), so the estimate shrinks monotonically toward \(0\) but never quite reaches it for finite \(\lambda\). That “shrinks but does not zero” behaviour is the signature of the L2 penalty.

With \(\sum x^2 = 1\) the formula is \(\hat\beta = \dfrac{\sum xy}{1+\lambda}\): at \(\lambda = 0\) it is just \(\sum xy\), and every coefficient is the ordinary least squares value times \(\dfrac{1}{1+\lambda}\). At \(\lambda=1\) that factor is \(\tfrac12\).

A matrix with parallel columns is singular (non-invertible): row reduction gives a row of zeros on the left. Adding \(\lambda I\) adds \(\lambda\) to each diagonal entry, which breaks the parallel columns. For the eigenvalues of \(\begin{pmatrix}1&1\\1&1\end{pmatrix}\), use the symmetric pattern from Eigenvalues & eigenvectors. A zero eigenvalue means some direction is squashed to zero (singular); adding \(\lambda I\) raises every eigenvalue by \(\lambda\), so it becomes \(\lambda > 0\) and the matrix becomes invertible.

The ridge region is a circle (round, no corners); the lasso region is a diamond with corners on the axes. The penalized estimate is where the smallest RSS ellipse first touches the region. A corner sticks out furthest, so the ellipse tends to hit it first — and a corner on an axis has one coordinate exactly \(0\).

On plot(fit, xvar="lambda") the x-axis is \(\log\lambda\) increasing to the right. More penalty (right) means smaller coefficients. A path that reaches \(0\) and stays there means that gene has been dropped. At the far right (very large \(\lambda\)) all coefficients are \(\approx 0\) and the model uses essentially no genes. See glmnet.

glmnet(x, y, alpha = a) needs x as a matrix (use as.matrix); alpha is 1 lasso, 0 ridge, in between elastic net. cv.glmnet adds cross-validation and stores $lambda.min and $lambda.1se. Get coefficients with coef(cvfit, s = "lambda.1se"). Set a seed — the folds are random.

Solutions

B1. Count: \(p=3\) unknown coefficients but only \(n=2\) samples, i.e. 2 equations. With more unknowns than equations the system is underdetermined. If the two rows are independent (rank 2), any two responses can be fitted exactly and one coefficient remains free: the exact fits form a line. If the rows are dependent, an exact fit requires consistent responses. In either case, the coefficients of an ordinary least-squares fit are not unique; an exact fit is not guaranteed by shape alone.

B2. \(\hat\beta(\lambda) = \dfrac{8}{4+\lambda}\):

  • \(\lambda=0\): \(8/4 = 2\) (the ordinary least squares value).
  • \(\lambda=4\): \(8/8 = 1\).
  • \(\lambda=12\): \(8/16 = 0.5\).
  • \(\lambda\to\infty\): \(\to 0\).

The coefficient shrinks monotonically toward \(0\) as \(\lambda\) grows, but stays strictly positive for any finite \(\lambda\) — ridge never sets it exactly to zero.

B3. (a) Ordinary least squares (\(\lambda = 0\)): \(3/1 = 3\) for \(x\) and \(1/1 = 1\) for \(z\). (b) Ridge at \(\lambda=1\): \(3/2 = 1.5\) for \(x\) and \(1/2 = 0.5\) for \(z\). (c) Each coefficient was multiplied by \(\tfrac{1}{1+\lambda}=\tfrac12\) — shrunk to half. Neither became exactly zero; ridge shrinks proportionally but keeps both predictors. (Optional, the same in matrices: \(X^\top X = I\) and \(X^\top\mathbf{y} = (3, 1)\), so \((X^\top X + I)^{-1}X^\top\mathbf{y} = (2I)^{-1}(3,1) = \tfrac12(3,1) = (1.5, 0.5)\).)

B4. (optional) (a) The two columns are both \((1,1)\) — parallel. Row reduction: \(\left[\begin{array}{cc|cc} 1 & 1 & 1 & 0 \\ 1 & 1 & 0 & 1 \end{array}\right] \xrightarrow{\;\text{R2}\,-\,\text{R1}\;} \left[\begin{array}{cc|cc} 1 & 1 & 1 & 0 \\ 0 & 0 & -1 & 1 \end{array}\right]\): a zero row on the left → singular, so ordinary least squares cannot invert it. (b) \(X^\top X + I = \begin{pmatrix}2&1\\1&2\end{pmatrix}\). Row reduction: \[ \left[\begin{array}{cc|cc} 2 & 1 & 1 & 0 \\ 1 & 2 & 0 & 1 \end{array}\right] \xrightarrow{\;\text{R2}\,-\,\frac12\text{R1}\;} \left[\begin{array}{cc|cc} 2 & 1 & 1 & 0 \\ 0 & \tfrac32 & -\tfrac12 & 1 \end{array}\right] \xrightarrow{\;\frac23\text{R2}\;} \left[\begin{array}{cc|cc} 2 & 1 & 1 & 0 \\ 0 & 1 & -\tfrac13 & \tfrac23 \end{array}\right] \xrightarrow{\;\frac12(\text{R1}\,-\,\text{R2})\;} \left[\begin{array}{cc|cc} 1 & 0 & \tfrac23 & -\tfrac13 \\ 0 & 1 & -\tfrac13 & \tfrac23 \end{array}\right], \] so it is now invertible, with inverse \(\tfrac13\begin{pmatrix}2&-1\\-1&2\end{pmatrix}\). (c) By the symmetric pattern, \(\begin{pmatrix}1&1\\1&1\end{pmatrix}\) has eigenvalue \(2\) for \((1,1)\) and \(0\) for \((1,-1)\): the \((1,-1)\) direction is squashed to zero, which is why it is singular. Adding \(\lambda I\) shifts the eigenvalues to \(2+\lambda\) and \(\lambda\), so the previously-zero eigenvalue becomes \(\lambda>0\) and the matrix is no longer singular. (Optional: the determinant goes from \(1 - 1 = 0\) to \(4 - 1 = 3\); it is the product of the eigenvalues, \(3 \cdot 1\).)

B5. (a) The ridge region \(\beta_1^2+\beta_2^2\le t\) is a disk / circle; the lasso region \(\lvert\beta_1\rvert+\lvert\beta_2\rvert\le t\) is a diamond with corners on the axes at \((\pm t,0)\) and \((0,\pm t)\). (b) The RSS contours are ellipses centred on the ordinary least squares point \((2,0.3)\), growing outward. The lasso is the one likely to return \(\beta_2 = 0\) exactly: the diamond’s corner on the \(\beta_1\)-axis is the part sticking out toward the ellipses, so an expanding contour tends to first touch there — and that corner has \(\beta_2 = 0\). The circle has no corners, so the ridge touch point sits at a generic location with both coefficients nonzero. The shape (corners vs. smoothness) is what creates, or prevents, sparsity.

B6. As \(\lambda\) increases (moving right), the penalty is stronger, so coefficients get smaller. A path that reaches the horizontal axis and stays there means that predictor’s coefficient has been set to exactly zero — the gene is dropped from the model. At the far right (largest \(\lambda\)) essentially no predictors remain (the model collapses toward just the intercept, predicting \(\bar y\)).

B7. (a) Lasso (or elastic net): you explicitly want a short, interpretable panel, which requires setting most coefficients to zero — ridge would keep all 15 000 genes. (b) Ridge: you want to keep the co-regulated genes and let them share the weight; ridge shrinks them together without dropping any, whereas lasso would arbitrarily discard all but one. (c) Elastic net: you want selection (\(p\gg n\)) but stability across correlated modules — the L2 part makes correlated genes enter or leave together, giving a more reproducible list than pure lasso.

R1.

dim(x)      # 40 200  -> n = 40 rows, p = 200 columns
40 < 200    # TRUE: p > n

R2.

fit_ridge <- glmnet(x, y, alpha = 0)
fit_lasso <- glmnet(x, y, alpha = 1)

# number of nonzero coefficients at a moderate lambda = 0.5
length(predict(fit_lasso, type = "nonzero", s = 0.5)[[1]])  # small: a handful
length(predict(fit_ridge, type = "nonzero", s = 0.5)[[1]])  # all 200: ridge keeps everything

Lasso is sparse (few nonzero coefficients); ridge keeps essentially all 200 genes.

R3.

set.seed(1)
cv_lasso <- cv.glmnet(x, y, alpha = 1, nfolds = 10)
cv_lasso$lambda.min
cv_lasso$lambda.1se

beta <- coef(cv_lasso, s = "lambda.1se")
selected <- rownames(beta)[which(beta != 0)]
selected     # "(Intercept)" plus a short list; should include several of gene1..gene5

With a strong true signal the model typically recovers most of gene1…gene5, plus perhaps a few false positives. The exact set varies with the seed and CV split — an honest reminder that selection is not perfectly stable at small \(n\).

R4.

set.seed(1)
cv_ridge <- cv.glmnet(x, y, alpha = 0, nfolds = 10)
beta_r <- coef(cv_ridge, s = "lambda.1se")
sum(beta_r == 0)     # 0 (or nearly): ridge does not zero coefficients

Ridge shrinks every coefficient but leaves them nonzero — no feature selection.

R5.

y_bin <- as.integer(y > median(y))
set.seed(1)
cv_bin <- cv.glmnet(x, y_bin, family = "binomial", alpha = 1, nfolds = 10)

beta_b <- coef(cv_bin, s = "lambda.1se")
rownames(beta_b)[which(beta_b != 0)]   # selected genes for the binary phenotype

This is penalized logistic regression: same penalty machinery, a binary responder/non-responder outcome, still returning a sparse gene list.

Where this leads

  • Cross-validation and model selection are given a first look here; the full treatment (train/validation/test splits, nested CV, performance metrics) belongs to Statistics and machine learning in bioinformatics.
  • Predictive vs. causal: a selected gene is predictive, not proven causal — collinearity means a dropped gene may be equally relevant. Validation is experimental, not statistical.
  • Penalized generalized linear models: the same penalties extend to logistic and Poisson / negative-binomial outcomes — connecting to the count-distribution material (Poisson & negative binomial) for RNA-seq counts.
  • Relation to PCA: ridge and PCA both stabilise collinear predictors, but PCA (week 2) builds new orthogonal directions, whereas ridge keeps the original genes — worth comparing once you have met both.