<p><a href="https://twitter.com/drsimonj">@drsimonj</a> here to show you how to conduct ridge regression (linear regression with L2 regularization) in R using the glmnet package, and use simulations to demonstrate its relative advantages over ordinary least squares regression.</p>
<h2><a href="https://drsimonj.svbtle.com/#ridge-regression_2"> </a>Ridge regression</h2>
<p>Ridge regression uses L2 regularisation to weight/penalise residuals when the parameters of a regression model are being learned. In the context of linear regression, it can be compared to Ordinary Least Square (OLS). OLS defines the function by which parameter estimates (intercepts and slopes) are calculated. It involves minimising the sum of squared residuals. L2 regularisation is a small addition to the OLS function that weights residuals in a particular way to make the parameters more stable. The outcome is typically a model that fits the training data less well than OLS but generalises better because it is less sensitive to extreme variance in the data such as outliers.</p>
<h2><a href="https://drsimonj.svbtle.com/#packages_2"> </a>Packages</h2>
<p>We’ll make use of the following packages in this post:</p>
<pre><code>library(tidyverse)
library(broom)
library(glmnet)
</code></pre>
<h2><a href="https://drsimonj.svbtle.com/#ridge-regression-with-glmnet_2"> </a>Ridge regression with glmnet</h2>
<p>The glmnet package provides the functionality for ridge regression via <code>glmnet()</code>. Important things to know:</p>
<ul><li> Rather than accepting a formula and data frame, it requires a vector input and matrix of predictors.</li>
<li> You must specify <code>alpha = 0</code> for ridge regression.</li>
<li> Ridge regression involves tuning a hyperparameter, lambda. <code>glmnet()</code> will generate default values for you. Alternatively, it is common practice to define your own with the <code>lambda</code> argument (which we’ll do).</li>
</ul><p>Here’s an example using the mtcars data set:</p>
<pre><code>y &lt;- mtcars$hp
x &lt;- mtcars %>% select(mpg, wt, drat) %>% data.matrix()
lambdas &lt;- 10^seq(3, -2, by = -.1)

fit &lt;- glmnet(x, y, alpha = 0, lambda = lambdas)
summary(fit)
#>           Length Class     Mode   
#> a0         51    -none-    numeric
#> beta      153    dgCMatrix S4     
#> df         51    -none-    numeric
#> dim         2    -none-    numeric
#> lambda     51    -none-    numeric
#> dev.ratio  51    -none-    numeric
#> nulldev     1    -none-    numeric
#> npasses     1    -none-    numeric
#> jerr        1    -none-    numeric
#> offset      1    -none-    logical
#> call        5    -none-    call   
#> nobs        1    -none-    numeric
</code></pre>
<p>Because, unlike OLS regression done with <code>lm()</code>, ridge regression involves tuning a hyperparameter, lambda, <code>glmnet()</code> runs the model many times for different values of lambda. We can automatically find a value for lambda that is optimal by using <code>cv.glmnet()</code> as follows:</p>
<pre><code>cv_fit &lt;- cv.glmnet(x, y, alpha = 0, lambda = lambdas)
</code></pre>
<p><code>cv.glmnet()</code> uses cross-validation to work out how well each model generalises, which we can visualise as:</p>
<pre><code>plot(cv_fit)
</code></pre>
<p><a href="https://svbtleusercontent.com/h8b1k5xswvw8ta.jpg"></a></p>
<p>The lowest point in the curve indicates the optimal lambda: the log value of lambda that best minimised the error in cross-validation. We can extract this values as:</p>
<pre><code>opt_lambda &lt;- cv_fit$lambda.min
opt_lambda
#> [1] 3.162278
</code></pre>
<p>And we can extract all of the fitted models (like the object returned by <code>glmnet()</code>) via:</p>
<pre><code>fit &lt;- cv_fit$glmnet.fit
summary(fit)
#>           Length Class     Mode   
#> a0         51    -none-    numeric
#> beta      153    dgCMatrix S4     
#> df         51    -none-    numeric
#> dim         2    -none-    numeric
#> lambda     51    -none-    numeric
#> dev.ratio  51    -none-    numeric
#> nulldev     1    -none-    numeric
#> npasses     1    -none-    numeric
#> jerr        1    -none-    numeric
#> offset      1    -none-    logical
#> call        5    -none-    call   
#> nobs        1    -none-    numeric
</code></pre>
<p>These are the two things we need to predict new data. For example, predicting values and computing an R2 value for the data we trained on:</p>
<pre><code>y_predicted &lt;- predict(fit, s = opt_lambda, newx = x)

# Sum of Squares Total and Error
sst &lt;- sum(y^2)
sse &lt;- sum((y_predicted - y)^2)

# R squared
rsq &lt;- 1 - sse / sst
rsq
#> [1] 0.9318896
</code></pre>
<p>The optimal model has accounted for 93% of the variance in the training data.</p>
<h2><a href="https://drsimonj.svbtle.com/#ridge-v-ols-simulations_2"> </a>Ridge v OLS simulations</h2>
<p>By producing more stable parameters than OLS, ridge regression should be less prone to overfitting training data. Ridge regression might, therefore, predict training data less well than OLS, but better generalise to new data. This will particularly be the case when extreme variance in the training data is high, which tends to happen when the sample size is low and/or the number of features is high relative to the number of observations.</p>
<p>Below is a simulation experiment I created to compare the prediction accuracy of ridge regression and OLS on training and test data.</p>
<p>I first set up the functions to run the simulation:</p>
<pre><code># Compute R^2 from true and predicted values
rsquare &lt;- function(true, predicted) {
  sse &lt;- sum((predicted - true)^2)
  sst &lt;- sum(true^2)
  rsq &lt;- 1 - sse / sst

  # For this post, impose floor...
  if (rsq &lt; 0) rsq &lt;- 0

  return (rsq)
}

# Train ridge and OLS regression models on simulated data set with `n_train`
# observations and a number of features as a proportion to `n_train`,
# `p_features`. Return R squared for both models on:
#   - y values of the training set
#   - y values of a simualted test data set of `n_test` observations
#   - The beta coefficients used to simulate the data
ols_vs_ridge &lt;- function(n_train, p_features, n_test = 200) {
  ## Simulate datasets
  n_features &lt;- floor(n_train * p_features)
  betas &lt;- rnorm(n_features)

  x &lt;- matrix(rnorm(n_train * n_features), nrow = n_train)
  y &lt;- x %*% betas + rnorm(n_train)
  train &lt;- data.frame(y = y, x)

  x &lt;- matrix(rnorm(n_test * n_features), nrow = n_test)
  y &lt;- x %*% betas + rnorm(n_test)
  test &lt;- data.frame(y = y, x)

  ## OLS
  lm_fit &lt;- lm(y ~ ., train)

  # Match to beta coefficients
  lm_betas &lt;- tidy(lm_fit) %>%
    filter(term != &quot;(Intercept)&quot;) %>%
    {.$estimate}
  lm_betas_rsq &lt;- rsquare(betas, lm_betas)

  # Fit to training data
  lm_train_rsq &lt;- glance(lm_fit)$r.squared

  # Fit to test data
  lm_test_yhat &lt;- predict(lm_fit, newdata = test)
  lm_test_rsq  &lt;- rsquare(test$y, lm_test_yhat)

  ## Ridge regression
  lambda_vals &lt;- 10^seq(3, -2, by = -.1)  # Lambda values to search
  cv_glm_fit  &lt;- cv.glmnet(as.matrix(train[,-1]), train$y, alpha = 0, lambda = lambda_vals, nfolds = 5)
  opt_lambda  &lt;- cv_glm_fit$lambda.min  # Optimal Lambda
  glm_fit     &lt;- cv_glm_fit$glmnet.fit

  # Match to beta coefficients
  glm_betas &lt;- tidy(glm_fit) %>%
    filter(term != &quot;(Intercept)&quot;, lambda == opt_lambda) %>% 
    {.$estimate}
  glm_betas_rsq &lt;- rsquare(betas, glm_betas)

  # Fit to training data
  glm_train_yhat &lt;- predict(glm_fit, s = opt_lambda, newx = as.matrix(train[,-1]))
  glm_train_rsq  &lt;- rsquare(train$y, glm_train_yhat)

  # Fit to test data
  glm_test_yhat &lt;- predict(glm_fit, s = opt_lambda, newx = as.matrix(test[,-1]))
  glm_test_rsq  &lt;- rsquare(test$y, glm_test_yhat)

  data.frame(
    model = c(&quot;OLS&quot;, &quot;Ridge&quot;),
    betas_rsq  = c(lm_betas_rsq, glm_betas_rsq),
    train_rsq = c(lm_train_rsq, glm_train_rsq),
    test_rsq = c(lm_test_rsq, glm_test_rsq)
  )

}

# Function to run `ols_vs_ridge()` `n_replications` times
repeated_comparisons &lt;- function(..., n_replications = 5) {
  map(seq(n_replications), ~ ols_vs_ridge(...)) %>% 
    map2(seq(.), ~ mutate(.x, replicate = .y)) %>% 
    reduce(rbind)
}
</code></pre>
<p>Now run the simulations for varying numbers of training data and relative proportions of features (takes some time):</p>
<pre><code>d &lt;- purrr::cross_d(list(
  n_train = seq(20, 200, 20),
  p_features = seq(.55, .95, .05)
))

d &lt;- d %>% 
  mutate(results = map2(n_train, p_features, repeated_comparisons))
</code></pre>
<p>Visualise the results…</p>
<p>For varying numbers of training data (averaging over number of features), how well do both models predict the training and test data?</p>
<pre><code>d %>%
  unnest() %>% 
  group_by(model, n_train) %>%
  summarise(
    train_rsq = mean(train_rsq),
    test_rsq = mean(test_rsq)) %>% 
  gather(data, rsq, contains(&quot;rsq&quot;)) %>% 
  mutate(data = gsub(&quot;_rsq&quot;, &quot;&quot;, data)) %>% 
  ggplot(aes(n_train, rsq, color = model)) +
    geom_line() +
    geom_point(size = 4, alpha = .3) +
    facet_wrap(~ data) +
    theme_minimal() +
    labs(x = &quot;Number of training observations&quot;,
         y = &quot;R squared&quot;)
</code></pre>
<p><a href="https://svbtleusercontent.com/ed74bghrr2zl3q.jpg"></a></p>
<p>As hypothesised, OLS fits the training data better but Ridge regression better generalises to new test data. Further, these effects are more pronounced when the number of training observations is low.</p>
<p>For varying relative proportions of features (averaging over numbers of training data) how well do both models predict the training and test data?</p>
<pre><code>d %>%
  unnest() %>% 
  group_by(model, p_features) %>%
  summarise(
    train_rsq = mean(train_rsq),
    test_rsq = mean(test_rsq)) %>% 
  gather(data, rsq, contains(&quot;rsq&quot;)) %>% 
  mutate(data = gsub(&quot;_rsq&quot;, &quot;&quot;, data)) %>% 
  ggplot(aes(p_features, rsq, color = model)) +
    geom_line() +
    geom_point(size = 4, alpha = .3) +
    facet_wrap(~ data) +
    theme_minimal() +
    labs(x = &quot;Number of features as proportion\nof number of observation&quot;,
         y = &quot;R squared&quot;)
</code></pre>
<p><a href="https://svbtleusercontent.com/btbpyyylpsm0hg.jpg"></a></p>
<p>Again, OLS has performed slightly better on training data, but Ridge better on test data. The effects are more pronounced when the number of features is relatively high compared to the number of training observations.</p>
<p>The following plot helps to visualise the relative advantage (or disadvantage) of Ridge to OLS over the number of observations and features:</p>
<pre><code>d %>%
  unnest() %>%
  group_by(model, n_train, p_features) %>%
  summarise(train_rsq = mean(train_rsq),
            test_rsq  = mean(test_rsq)) %>% 
  group_by(n_train, p_features) %>% 
  summarise(RidgeAdvTrain = train_rsq[model == &quot;Ridge&quot;] - train_rsq[model == &quot;OLS&quot;],
            RidgeAdvTest  = test_rsq[model == &quot;Ridge&quot;] - test_rsq[model == &quot;OLS&quot;]) %>% 
  gather(data, RidgeAdvantage, contains(&quot;RidgeAdv&quot;)) %>% 
  mutate(data = gsub(&quot;RidgeAdv&quot;, &quot;&quot;, data)) %>% 
  ggplot(aes(n_train, p_features, fill = RidgeAdvantage)) +
    scale_fill_gradient2(low = &quot;red&quot;, high = &quot;green&quot;) +
    geom_tile() +
    theme_minimal() +
    facet_wrap(~ data) +
    labs(x = &quot;Number of training observations&quot;,
         y = &quot;Number of features as proportion\nof number of observation&quot;) +
    ggtitle(&quot;Relative R squared advantage of Ridge compared to OLS&quot;)
</code></pre>
<p><a href="https://svbtleusercontent.com/nde8wecxn3qzxa.jpg"></a></p>
<p>This shows the combined effect: that Ridge regression better transfers to test data when the number of training observations is low and/or the number of features is high relative to the number of training observations. OLS performs slightly better on the training data under similar conditions, indicating that it is more prone to overfitting training data than when ridge regularisation is employed.</p>
<h2><a href="https://drsimonj.svbtle.com/#sign-off_2"> </a>Sign off</h2>
<p>Thanks for reading and I hope this was useful for you.</p>
<p>For updates of recent blog posts, follow <a href="https://twitter.com/drsimonj">@drsimonj</a> on Twitter, or email me at <a href="mailto:drsimonjackson@gmail.com">drsimonjackson@gmail.com</a> to get in touch.</p>
<p>If you’d like the code that produced this blog, check out the <a href="https://github.com/drsimonj/blogR">blogR GitHub repository</a>.</p>