Ridge, lasso & elastic net

Week 4 — Ridge, lasso & elastic net

Quantitative biology and integrative omics

About this lecture

In Linear models we fit a straight-line model by least squares. That works beautifully when we have many samples and few predictors. In genomics we usually have the opposite: thousands of genes, a few dozen samples. Ordinary least squares breaks. Today we fix it by penalizing large coefficients.

  • Ridge (L2): shrink all coefficients toward zero — tames collinearity, keeps every predictor.
  • Lasso (L1): shrink and set some coefficients exactly to zero — automatic feature selection (a sparse model).
  • Elastic net: a tunable mix of the two.
  • The geometry behind why lasso zeros coefficients but ridge does not (a diamond vs. a circle).
  • The tuning parameter \lambda, and a first look at choosing it (cross-validation is the next unit).
  • In R: the glmnet package. Biology: selecting a handful of predictive genes from a whole transcriptome.

Biology first: too many genes, too few samples

You measure expression of 20 000 genes in 40 patients and want to predict a phenotype (drug response, tumour subtype, survival). You would like a model

\text{phenotype} \approx \beta_1\,\text{gene}_1 + \beta_2\,\text{gene}_2 + \dots + \beta_p\,\text{gene}_p.

  • Predictors p = 20\,000 hugely exceeds samples n = 40. This is the p \gg n regime — the normal situation in omics.
  • Ordinary least squares has infinitely many perfect fits and picks nonsense: huge, unstable coefficients that memorise noise.
  • Many genes are co-regulated (collinear), so their coefficients trade off wildly.

We want a model that is stable and, ideally, short — built on a few genes we could take to the bench. That is exactly what penalties deliver.

Recall: least squares and where it breaks

Ordinary least squares (OLS) picks the coefficients that make the total squared miss (the residual sum of squares, RSS) as small as possible. Why penalize? showed where that breaks:

  • More genes than samples (p > n): many different coefficient sets fit the training data perfectly, so ordinary least squares has no single answer.
  • Correlated genes: the data pin down their combined effect but not the split, so the coefficients jump around from one dataset to the next (the resampling demo).
  • Either way ordinary least squares has only one goal, fit the training data, and with enough predictors it fits the noise too: overfitting.

We need a second goal that competes with “fit the data”: keep the coefficients small.

The idea: add a penalty for big coefficients

Keep the fit term, but add a cost that grows with the size of the coefficients. The computer picks the coefficients that make

total squared miss (fit the data) + \lambda × penalty (keep the coefficients small)

as small as possible.

  • \lambda \ge 0 sets the exchange rate between the two goals. \lambda = 0 gives plain ordinary least squares; larger \lambda buys smaller coefficients at the price of some fit.
  • The shape of the penalty is what distinguishes the three methods:
Method penalty(\boldsymbol\beta) name
Ridge \sum_j \beta_j^2 L2 (squared)
Lasso \sum_j \lvert\beta_j\rvert L1 (absolute)
Elastic net mix of both L1 + L2

First: put predictors on a common scale

The penalty \sum_j \beta_j^2 (or \sum_j |\beta_j|) adds up coefficients across all predictors. That only makes sense if the predictors are comparable in scale.

  • A gene measured in large units gets an artificially small coefficient and is under-penalized; a gene in small units is over-penalized. The penalty would depend on your units, which is unacceptable.
  • Fix: standardize each predictor to mean 0 and standard deviation 1 before fitting. Then a coefficient’s size reflects importance, not units.
  • The intercept is never penalized — it just anchors the overall level of \mathbf{y}.

glmnet does this standardization for you (standardize = TRUE by default) and reports coefficients back on the original scale.

Ridge regression (L2 penalty)

Penalty = the sum of squared coefficients, \sum_j \beta_j^2.

  • With one predictor, ridge is the formula from Why penalize?: the usual slope with \lambda added below the line, \hat\beta = \dfrac{\sum xy}{\sum x^2 + \lambda}. Bigger \lambda, bigger denominator, smaller slope — but never exactly 0.
  • With many predictors the same happens to all of them: every coefficient is shrunk toward zero, none becomes exactly zero. Ridge keeps all predictors.
  • Ridge always gives one stable answer, even when p > n or genes are correlated. This is why ridge tames collinearity.

Ridge shares weight equally between correlated genes

Two co-regulated genes g_1, g_2 carry almost the same signal. Ordinary least squares is free to write

100\,g_1 - 98\,g_2, \quad\text{or}\quad -50\,g_1 + 52\,g_2, \quad\text{or}\dots

— wildly different coefficients that predict almost identically. The coefficients are unstable: a tiny change in the data flips them.

  • Ridge dislikes large coefficients (they cost \beta^2), so it spreads the weight smoothly and roughly equally between g_1 and g_2 — small, stable, sensible values.
  • This “sharing” behaviour is a hallmark of the L2 penalty and is often desirable in biology, where truly co-regulated genes should share credit.

Lasso regression (L1 penalty)

Penalty = the sum of absolute values, \sum_j \lvert\beta_j\rvert, instead of squares.

  • One small change — squares become absolute values — has a dramatic effect: as \lambda grows, coefficients are driven exactly to zero, one after another.
  • A coefficient of exactly zero means the predictor is dropped. Lasso therefore performs automatic feature selection: it returns a sparse model using only a subset of the genes.
  • There is no simple formula like ridge’s; the computer searches for the best coefficients — which is what glmnet does.

Why lasso zeros coefficients: the geometry

Equivalent view: minimize RSS subject to a budget on the coefficients.

\text{Ridge: } \sum_j \beta_j^2 \le t \qquad\qquad \text{Lasso: } \sum_j \lvert\beta_j\rvert \le t

In two dimensions (\beta_1,\beta_2) the budget region is:

  • Ridge → a circle (disk): \beta_1^2 + \beta_2^2 \le t — smooth, round, no special points.
  • Lasso → a diamond (square on its corner): \lvert\beta_1\rvert + \lvert\beta_2\rvert \le t — with sharp corners sitting on the axes.

The RSS forms elliptical contours around the ordinary least squares solution. The penalized estimate is where the smallest ellipse first touches the budget region.

A corner on an axis means a zero coefficient

  • A corner of the diamond sits on an axis: at that point one of the coordinates is exactly zero (e.g. \beta_2 = 0).
  • Expanding ellipses are very likely to first touch a pointy corner rather than a flat edge — so the lasso solution often lands with some coefficients exactly zero.
  • The circle has no corners, so the touch point almost never sits exactly on an axis — ridge coefficients get small but stay nonzero.

One sentence: the corners of the L1 diamond are what create sparsity; the roundness of the L2 circle is what prevents it.

In higher dimensions the diamond becomes a many-cornered shape whose edges and faces lie in coordinate subspaces — touching one zeros several coefficients at once.

Try it: circle vs diamond

Try it: lasso on correlated genes

Choosing \lambda (preview)

\lambda controls how hard we shrink — the bias–variance dial from Why penalize?.

  • \lambda \to 0: back to ordinary least squares — overfits (high variance).
  • \lambda \to \infty: all coefficients \to 0, the model predicts the mean — underfits (high bias).
  • Somewhere in between is the \lambda that predicts new data best. Training error cannot find it (it keeps falling as \lambda \to 0), so we estimate error on held-out data: cross-validation, the next unit.

glmnet reports two choices: lambda.min (lowest cross-validated error) and lambda.1se (the largest \lambda within one standard error of it: a sparser model that predicts about as well, often preferred for a short gene list).

In R: glmnet

The glmnet package fits ridge, lasso, and elastic net over a whole grid of \lambda efficiently.

library(glmnet)

# x: samples x genes matrix (n rows, p columns); y: the phenotype vector
x <- as.matrix(expr)      # e.g. 40 patients x 20000 genes
y <- response            # numeric outcome (e.g. drug IC50)

# alpha = 1 -> lasso, alpha = 0 -> ridge, 0 < alpha < 1 -> elastic net
fit <- glmnet(x, y, alpha = 1)     # fits a path of lambda values

plot(fit, xvar = "lambda")          # coefficient paths vs log(lambda)
print(fit)                          # Df (# nonzero), %Dev, Lambda per step
  • glmnet standardizes predictors internally (standardize = TRUE) and returns coefficients on the original scale.
  • It does not fit a single \lambda — it returns the whole path, so you see how coefficients enter and leave as \lambda changes.

In R: cross-validated fit and the gene list

set.seed(1)                              # CV is random; fix the seed for reproducibility
cvfit <- cv.glmnet(x, y, alpha = 1, nfolds = 10)

plot(cvfit)                              # CV error vs log(lambda), with lambda.min / .1se
cvfit$lambda.min                         # lambda with lowest CV error
cvfit$lambda.1se                         # sparser model within 1 SE

# coefficients at the chosen lambda
beta <- coef(cvfit, s = "lambda.1se")    # a sparse vector; most entries are 0
selected <- rownames(beta)[which(beta != 0)]
selected                                 # the genes the model kept  <- the biology

# predict the phenotype for new samples
predict(cvfit, newx = x_new, s = "lambda.1se")
  • For a binary phenotype (responder vs. not) use family = "binomial" — penalized logistic regression, same machinery.

Biology: from transcriptome to a testable signature

  • Predictive gene signatures. Lasso / elastic net on expression + drug response returns a small panel of genes that predict response — a candidate biomarker you can take to a targeted assay.
  • Interpretability & cost. A 20-gene panel can be run cheaply in the clinic; a 20 000-gene model cannot. Sparsity is not just statistics — it is assay design.
  • Stability matters. With n \approx 40, different CV splits can select somewhat different genes. Report a stable core, prefer lambda.1se, and consider elastic net so correlated pathway members are kept together.
  • Not causal. A selected gene is predictive, not proven causal — collinearity means a dropped gene may be just as relevant as the one kept. Validate on the bench.

Which penalty when?

Situation Reach for
Many collinear predictors, want to keep them all Ridge
Want a short, interpretable subset (feature selection) Lasso
p \gg n and correlated groups of predictors Elastic net
Purely predictive, interpretability not needed Ridge (often lowest error)
Need a testable gene panel Lasso / elastic net
  • All three reduce variance / overfitting relative to ordinary least squares; they differ in whether and how they zero coefficients.
  • Always standardize (glmnet does it), never penalize the intercept, and choose \lambda by cross-validation.

Summary

Concept Key fact
Problem p \gg n or collinearity → OLS unstable / overfits
General form make squared miss + \lambda × penalty as small as possible
Ridge (L2) penalty \sum\beta_j^2; shrinks all, keeps all; shares weight between correlated genes
Lasso (L1) penalty \sum\lvert\beta_j\rvert; sets some \beta_j = 0 → feature selection; picks one of two correlated genes
Geometry circle (ridge) vs diamond (lasso); corners on axes → zeros
Elastic net \alpha mixes lasso and ridge; grouped selection
\lambda shrinkage dial; bias–variance trade-off; choose by cross-validation
R glmnet(x, y, alpha=…), cv.glmnet(…), coef(cvfit, s="lambda.1se")
Biology short, testable gene signatures; predictive \neq causal

Next: apply this to a real wide expression matrix in the exercise, then test yourself with the quiz.

Optional: the maths behind ridge and lasso

The same objectives in matrix notation, for those who want them.

In words (this lecture) In matrices
ridge: squared miss + \lambda × sum of squares \hat{\boldsymbol\beta}_{\text{ridge}} = \arg\min_{\boldsymbol\beta}\ \lVert \mathbf{y} - X\boldsymbol\beta \rVert^2 + \lambda \sum_{j}\beta_j^2
ridge has a formula \hat{\boldsymbol\beta}_{\text{ridge}} = (X^\top X + \lambda I)^{-1} X^\top \mathbf{y}; adding \lambda I lifts every eigenvalue by \lambda, so it always inverts
lasso: squared miss + \lambda × sum of absolute values \hat{\boldsymbol\beta}_{\text{lasso}} = \arg\min_{\boldsymbol\beta}\ \lVert \mathbf{y} - X\boldsymbol\beta \rVert^2 + \lambda \sum_{j}\lvert\beta_j\rvert (no formula: \lvert\beta\rvert has a kink at 0)
elastic net: \alpha mixes the two penalty \lambda\big[\alpha\sum_j \lvert\beta_j\rvert + (1-\alpha)\sum_j \beta_j^2\big]