4.8 Regression regularization

In this section we discuss regularization in the context of regression as a way of controlling overfit.

Recall that in regression we have observations from \(\mathbb R^p\) and our task is to predict a value in \(\mathbb R\). We will do this by finding a function \(h\in \mathcal H\) that gives a small out-of-sample error \[ E_{out} = E\left[ (Y-h(X))^2 \right]. \] In linear regression, the collection of functions \(\mathcal H\) are the functions of the form \[ h(x) = \beta_1x^1+ \cdots + \beta_p x^p, \] and we are thus to choose the parameters \(\beta_1,\ldots,\beta_p\) in a good way. The \(\beta\) that minimises the in-sample error is the least squares estimate of \(\beta_1,\ldots,\beta_p\) and can be calculated easily.

As we have seen, we may specify some function \(\varphi_i\) and use \(\varphi_1(x),\ldots,\varphi_M(x)\) to predict \(y\) and we are still in the case of linear regression. However we need to be careful not to overfit. Let us see a simple example were \(\varphi\) are polynomials. First we construct the functions that will generate our data:

library(ggplot2)
library(gridExtra)
library(resample)
## Warning: package 'resample' was built under R version 4.6.1
gen_data <- function(truth, n.obs = 100) {
  x <- runif(n.obs, min = -2, max = 2)
  y <- truth(x) + rnorm(n.obs) * 0.4
  data.df <- data.frame(y = y, x = x)
}

truth <- function(x) {
  sin(x * 2 + 1) + x
}

For convenience, we write a function that fits three different polynomial regressions and returns the plot.

fit_plot <- function(){
  data.train.df <- gen_data(truth)

  x.grid <- seq(-2, 2, 0.01)
  x.grid.df <- data.frame(x = x.grid)

  fit1 <- predict(lm(y ~ poly(x, 2), data.train.df),
                  x.grid.df)
  fit2 <- predict(lm(y ~ poly(x, 6), data.train.df),
                  x.grid.df)
  fit3 <- predict(lm(y ~ poly(x, 20), data.train.df),
                  x.grid.df)

  cbp1 <- c("#999999", "#E69F00", "#56B4E9", "#009E73",
            "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

  p <- ggplot(data.frame(
    x = x.grid,
    fit1 = fit1,
    fit2 = fit2,
    fit3 = fit3
  )) +
    geom_line(aes(x = x, y = fit1, color = "1"), size = 1) +
    geom_line(aes(x = x, y = fit2, color = "2"), size = 1) +
    geom_line(aes(x = x, y = fit3, color = "3"), size = 1) +
    scale_colour_manual(
      name = "",
      values = c(
        "train" = cbp1[1],
        "1" = cbp1[2],
        "2" = cbp1[3],
        "3" = cbp1[4]
      ),
      labels = c("1" = "2nd", "2" = "6th", "3" = "20th")
    ) +
    geom_point(aes(x = x, y = y, color = "train"),
               data = data.train.df,
               show.legend = FALSE) +
    ylab("y") +
    coord_cartesian(ylim = c(-3, 2)) +
    theme_minimal()

  p
}

Next we fit the polynomial models to four different training sets, generated from the same distribution.

set.seed(42)
grid.arrange(fit_plot(), fit_plot(), fit_plot(), fit_plot(),
             nrow = 2)
Polynomial fits to four different sets of training data, sampled from the same distribution

Figure 4.17: Polynomial fits to four different sets of training data, sampled from the same distribution

We see from the pictures that the 2nd degree polynomial fit does not change very much on the different training sets, while the 20th degree polynomial looks very different in the four pictures.

Now let us repeat this experiment many times, and only plot the mean and variance of \(h\).

Mean fit and 95% CI for the different polynomial regressions

Figure 4.18: Mean fit and 95% CI for the different polynomial regressions

From the pictures we see that the 2nd degree polynomial has a bias, but for 6th degree, the bias is close to 0. The error in the 2nd degree polynomial is a sum of bias and variance, but for 6th and 20th the error is dominated by the variance term. The variance becomes larger as the degree of the polynomial becomes larger, while the bias is already close to 0 for 6th degree. Therefore, the total error, the sum of bias and variance, is smallest for a 6th degree polynomial. As before, we see that a very flexible model will tend to overfit the data and may perform worse than a less flexible model.

Another way to see the same phenomena is to choose one point, here \(x=1.5\), and plot the bias and variance as we vary the degree of the polynomial. We do this for sample size \(n=100\) and \(n=10000\).

library(ggplot2)
library(gridExtra)

biasVariancePlot <- function(n.obs, x0 = 1.5, n.sim = 1e3, seed = 42){
  degrees <- seq(2,20,2)

  predictions <- matrix(nrow = n.sim, ncol = length(degrees))
  x.df = data.frame(x = x0)

  for (sim in seq_len(n.sim)) {
    data.df <- gen_data(truth, n.obs)
    for (i in seq(length(degrees))) {
      predictions[sim,i] <- predict(lm(y ~ poly(x, degrees[i]), data.df),
                                    x.df)
    }
  }

  plot.df <- data.frame(hbar = colMeans(predictions),
                         variance = colVars(predictions),
                         bias = (colMeans(predictions)-truth(x0))^2,
                         degree = degrees,
                         total = colVars(predictions) + (colMeans(predictions)-truth(x0))^2)

  cbp1 <- c("#999999", "#E69F00", "#56B4E9", "#009E73",
            "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

  ggplot(plot.df, aes(x = degree)) +
    geom_line(aes(y = bias, color = "bias"), size = 1) +
    geom_line(aes(y = variance, color = "variance"), size = 1) +
    geom_line(aes(y = total, color = "total"), size = 1) +
    scale_colour_manual(name = "",
                        values = c("bias" = cbp1[2], "variance" = cbp1[3], "total" = cbp1[4]),
                        labels = c("bias" = "bias", "variance" = "variance", "total" = "total")) +
    scale_y_continuous(trans='log10') +
    ylab("Error") +
    xlab("Degree") +
    theme_minimal()

}

grid.arrange(biasVariancePlot(100), biasVariancePlot(10000),
             nrow = 1)
Bias-variance decomposition when varying the degree of the polynomial. Left picture with n = 100, right with n = 10000

Figure 4.19: Bias-variance decomposition when varying the degree of the polynomial. Left picture with n = 100, right with n = 10000

From the pictures we see that the bias is decreasing and the variance is increasing, as the degree increases. In the left picture, \(n=100\), the minimum total error is at a degree around 3. When the sample size increases, in the right picture, we can fit a more complex model, and the minimum error is at a degree around 8.

We have seen that we also in the regression setting need to bound the model complexity so that we do not overfit the model. This can be done by choosing a small family of models \(\mathcal H\). In the above case this would mean limiting the degree of the polynomial. Another option, that we will explore here, is to include a regularization term in the loss function.

Recall that least squares regression minimizes the in-sample error: \[ E_{in} = \sum_{i=1}^n\left( y_i - \beta_0 - \sum_{j=1}^p \beta_j x_{ij} \right)^2. \] Ridge regression instead minimizes \[ E_{in} + \lambda\sum_{j=1}^p \beta_j^2, \] and the lasso minimizes \[ E_{in} + \lambda\sum_{j=1}^p | \beta_j |. \] Here \(\lambda\) is a tuning parameter that needs to be determined separately. Ridge regression and lasso use different penalty terms of model complexity, but the main idea is the same. Models with many and large parameters will be penalized in favor of less complex models. Compared to least squares regression, the estimates of \(\beta_j\) will be smaller in ridge and lasso. That is the estimates will shrink towards zero. These methods are therefore sometimes called shrinkage methods. We know that the estimates in least squares regression are unbiased and shrinkage methods therefore introduce a bias. The hope is that the variance will decrease sufficiently, so that the total prediction error is smaller. Note that neither of these methods are scale invariant, however usually software will take care of this automatically.

Let us look at the same example above, this time with a degree 20 polynomial, but penalized with ridge and lasso.

library(ggplot2)
library(gridExtra)
library(glmnet)
## Warning: package 'glmnet' was built under R version 4.6.1
data.df <- gen_data(truth)

model.ridge <- glmnet(poly(data.df$x,20), data.df$y, alpha = 0 )
model.lasso <- glmnet(poly(data.df$x,20), data.df$y, alpha = 1 )
Coefficents as lambda is varied for ridge regression

Figure 4.20: Coefficents as lambda is varied for ridge regression

Coefficients as lambda is varied for the lasso

Figure 4.21: Coefficients as lambda is varied for the lasso

In the pictures we see that the fitted coefficients decrease towards 0 as \(\lambda\) increases. The main difference between the two methods is that in the ridge regression all coefficients are strictly positive for any finite \(\lambda\), while for the lasso, coefficients become 0 when \(\lambda\) is large. This difference relates to model interpretability. That is, the lasso will produce a simple model where many variables can be disregarded. We also mention that the lasso and ridge regression can, unlike unregularized least squares, handle the case \(p>>n\). There is a generalization of ridge and lasso called elastic net, where a parameter \(0\leq \alpha \leq 1\) is introduced and the loss function is instead, \[ E_{in} + \lambda\left( \alpha \sum_{j=1}^p | \beta_j | + (1-\alpha) \sum_{j=1}^p \beta_j^2\right). \]