Week 10: Regularization

PS 818 - Data Analysis with Statistical Models

Anton Strezhnev

University of Wisconsin-Madison

November 9, 2026

Regularization

\[ \DeclareMathOperator*{\argmin}{arg\,min} \DeclareMathOperator*{\argmax}{arg\,max} \]

Previously

  • Mixture models
    • A discrete latent variable: cluster membership
    • MLE/MAP estimation via Expectation-Maximization
  • Item response theory
    • A continuous latent trait that drives discrete responses
    • Logit/probit regression with unobserved regressors
    • Identification via priors (or constraints) that fix the location and scale of the latent space

This week

  • Flexible regression
    • Estimating \(E[Y_i | X_i]\) when \(X_i\) is continuous and we don’t want to assume a restrictive specification
    • Basis expansions: polynomials, step functions, splines
  • Regularization
    • The bias-variance trade-off
    • Ridge (\(L_2\)) and lasso (\(L_1\)) penalties
    • Ridge on a spline’s slope changes: a penalty on curvature
    • Choosing the penalty via cross-validation
    • Connection to Bayes - penalties are priors
  • Running example: Age and the 2020 presidential vote in the 2023 CES

Going forward

  • Midterm 2 - In class, Wednesday, November 11
  • Week 11 - Flexible Regression: Trees and Forests
  • Week 12 - Flexible Regression: Kernels and Gaussian Processes
  • Week 13 - Causal Inference when adjusting with flexible regression models
  • Week 14 - Working with “Big” Datasets

Flexible regression

  • We’ve spent a lot of time estimating the conditional expectation function (CEF) \(E[Y|X] = f(X)\).

    • But so far we’ve emphasized methods where we know the true functional form (e.g. a linear CEF)

      \[E[Y|X] = X^{\prime}\beta\]

    • Linearity is trivially satisfied when \(X\) is discrete (a dummy for every value), but a potentially problematic assumption when \(X\) is continuous.

  • We want to keep the convenience of a model that is linear in the parameters, but transform \(X\) to capture non-linear relationships between \(Y\) and \(X\).

  • Define the linear basis expansion for a set of \(M\) basis functions \(h_m(X)\)

    \[f(X) = \sum_{m=1}^M \beta_m h_m(X)\]

    • Once we pick the \(h_m()\), this is “just” a regression of \(Y\) on \(h_1(X), h_2(X), \dotsc, h_M(X)\).

Example: Age and the 2020 vote

  • How does vote choice vary with age?
    • Age “effects”: people become more conservative as they age
    • Cohort “effects”: the political events that occur when a cohort comes of age have persistent effects (Boomer, Gen-X, Millennial, Zoomer) (Ghitza, Gelman, and Auerbach 2023)
    • Functional form between age and political attitudes not clear ex-ante!
  • Data: the 2023 Cooperative Election Study (Schaffner et al. 2024)
    • \(Y_i\): recalled 2020 presidential vote (1 = Trump, 0 = Biden) among respondents who voted
    • \(X_i\): age in years (2023 minus birth year)
    • We use the CES survey weights throughout, so the fits are weighted least squares. To keep the notation simple, the math is written unweighted.

Example: Age and the 2020 vote

ces_raw <- read_dta("../week8/data/CCES23_Common_OUTPUT.dta.gz") # the file from Week 8
count(ces_raw, presvote20post) # value labels are in the Stata file; see the questionnaire
# A tibble: 8 × 2
  presvote20post                      n
  <dbl+lbl>                       <int>
1  1 [Joe Biden]                   9468
2  2 [Donald Trump]                8229
3  3 [Jo Jorgensen]                 176
4  4 [Howie Hawkins]                 75
5  5 [Other]                        142
6  6 [Did not vote for President]  6398
7  8 [skipped]                       11
8 NA                                  1
ces <- ces_raw %>%
  mutate(age = 2023 - birthyr) %>%
  filter(presvote20post %in% 1:2, age <= 90) %>% # Biden or Trump voters; only a handful are over 90
  mutate(trump = as.numeric(presvote20post == 2),
         w = commonweight / mean(commonweight)) # survey weights, rescaled to average 1
tibble(n = nrow(ces), unweighted = mean(ces$trump), weighted = weighted.mean(ces$trump, ces$w))
# A tibble: 1 × 3
      n unweighted weighted
  <int>      <dbl>    <dbl>
1 17675      0.465    0.470

Example: Age and the 2020 vote

  • Points are the (weighted) share voting Trump at each age, sized by the number of respondents. The line is a (weighted) linear fit.

Polynomial basis

  • A common set of basis functions to choose is the global polynomial basis

    • You’ve probably already done this when you’ve included squared terms in your regressions!
  • For example, for a univariate \(X\), the basis for a global cubic polynomial is:

    \[h_1(X) = 1, \quad h_2(X) = X, \quad h_3(X) = X^2, \quad h_4(X) = X^3\]

  • A \(K\)th order polynomial requires \(K+1\) parameters

  • However, there are some drawbacks to using a global polynomial - each observation influences the entire curve.

    • High-order polynomials are notoriously unstable at the edges of the data.

Polynomial basis

cubic_fit <- lm(trump ~ poly(age, 3), data = ces, weights = w) # poly() uses an orthogonal version of the same basis
poly15_fit <- lm(trump ~ poly(age, 15), data = ces, weights = w)

Step functions

  • Instead of a single global polynomial, fit local averages within regions of \(X\) defined by cutpoints \(\xi_1 < \xi_2 < \dotsc < \xi_M\):

    \[h_1(X) = I(X < \xi_1), \quad h_2(X) = I(\xi_1 \le X < \xi_2), \quad \dotsc, \quad h_{M+1}(X) = I(\xi_M \le X)\]

  • Natural cutpoints here: generations: Gen Z (\(\le 26\) in 2023), Millennials (27-42), Gen X (43-58), Boomers (59-77), Silent (78+)

gen_knots <- c(26, 42, 58, 77) # the last age in each generation
step_fit <- lm(trump ~ cut(age, c(-Inf, gen_knots, Inf)), data = ces, weights = w)

Step functions

Piecewise linear functions

  • Step functions are discontinuous: a 42-year-old and a 43-year-old get very different predictions.

  • Instead, fit a line within each region, and force the lines to connect at the cutpoints (called knots):

    \[f(X) = \beta_0 + \beta_1 X + \sum_{k=1}^{K} \beta_{k+1} (X - \xi_k)_+\]

    where \((\cdot)_+\) denotes \(\max(\cdot, 0)\).

  • This is a linear spline in the truncated power basis. Each term \((X - \xi_k)_+\) is zero to the left of knot \(\xi_k\) and a line with slope 1 to its right.

  • Interpretation:

    • \(\beta_1\) is the slope to the left of the first knot.
    • \(\beta_{k+1}\) is the change in the slope at knot \(\xi_k\).
    • The slope between \(\xi_k\) and \(\xi_{k+1}\) is \(\beta_1 + \beta_2 + \dotsc + \beta_{k+1}\).

Linear splines

tp_basis <- function(x, knots) { # truncated power basis: one column (x - knot)_+ per knot
  outer(x, knots, function(x, k) pmax(x - k, 0)) %>% `colnames<-`(paste0("(age-", knots, ")+"))
}
gen_spline <- lm(trump ~ age + tp_basis(age, gen_knots), data = ces, weights = w)
coef(gen_spline) %>% setNames(c("(Intercept)", "age", colnames(tp_basis(0, gen_knots))))
(Intercept)         age   (age-26)+   (age-42)+   (age-58)+   (age-77)+ 
    0.09792     0.00854    -0.00287     0.00139    -0.00467     0.01573 

Higher-order splines

  • A degree-\(d\) spline with knots \(\xi_1, \dotsc, \xi_K\) is a piecewise polynomial that…

    • …is a polynomial of degree \(d\) between each pair of knots
    • …has continuous derivatives of order \(0, 1, \dotsc, d-1\) at each knot
  • If we also forced the \(d\)th derivative to be continuous, we’d recover a global polynomial.

  • The most common choice is the cubic spline (\(d = 3\)): continuous first and second derivatives, so the knots are hard to see.

    • Truncated power basis: \(1, X, X^2, X^3, (X - \xi_1)^3_+, \dotsc, (X - \xi_K)^3_+\), so \(K + 4\) parameters.
  • Natural splines add the constraint that the function is linear beyond the boundary knots, which limits edge behavior (where there’s no data).

  • When the degree and the knots are fixed in advance, these are called regression splines

    • Given a particular basis, estimation is done via OLS (or MLE for GLMs w/ other link functions)

B-splines

  • The truncated power basis is easy to interpret but numerically unstable.

  • The B-spline basis spans the same set of functions, but each basis function is non-zero only over a few neighboring knots.

    • Defined recursively: higher-order B-splines are weighted averages of neighboring lower-order ones (see Hastie, Tibshirani, and Friedman (2009), Chapter 5 appendix).
    • Same fitted values as the truncated power basis with the same knots, just different coefficients.
  • In R, bs() (B-splines) and ns() (natural splines) in the splines package build the basis for you.

    • You can include them in a formula like any other transformation of a regressor.

B-splines

cubic_spline <- lm(trump ~ bs(age, knots = gen_knots), data = ces, weights = w) # degree = 3 by default
natural_spline <- lm(trump ~ ns(age, knots = gen_knots), data = ces, weights = w)

How many knots? Where?

  • How many knots should we pick?
    • Bias-variance trade-off
    • Many knots \(\leadsto\) more parameters \(\leadsto\) more variance
    • Fewer knots \(\leadsto\) function can’t “bend” as much if it needs to \(\leadsto\) more bias
  • One extreme: a knot at every age, \(\xi = 22, 23, \dotsc, 89\) (\(K = 68\) knots, 70 parameters).
    • Equivalent to regressing on a dummy for each age.

How many knots? Where?

knots <- 22:89
spline_basis <- function(age) cbind(1, age, tp_basis(age, knots)) # intercept, slope, 68 slope changes
X_age <- spline_basis(ces$age)
X_grid <- spline_basis(age_grid$age)
ols_beta <- lm.wfit(X_age, ces$trump, ces$w)$coefficients # weighted least squares
max(abs(X_grid %*% ols_beta - age_means$trump)) # the fit is just the age-by-age averages
[1] 3e-15

Bias and variance

  • The knot-at-every-age spline is unbiased for the CEF at each age: it doesn’t impose any shape at all.

    • But it’s noisy
  • Recall that the mean squared error of an estimator \(\hat{\theta}\) of a parameter \(\theta\) decomposes into the variance and the squared bias

    \[\underbrace{E\big[(\hat{\theta} - \theta)^2\big]}_{\text{MSE}} = \underbrace{E\big[\hat{\theta}^2\big]- E\big[\hat{\theta}\big]^2}_{\text{Variance}} + \underbrace{\big(E[\hat{\theta}] - \theta\big)^2}_{\text{Squared Bias}}\]

  • We often like unbiasedness because it lets us characterize the remaining error as variance

    • But if we just want our estimate to be close to the truth, we might accept some bias in exchange for a large reduction in uncertainty.

Bias and variance

  • We’ve already accepted bias for lower variance before:
    • An informative prior pulls estimates towards our existing beliefs.
    • Sharper prior \(\leadsto\) more bias, lower variance.
  • What sort of bias do we want here?
    • Bias the slope changes \(\beta_2, \dotsc, \beta_{K+1}\) towards zero
    • All else equal, prefer a curve that doesn’t bend much.

Penalized regression

  • OLS finds the \(\beta\) that minimizes the residual sum of squares

    \[\text{RSS}(\beta) = \sum_{i=1}^N (Y_i - X_i^{\prime}\beta)^2\]

  • GLMs more generally minimize the negative log-likelihood.

  • Penalized regression adds a term to the objective function that penalizes “complex” values of \(\beta\)

    \[\hat{\beta}_\lambda = \argmin_\beta \text{RSS}(\beta) + \lambda \cdot \text{Pen}(\beta)\]

    where \(\lambda \ge 0\) is a tuning parameter chosen by the researcher.

    • \(\lambda = 0\): OLS.
    • \(\lambda \to \infty\): whatever minimizes the penalty.

Penalties

  • Different penalties encode different notions of “complexity”. We’ll use the \(L_p\) norms \(||\beta||_p = \big(\sum_k |\beta_k|^p\big)^{1/p}\):
    • \(L_2\) (Euclidean) norm, squared: \(||\beta||_2^2 = \sum_k \beta_k^2\) - ridge regression (Hoerl and Kennard 1970)
    • \(L_1\) norm: \(||\beta||_1 = \sum_k |\beta_k|\) - the lasso (Tibshirani 1996)
    • \(L_0\) “norm”: the number of non-zero \(\beta_k\) (best subset selection).
  • We’ll typically standardize the covariates (mean 0, variance 1) first, so that the penalty doesn’t depend on their units.
    • And we don’t penalize the intercept - since the intercept is essentially just de-meaning the outcome.

Ridge regression on the knots

  • For the knot-at-every-age spline, we’ll penalize the squared slope changes:

    \[\min_{\beta} \sum_{i=1}^N \bigg(Y_i - \beta_0 - \beta_1 X_i - \sum_{k=1}^{K} \beta_{k+1} (X_i - \xi_k)_+\bigg)^2 + \lambda \sum_{j=2}^{K+1} \beta_j^2\]

  • What are the two extremes:

    • \(\lambda = 0\): the age-by-age averages.
    • \(\lambda \to \infty\): the least squares line
  • In matrix form, with \(D = \text{diag}(0, 0, 1, \dotsc, 1)\):

    \[\hat{\beta}_\lambda = \argmin_\beta (Y - X\beta)^{\prime}(Y - X\beta) + \lambda \beta^{\prime} D \beta\]

  • Take the derivative and set it to zero: \(-2X^{\prime}(Y - X\beta) + 2\lambda D\beta = 0\), so

    \[\hat{\beta}_\lambda = (X^{\prime}X + \lambda D)^{-1}X^{\prime}Y\]

    • Least squares with \(\lambda D\) added to \(X^{\prime}X\)

Ridge regression on the knots

  • Straightforward implementation
D <- diag(c(0, 0, rep(1, length(knots))))
ridge_beta <- function(lambda, X = X_age, y = ces$trump, w = ces$w) {
  solve(crossprod(X, w * X) + lambda * D, crossprod(X, w * y))
}

What is the ridge penalty doing?

  • \(\beta_{k+1}\) is the change in slope at knot \(\xi_k\). With knots \(h\) apart (here, \(h = 1\) year), that’s a second difference:

    \[\beta_{k+1} = \frac{f(\xi_{k+1}) - f(\xi_k)}{h} - \frac{f(\xi_k) - f(\xi_{k-1})}{h} = \frac{f(\xi_{k+1}) - 2f(\xi_k) + f(\xi_{k-1})}{h}\]

  • The ridge penalty on the slope changes is a penalty on how much \(f\) bends.

    • A straight line has no curvature, so it’s never penalized.
    • “Wiggly” functions bend a lot, so they’re penalized a lot.

Smoothing splines

  • What happens as the knots get closer together (\(h \to 0\))?

    \[\frac{\beta_{k+1}}{h} = \frac{f(\xi_{k+1}) - 2f(\xi_k) + f(\xi_{k-1})}{h^2} \approx f''(\xi_k)\]

  • So the ridge penalty is a Riemann sum for the integrated squared second derivative:

    \[\lambda \sum_k \beta_{k+1}^2 = \lambda h \sum_k \bigg(\frac{\beta_{k+1}}{h}\bigg)^2 h \approx \lambda h \int f''(x)^2 \, dx\]

  • In the limit we get the smoothing spline, which searches over all functions \(f\):

    \[\min_f \sum_{i=1}^N \big(Y_i - f(X_i)\big)^2 + \lambda \int f''(x)^2 \, dx\]

  • The solution is a natural cubic spline with a knot at every unique \(X_i\) (Schoenberg 1964; Green and Silverman 1994).

  • In R: smooth.spline(), or s() in the gam package.

Effective number of parameters

  • Penalized fits are linear smoothers - that is, they can be expressed as a linear function of \(Y\)

    \[\hat{Y} = X(X^{\prime}X + \lambda D)^{-1}X^{\prime}Y = S_\lambda Y\]

  • For least squares (\(\lambda = 0\)), \(S_0\) is the projection (“hat”) matrix.

    • Its trace (sum of the diagonals) is equal to the number of parameters!
  • Define the effective number of parameters of a penalized fit as \(p_\lambda = \text{tr}(S_\lambda)\).

Effective number of parameters

eff_params <- function(lambda, X = X_age, w = ces$w) {
  XtWX <- crossprod(X, w * X)
  sum(diag(solve(XtWX + lambda * D, XtWX))) # tr(S) = tr((X'X + lambda D)^-1 X'X), with weights
}
tibble(lambda = c(0, 1e3, 1e5, 1e7, 1e9)) %>% mutate(eff_params = map_dbl(lambda, eff_params)) %>%
  mutate(lambda = format(lambda, scientific = F, big.mark = ",")) %>% kable()
lambda eff_params
0 70.00
1,000 18.80
100,000 6.26
10,000,000 2.59
1,000,000,000 2.01
  • Penalizing the 68 slope changes takes us continuously from 70 parameters (the age-by-age averages) to the 2 of a straight line.

Smoothing splines in practice: gam()

  • The gam package (Hastie and Tibshirani 1990) fits smoothing splines inside a regression formula: s(age, df = 4).

    • Instead of \(\lambda\), you choose the smooth’s effective number of parameters (gam() calls it df; not counting the intercept), and gam() finds the \(\lambda\) that gives it.
    • df is the tuning parameter: small df is close to a line, large df is close to the age-by-age averages.
  • The weights argument works like it does in lm().

  • You can add more smooth terms (s(age) + s(income)) and ordinary covariates: a generalized additive model.

Smoothing splines in practice: gam()

age_gam <- gam(trump ~ s(age, df = 4), data = ces, weights = w) # df = 4 is the default
fit_gam <- function(df, data = ces) { # to loop over df, write it into the formula itself
  gam(as.formula(paste("trump ~ s(age, df =", df, ")")), data = data, weights = w)
}

Bayesian interpretation

  • Penalized regression has an interpretation as Bayesian regression. Consider our normal model:

    \[Y_i |X_i, \beta \sim \text{Normal}(X_i^{\prime}\beta, \sigma^2)\]

  • And put a normal prior on the penalized coefficients: \(\beta_j \sim \text{Normal}(0, \tau^2)\) for \(j = 2, \dotsc, K+1\), flat on \(\beta_0, \beta_1\).

  • The log-posterior is, up to constants

    \[\log p(\beta | \mathbf{X}, Y) = - \frac{1}{2\sigma^2}\sum_{i=1}^N (Y_i - X_i^{\prime}\beta)^2 - \frac{1}{2\tau^2} \sum_{j=2}^{K+1} \beta_j^2\]

Bayesian interpretation

  • Multiplying by \(-2\sigma^2\)

    \[-2\sigma^2 \log p(\beta | \mathbf{X}, Y) = \sum_{i=1}^N (Y_i - X_i^{\prime}\beta)^2 + \frac{\sigma^2}{\tau^2} \sum_{j=2}^{K+1} \beta_j^2\]

  • With \(\lambda = \sigma^2/\tau^2\), this is the ridge objective. The ridge estimate is the posterior mode

    • Big \(\lambda\) \(\leftrightarrow\) a tight prior that slope changes are small.

Choosing \(\lambda\)

  • We’ll choose \(\lambda\) to optimize a measure of fit.
    • In-sample fit always chooses \(\lambda = 0\).
    • We need an estimate of out-of-sample error: how well does the fit predict observations it wasn’t estimated on?
  • \(K\)-fold cross-validation:
    1. Randomly split the observations into \(K\) “folds” (commonly \(K = 5\) or \(10\)).
    2. For each fold \(k\): fit the model on the other \(K - 1\) folds, and compute the squared error of the predictions in fold \(k\).
    3. Average the squared errors across all observations. Repeat for every \(\lambda\) and pick the smallest.
    • Every observation is used for fitting (\(K - 1\) times) and for evaluation (once).

Choosing \(\lambda\)

  • Leave-one-out CV (\(K = N\))
    • For linear smoothers, there’s a straightforward expression using the “hat matrix” and the residuals (like in linear regression!)
    \[\text{CV}_{\text{LOO}}(\lambda) = \frac{1}{N}\sum_{i=1}^N \bigg(\frac{Y_i - \hat{Y}_i}{1 - [S_\lambda]_{ii}}\bigg)^2\]

Cross-validation by hand

set.seed(53703)
folds <- sample(rep(1:10, length.out = nrow(ces)))
wmse <- function(err, w = ces$w) sum(w * err^2) / sum(w) # weighted mean squared error
cv_ridge <- function(lambda) {
  err <- numeric(nrow(ces))
  for (k in 1:10) {
    in_k <- folds == k
    beta_k <- ridge_beta(lambda, X = X_age[!in_k, ], y = ces$trump[!in_k], w = ces$w[!in_k])
    err[in_k] <- ces$trump[in_k] - X_age[in_k, ] %*% beta_k
  }
  wmse(err)
}
lambda_grid <- 10^seq(0, 9, by = .25)
cv_error <- map_dbl(lambda_grid, cv_ridge)
lambda_cv <- lambda_grid[which.min(cv_error)]
lambda_cv
[1] 1e+05
eff_params(lambda_cv)
[1] 6.26

Cross-validation by hand

  • \(\lambda = 0\) is the age-by-age averages and \(\lambda \to \infty\) is the straight line. Cross-validation picks something in between, with 6.3 effective parameters.

Penalized regression with glmnet

  • The standard R package for penalized regression is glmnet (Friedman, Hastie, and Tibshirani 2010), which minimizes

    \[\frac{1}{2N}\sum_{i=1}^N (Y_i - \beta_0 - X_i^{\prime}\beta)^2 + \lambda\bigg[\frac{1 - \alpha}{2}||\beta||_2^2 + \alpha ||\beta||_1\bigg]\]

    • alpha = 0 is ridge, alpha = 1 is the lasso, and values in between are the elastic net.
    • Works for other GLM families (family = "binomial", "poisson", …) by swapping the RSS for the negative log-likelihood.

Penalized regression with glmnet

  • Some important defaults:
    • standardize = TRUE: covariates are rescaled to have variance 1 before penalizing, so that the penalty doesn’t depend on their units.
    • The intercept is never penalized. Other coefficients can be left unpenalized with penalty.factor = 0.
    • Fits the whole path of solutions for a decreasing sequence of \(\lambda\) values. cv.glmnet() picks \(\lambda\) by \(K\)-fold cross-validation.
    • Survey weights go in weights =.

Penalized regression with glmnet

  • Ridge on the knots
Z_age <- X_age[, -1] # glmnet adds its own intercept
pen <- c(0, rep(1, length(knots))) # 0 = leave age unpenalized
ridge_cv <- cv.glmnet(Z_age, ces$trump, weights = ces$w, alpha = 0, penalty.factor = pen,
                      standardize = FALSE, foldid = folds)
ridge_cv

Call:  cv.glmnet(x = Z_age, y = ces$trump, weights = ces$w, foldid = folds,      alpha = 0, penalty.factor = pen, standardize = FALSE) 

Measure: Mean-Squared Error 

    Lambda Index Measure      SE Nonzero
min    3.4    26    0.24 0.00115      69
1se   35.2     1    0.24 0.00111      69
  • lambda.min minimizes the CV error. lambda.1se is the largest \(\lambda\) whose CV error is within one standard error of the minimum (a choice that is sparser).

Visualizing the penalty

  • Penalized regression can also be written as a constrained optimization problem: find the \(\beta\) that minimizes

    \[\text{RSS} = \sum_{i=1}^N (Y_i - X_i^{\prime}\beta)^2 \quad \text{subject to} \quad \sum_{k=1}^K \beta_k^2 \le s\]

  • Each \(\lambda\) in the penalized form corresponds to some budget \(s\) in the constrained form.

    • We prefer the penalized form for computation, but the constrained form shows how the penalty acts on the solution.

Visualizing the penalty

Ridge constraint region

Source: Hastie, Tibshirani, and Friedman (2009), Figure 3.11

The lasso

  • Ridge regression shrinks coefficients towards zero, but it doesn’t set any of them to exactly zero.
    • In other words, it does not do model selection.
  • We might like a penalty that produces sparse solutions, ones where many coefficients are exactly zero.
    • The \(L_1\) penalty accomplishes this!
    • The least absolute shrinkage and selection operator, or lasso (Tibshirani 1996), replaces the squared coefficients with their absolute values
    \[\sum_{i=1}^N (Y_i - X_i^{\prime}\beta)^2 + \lambda\sum_{k=1}^K |\beta_k|\]

Visualizing the lasso

Lasso constraint region

Source: Hastie, Tibshirani, and Friedman (2009), Figure 3.11

Bayesian lasso

  • The lasso is also the posterior mode under a particular prior on \(\beta\).

    • Instead of the normal, the prior is the Laplace (double-exponential) distribution with location \(0\) and scale \(b\)

    \[p(\beta_k) = \frac{1}{2b} \exp\bigg\{ -\frac{|\beta_k|}{b}\bigg\}\]

    • \(-\log p(\beta_k) = |\beta_k|/b + \text{const}\): the \(L_1\) penalty.
  • Compared to the normal, the Laplace has a sharper peak at zero and heavier tails.

    • Strong pull towards exactly zero for small coefficients, less shrinkage of large ones.
  • Careful: the posterior mode is sparse, but the posterior mean under a Laplace prior is not (Park and Casella 2008).

    • The sparsity of the lasso is a feature of the optimization.

The lasso on the knots

  • What does the lasso do with our 68 slope changes?
    • Ridge shrinks all the slope changes. The fit bends a little bit everywhere.
    • The lasso sets most of them to exactly zero. The fit is piecewise linear with a few kinks.
  • Penalizing the \(L_1\) norm of a function’s slope changes is called \(\ell_1\) trend filtering (Kim et al. 2009; Tibshirani 2014)
    • Knots are chosen adaptively.

The lasso on the knots

lasso_cv <- cv.glmnet(Z_age, ces$trump, weights = ces$w, alpha = 1, penalty.factor = pen,
                      standardize = FALSE, foldid = folds)
lasso_beta <- coef(lasso_cv, s = "lambda.min")
knots[lasso_beta[-(1:2)] != 0] # the knots with non-zero slope changes
 [1] 34 35 36 37 53 54 55 56 59 66 68 69 75 77 78

Comparing the fits

  • 10-fold cross-validation error for every fit, using the same folds
cv_fit <- function(fit_fun) { # fit_fun: data -> fitted model with a predict() method
  err <- numeric(nrow(ces))
  for (k in 1:10) {
    in_k <- folds == k
    err[in_k] <- ces$trump[in_k] - predict(fit_fun(ces[!in_k, ]), ces[in_k, ])
  }
  wmse(err)
}
cv_table <- tibble(
  Method = c("Intercept only", "Linear", "Cubic polynomial", "15th order polynomial",
             "Linear spline, generational knots", "Cubic spline, generational knots",
             "Linear spline, knot at every age", "Ridge on the knots (CV)",
             "Lasso on the knots (CV)", "Smoothing spline, gam() (df by CV)"),
  `CV error` = c(cv_fit(function(d) lm(trump ~ 1, data = d, weights = w)),
                 cv_fit(function(d) lm(trump ~ age, data = d, weights = w)),
                 cv_fit(function(d) lm(trump ~ poly(age, 3), data = d, weights = w)),
                 cv_fit(function(d) lm(trump ~ poly(age, 15), data = d, weights = w)),
                 cv_fit(function(d) lm(trump ~ age + tp_basis(age, gen_knots), data = d, weights = w)),
                 cv_fit(function(d) lm(trump ~ bs(age, knots = gen_knots), data = d, weights = w)),
                 cv_fit(function(d) lm(trump ~ age + tp_basis(age, knots), data = d, weights = w)),
                 min(cv_error), min(lasso_cv$cvm),
                 min(sapply(2:15, function(k) cv_fit(function(d) fit_gam(k, d))))))

Comparing the fits

cv_table %>% mutate(`vs. best (x 10,000)` = sprintf("%.1f", 1e4 * (`CV error` - min(`CV error`))),
                    `CV error` = sprintf("%.5f", `CV error`)) %>% kable(align = "lrr")
Method CV error vs. best (x 10,000)
Intercept only 0.24919 90.9
Linear 0.24026 1.6
Cubic polynomial 0.24028 1.8
15th order polynomial 0.24056 4.7
Linear spline, generational knots 0.24018 0.8
Cubic spline, generational knots 0.24028 1.9
Linear spline, knot at every age 0.24139 12.9
Ridge on the knots (CV) 0.24010 0.0
Lasso on the knots (CV) 0.24012 0.2
Smoothing spline, gam() (df by CV) 0.24010 0.0

Many predictors

  • Regularization matters most when the model has many parameters relative to the data size.
    • Real models have lots of covariates, interactions, and flexible terms for each of them.
  • Let’s predict the 2020 vote with everything else in the CES that isn’t just party ID:
    • Main effects for gender, education, race, Hispanic identity, state, region, urbanicity, employment, student status, marital status, children, home ownership, income, religion, religiosity (three measures), born-again status, military service, health insurance, sexual orientation, immigration background, internet access, media use, recent retirement or childbirth
    • Two-way interactions among 12 core demographics
    • Age as a linear regression spline (a knot every two years), with a separate age curve for each category of gender, education, race, urbanicity, religiosity and region

Many predictors

covs <- c("gender4", "educ", "race", "hispanic", "inputstate", "region", "urbancity", "employ", "student", "marstat",
          "child18", "ownhome", "faminc_new", "religpew", "pew_bornagain", "pew_religimp", "pew_churatd", "pew_prayer",
          "milstat_1", "milstat_3", "healthins_2", "sexuality", "immstat", "internethome",
          "CC23_300_1", "CC23_300_2", "CC23_300_3", "CC23_300_4", "CC23_305_4", "CC23_305_6")
core <- c("gender4", "educ", "race", "urbancity", "marstat", "pew_religimp", "region", "ownhome", "child18",
          "faminc_new", "religpew", "employ")
by_age <- c("gender4", "educ", "race", "urbancity", "pew_religimp", "region") # each gets its own age curve
ces_covs <- ces %>% select(all_of(covs)) %>%
  mutate(across(everything(), ~ fct_na_value_to_level(fct_drop(as_factor(.x)), "missing")))
X_main_int <- sparse.model.matrix(reformulate(c(".", paste0("(", paste(core, collapse = " + "), ")^2"))), ces_covs)[, -1]
age_basis <- cbind(age = ces$age, tp_basis(ces$age, seq(22, 88, by = 2)))
D_by <- sparse.model.matrix(reformulate(by_age), ces_covs)[, -1]
X_age_by <- do.call(cbind, lapply(colnames(D_by), function(v) {
  Matrix(age_basis * D_by[, v], sparse = TRUE, dimnames = list(NULL, paste0(colnames(age_basis), ":", v)))
}))
X_big <- cbind(Matrix(age_basis, sparse = TRUE), X_main_int, X_age_by)
X_big <- X_big[, colSums(X_big != 0) >= 50] # drop columns that are non-zero for fewer than 50 respondents
dim(X_big)
[1] 17675  1898

Many predictors: least squares

  • 1,898 predictors. Weighted least squares, with the same 10 folds
X_dense <- cbind(1, as.matrix(X_big))
err_ols <- err_null <- numeric(nrow(ces))
for (k in 1:10) {
  in_k <- folds == k
  b <- lm.wfit(X_dense[!in_k, ], ces$trump[!in_k], ces$w[!in_k])$coefficients
  err_ols[in_k] <- ces$trump[in_k] - X_dense[in_k, ] %*% replace_na(b, 0) # NA = collinear column
  err_null[in_k] <- ces$trump[in_k] - weighted.mean(ces$trump[!in_k], ces$w[!in_k])
}
rm(X_dense)
c(intercept_only = wmse(err_null), least_squares = wmse(err_ols))
intercept_only  least_squares 
         0.249          0.192 

Many predictors: ridge and lasso

big_ridge <- cv.glmnet(X_big, ces$trump, weights = ces$w, alpha = 0, foldid = folds)
big_lasso <- cv.glmnet(X_big, ces$trump, weights = ces$w, alpha = 1, foldid = folds)
map_dfr(list(Ridge = big_ridge, Lasso = big_lasso), .id = "Method", function(fit) {
  tibble(lambda = c("lambda.min", "lambda.1se"),
         `CV error` = fit$cvm[match(c(fit$lambda.min, fit$lambda.1se), fit$lambda)],
         `Non-zero coefficients` = fit$nzero[match(c(fit$lambda.min, fit$lambda.1se), fit$lambda)])
}) %>% mutate(`CV error` = sprintf("%.4f", `CV error`)) %>% kable(align = "llrr")
Method lambda CV error Non-zero coefficients
Ridge lambda.min 0.1692 1898
Ridge lambda.1se 0.1708 1898
Lasso lambda.min 0.1667 386
Lasso lambda.1se 0.1681 213
  • Least squares: 0.192. Intercept only: 0.249.

Many predictors: the lasso path

  • Coefficients enter as \(\lambda\) falls. Right: the CV error (with \(\pm\) 1 SE) and the number of non-zero coefficients along the top.

Many predictors: what gets selected?

lasso_coefs <- coef(big_lasso, s = "lambda.1se")[-1, 1]
selected <- lasso_coefs[lasso_coefs != 0]
tibble(term = names(selected), coef = selected) %>% arrange(-abs(coef)) %>% head(10) %>% kable(digits = 3)
term coef
religpewMuslim -0.226
sexualityGay man -0.190
raceBlack:pew_religimpNot at all important 0.180
pew_religimpNot at all important -0.148
urbancityRural area 0.124
religpewJewish:pew_religimpSomewhat important -0.112
religpewAtheist -0.111
pew_bornagainNo -0.110
educHigh school graduate:raceAsian -0.108
sexualityBisexual -0.102

Lasso as variable selection

  • Variable selection is a common problem in statistics
    • We assume a world where among our covariates \(X\), some “matter” but most don’t.
    • Ex-ante, we have no idea which covariates are the relevant ones!
  • Classical approaches
    • Forward selection - Start with an empty model and add variables one-by-one.
    • Backward selection - Start with a full model and remove the least useful variables one-by-one.
  • The lasso can be thought of as an alternative to these techniques
    • Advantages in computational time/feasibility as well as potential predictive benefits from shrinkage.
    • But: which variables get selected can be unstable, especially among correlated predictors
    • And the lasso (by default) selects columns, not variables. How a variable’s influence is split across main effects, interactions and basis functions depends on how we built the design matrix.

Post-lasso OLS

  • What if we took the columns the lasso selected and just ran (weighted) least squares?
X_sel <- cbind(1, as.matrix(X_big[, names(selected)]))
post_lasso <- lm.wfit(X_sel, ces$trump, ces$w)$coefficients
tibble(term = names(selected), lasso = selected, post_lasso = post_lasso[-1]) %>%
  arrange(-abs(lasso)) %>% head(6) %>% kable(digits = 3)
term lasso post_lasso
religpewMuslim -0.226 -0.288
sexualityGay man -0.190 -0.232
raceBlack:pew_religimpNot at all important 0.180 0.281
pew_religimpNot at all important -0.148 -0.145
urbancityRural area 0.124 0.141
religpewJewish:pew_religimpSomewhat important -0.112 -0.133
  • 91% of the 213 coefficients are larger in magnitude after refitting.
    • Why? The lasso shrinks the coefficients it keeps towards zero.
    • Refitting also shifts weight between the selected columns.

Summary

  • Basis expansions let us fit flexible CEFs with linear regression
    • Splines: piecewise polynomials joined smoothly at knots.
    • More knots \(\leadsto\) less bias, more variance.
  • Penalized regression: trading off bias for lower variance
    • Ridge (\(L_2\)): shrinks all coefficients. Lasso (\(L_1\)): shrinks coefficients and sets some to \(0\).
    • Penalties are priors: normal for ridge, Laplace for the lasso.
  • Penalized splines: lots of knots + a penalty
    • A ridge penalty on a spline’s slope changes is a penalty on its curvature.
  • Choose \(\lambda\) out-of-sample

Next week

  • Midterm 2 - In class, Wednesday, November 11

  • Flexible regression: trees and forests

    • Regression trees
    • Aggregation via sums of trees + regularization via BART
    • Bagging, boosting, random forests
  • Readings: Chapter 8 of James et al. (2013); Chapters 9-10 and 15 of Hastie, Tibshirani, and Friedman (2009)

References

Friedman, Jerome, Trevor Hastie, and Robert Tibshirani. 2010. “Regularization Paths for Generalized Linear Models via Coordinate Descent.” Journal of Statistical Software 33 (1): 1–22. https://doi.org/10.18637/jss.v033.i01.
Ghitza, Yair, Andrew Gelman, and Jonathan Auerbach. 2023. “The Great Society, Reagan’s Revolution, and Generations of Presidential Voting.” American Journal of Political Science 67 (3): 520–37. https://doi.org/10.1111/ajps.12713.
Green, P. J., and B. W. Silverman. 1994. Nonparametric Regression and Generalized Linear Models: A Roughness Penalty Approach. Monographs on Statistics and Applied Probability 58. London: Chapman and Hall.
Hastie, Trevor J., and Robert J. Tibshirani. 1990. Generalized Additive Models. Monographs on Statistics and Applied Probability 43. London: Chapman and Hall.
Hastie, Trevor, Robert Tibshirani, and Jerome Friedman. 2009. The Elements of Statistical Learning: Data Mining, Inference, and Prediction. 2nd ed. New York: Springer. https://doi.org/10.1007/978-0-387-84858-7.
Hoerl, Arthur E., and Robert W. Kennard. 1970. “Ridge Regression: Biased Estimation for Nonorthogonal Problems.” Technometrics 12 (1): 55–67. https://doi.org/10.1080/00401706.1970.10488634.
James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani. 2013. An Introduction to Statistical Learning. New York: Springer. https://doi.org/10.1007/978-1-4614-7138-7.
Kim, Seung-Jean, Kwangmoo Koh, Stephen Boyd, and Dimitry Gorinevsky. 2009. “\(\ell_1\) Trend Filtering.” SIAM Review 51 (2): 339–60. https://doi.org/10.1137/070690274.
Park, Trevor, and George Casella. 2008. “The Bayesian Lasso.” Journal of the American Statistical Association 103 (482): 681–86. https://doi.org/10.1198/016214508000000337.
Schaffner, Brian, Stephen Ansolabehere, Jeremy Pope, and Marissa Shih. 2024. “CES Common Content, 2023.” Harvard Dataverse. https://doi.org/10.7910/DVN/JQJTCC.
Schoenberg, I. J. 1964. “Spline Functions and the Problem of Graduation.” Proceedings of the National Academy of Sciences 52 (4): 947–50. https://doi.org/10.1073/pnas.52.4.947.
Tibshirani, Robert. 1996. “Regression Shrinkage and Selection via the Lasso.” Journal of the Royal Statistical Society: Series B (Methodological) 58 (1): 267–88. https://doi.org/10.1111/j.2517-6161.1996.tb02080.x.
Tibshirani, Ryan J. 2014. “Adaptive Piecewise Polynomial Estimation via Trend Filtering.” The Annals of Statistics 42 (1): 285–323. https://doi.org/10.1214/13-AOS1189.