library(glmnet)
airbnb = read.csv('https://ec242.netlify.app/data/airbnb_chicago_amenities.csv')Shrinkage with LASSO, Ridge, and Random Forests
Required Reading
- This page.
Guiding Questions
- What is shrinkage?
- What do we do with too many right-hand-side variables?
- What is LASSO?
This week is a little different
We will use the lecture slides from my friend and ace economist, Ed Rubin (U of Oregon). We go through them in three parts. After each part, we stop and try it on the Chicago Airbnb data from last week. At the end, we run Tuesday’s simulation on this data.
The data and packages
Dr. Rubin’s examples use the Credit data from the ISLR package. You do not need it. We use the Airbnb listings again, with 48 new columns. Each new column is 1 if the listing has that amenity and 0 if it does not: a hot tub, a gym, a lake view, an EV charger, a piano. That gives us 60 predictors.
You need the glmnet package. It is new for us.
Shrinkage helps most when we have many predictors and few observations. So we train on only 300 listings and test on the rest.
glmnet does not take a formula. It takes a matrix of predictors, x, and a vector for the outcome, y.
set.seed(242)
train_idx = sample(nrow(airbnb), 300)
train = airbnb[train_idx, ]
test = airbnb[-train_idx, ]
x_train = train %>% dplyr::select(-price) %>% as.matrix()
y_train = train$price
x_test = test %>% dplyr::select(-price) %>% as.matrix()
lambdas = 10^seq(3, -1, length = 100)Is a piano worth $173 a night?
Start with plain OLS on the 300 training listings. glmnet with lambda = 0 is OLS.
ols = glmnet(x_train, y_train, lambda = 0)Here are the five amenities with the largest OLS coefficients.
| Amenity | OLS coefficient (per night) | Listings in the 300 that have it |
|---|---|---|
| piano | $173 | 5 |
| lake access | −$156 | 8 |
| beach access | $130 | 14 |
| ev charger | −$122 | 21 |
| record player | −$94 | 4 |
Do you believe a piano adds $173 a night? How many pianos did OLS see?
OLS believes every coefficient. It cannot say “I am not sure.” Shrinkage gives it a way to say that.
Think of \(\lambda\) as how skeptical the model is.
- At \(\lambda = 0\), the model believes everything. That is OLS.
- As \(\lambda\) grows, every coefficient must pay a penalty. A coefficient stays large only if it improves the fit by more than it costs.
- Ridge charges the square of each coefficient. A small coefficient costs almost nothing. So ridge shrinks every coefficient, but it keeps them all.
- Lasso charges the size of each coefficient. Every dollar of coefficient costs the same. So a weak coefficient is cheaper to drop. The lasso sets it to exactly zero.
- At a very large \(\lambda\), every coefficient is zero. The model predicts the average price for every listing.
Five pianos is weak evidence. A skeptical model should not believe it.
Terminology
I used to have this lecture at the end of our semester, but I think the intuition behind LASSO and ridge regression helps understand our “overfitting” problem. There are two terms I want to cover before we dive into the slides:
Bias vs. Variance: We saw that super-overfit polynomial a couple weeks ago (where we took 20 observations and fit a 16th-degree polynomial). The model we fit was very flexible and bendy, but it did get most of the data points right. It had low bias as it was generally right, but had huge variance – it was all over the place, even within a small range of advertising mode spending. Bias vs. variance refers to the innate tradeoff between these two things. When we used the train and test samples to get the best out of sample fit, we were balancing bias and variance.
Cross validation: This is the term for splitting your sample into two (or more) different subsets (e.g. train and test), fitting the model on one and checking how it does on the other – and then rotating, so every chunk of the data gets a turn being held out.
Part 1: Ridge
Go through the slides from Shrinkage methods to the start of the Lasso section.
Now fit a ridge regression on the training data. alpha = 0 makes it ridge. glmnet standardizes the predictors for you.
ridge = glmnet(x_train, y_train, alpha = 0, lambda = lambdas)- Run
plot(ridge, xvar = "lambda"). Each line is one coefficient. What happens to the coefficients as \(\lambda\) grows? - Does any coefficient reach exactly zero?
Part 2: Lasso
Go through the slides from Lasso to the start of the “Ridge or lasso?” section.
alpha = 1 makes it a lasso.
lasso = glmnet(x_train, y_train, alpha = 1, lambda = lambdas)Here are both models on the same 300 listings. The five colored lines are the largest lasso coefficients. All coefficients are on a standardized scale, so we can compare them.

- Compare the two panels. What does the lasso do that ridge does not?
- Which coefficient lasts the longest in the lasso?
- The
ev_chargercoefficient is negative. Why would an EV charger go with a lower price?
Part 3: Choosing \(\lambda\)
Go through the slides from Ridge or lasso? to the end.
cv.glmnet does the cross-validation for you. It tries every \(\lambda\) and keeps the one with the lowest held-out error.
set.seed(242)
lasso_cv = cv.glmnet(x_train, y_train, alpha = 1, lambda = lambdas, nfolds = 10)
- Find the best \(\lambda\) with
lasso_cv$lambda.min. - Run
coef(lasso_cv, s = "lambda.min"). The lasso shows a dropped coefficient as.. Which amenities did it keep? Which did it drop? What happened to the piano? - Vote first. Will OLS or the lasso have the lower test RMSE? By how much?
- Predict
test$pricewitholsand with the lasso. Usex_test, ands = "lambda.min"for the lasso. Use thermsefunction from last week. What is the test RMSE of each? Which one wins? - Change 300 to 3,000 and do it again. Which one wins now? Why?
Do it again. And again.
The lasso won by about $11. But that was one draw of 300 listings. Maybe we got lucky.
On Tuesday we had the same problem. We drew a new dataset, fit the models, and did it again 250 times. Then we looked at the spread of the predictions. We do the same thing here.
There is one difference. On Tuesday we knew the truth: \(f(x) = x^2\). We do not know the true price function for Chicago. So we pretend:
- All 7,116 listings are the population.
- The OLS fit on all 7,116 listings is the truth. With 7,116 listings, OLS does not overfit.
- Each simulation draws 300 listings from the population. That is one training set.
We predict one listing: listing C from last week’s guessing game. It has 2 bedrooms, sleeps 4, and costs $954 a night. We leave it out of every draw. We also track the piano coefficient.
x_all = airbnb %>% dplyr::select(-price) %>% as.matrix()
y_all = airbnb$price
population = glmnet(x_all, y_all, lambda = 0)
best_lambda = lasso_cv$lambda.min
listing_C = x_all[1082, , drop = FALSE]
truth_C = predict(population, listing_C)[1]
B = 200
sims = data.frame(draw = 1:B, ols = NA, lasso = NA, ols_piano = NA, lasso_piano = NA)
set.seed(242)
for (b in 1:B) {
rows = sample(setdiff(1:nrow(airbnb), 1082), 300)
ols_b = glmnet(x_all[rows, ], y_all[rows], lambda = 0)
lasso_b = glmnet(x_all[rows, ], y_all[rows], alpha = 1, lambda = lambdas)
sims$ols[b] = predict(ols_b, listing_C)
sims$lasso[b] = predict(lasso_b, listing_C, s = best_lambda)
sims$ols_piano[b] = coef(ols_b)["piano", 1]
sims$lasso_piano[b] = coef(lasso_b, s = best_lambda)["piano", 1]
}200 guesses for listing C
Each dot is one model fit on one draw of 300 listings.

Now we split the error into bias and variance. These are the same functions from Tuesday.
get_bias = function(estimate, truth) mean(estimate) - truth
get_var = function(estimate) mean((estimate - mean(estimate))^2)
get_mse = function(truth, estimate) mean((estimate - truth)^2)| Model | Average guess | Bias Squared | Variance | Mean Squared Error |
|---|---|---|---|---|
| OLS | $524 | 61 | 16,067 | 16,128 |
| Lasso | $457 | 3,495 | 6,586 | 10,082 |
200 pianos
Here is the piano coefficient from each draw. The black line is the truth.

The tradeoff, \(\lambda\) by \(\lambda\)
Above, we used one value of \(\lambda\). Now we use all 100. We also use 500 listings instead of one, and average over them. For each \(\lambda\), we get the squared bias and the variance, like Tuesday.

This is the bias-variance plot from Tuesday, made with real data. The x-axis runs the other way. A small \(\lambda\) is a flexible model.
- In the first plot, which model is closer to the truth on average? Which model is steadier?
- Look at the table. Which part of the error does the lasso cut? What does it pay for that?
- Listing C costs $954. The truth from all 7,116 listings is about $516. Why can no model close that gap? What did Tuesday call this error?
- OLS gives the piano a value in every draw. How wide is the range? How often does the lasso say “no piano effect”?
- Find the bottom of the black curve. Where did cross-validation put \(\lambda\)? Cross-validation saw only 300 listings. How did it do?
- Run the simulation code with
hot_tubin place ofpiano. About 1 in 18 listings has a hot tub. What changes?
Random Forests
The decision trees (or “regression trees”) we previously saw were hopefully an intuitive way of partitioning out the predictor variable space into prediction areas. By “partitioning”, I mean chopping up the predictor space in a way that explains the data best, then using the resulting regions as the prediction for any value of the predictors. From ISLR Chapter 8:

We can change the two tuning parameters - cp and minsplit to make the partition more or less detailed (have more or fewer terminal nodes), and there are actually other parameters we can play with in regression trees, though we won’t address those here. If we tune those parameters by cross-validation, then we can generate a pretty good predictor with our chosen tree. But…we can still do better.
Regression trees still have quite a bit of variance, and we’d love to reduce that variance. One way of doing this is by constructing a random forest. As the name indicates, a random forest is a whole bunch of trees put together. But how do we combine multiple trees? And how do we make multiple trees if we have one dataset that leads to one optimal tree?
Multiple trees by bootstrap
The “bootstrap” is a statistical term that means, essentially, randomly resampling. We can “bootstrap” our existing (training) data by randomly drawing observations from the data. Usually, if we have \(n\) observations, we’ll draw \(n\) observations with replacement, which gives us a slightly different dataset: some observations will not be in the bootstrapped sample, and some will be represented 2+ times. All of the bootstrapped samples follow the same distribution of the predictors, but are different realizations. It’s like getting more random samples for free!
So let’s say you draw sample \(b=1\) from the \(n\) observations. It is also of size \(n\), but is different from the original sample. Then, you draw sample number \(b=2\), all the way to, say, \(B = 250\). Now you have 250 different samples of data, and each one will generate a different regression tree, even using the same tuning parameter values.
Combining multiple trees
We need a way of generating a RMSE for any given tuning parameter value, but now we have \(B\) different trees. We can take our test data and put it into each of the \(B\) trees and get a predicted value, right? And when the tree is different, then the prediction will be different. If we take the average over all \(B\) predictions, we’ll get a prediction that has less variance, even when each tree has variance \(\sigma^2\), because averaging \(B\) independent trees cuts the variance to \(\frac{\sigma^2}{B}\). (The trees aren’t quite independent – they’re grown on overlapping bootstrap samples – so you never get the full \(1/B\) reduction.)
So the rmse is:
\[RMSE = \sqrt{\frac{1}{N} \sum_{i=1}^N \left(y_i - \frac{1}{B} \sum_{b=1}^B \hat{f}_{b}(x_i)\right)^2}\]
While it takes a bit longer to estimate this (especially when \(B\) is large), you get much more stable results that often predict better on an evaluation hold-out sample.
OK, technically that’s “bagging”
Random Forest has one other wrinkle – when choosing amongst the candidate predictors for each split, the Random Forest method will choose from a randomly selected subset of the predictors. The reasoning for this given in ISLR is intuitive: if there is one predictor that predicts quite well for the sample, it will always be selected and little emphasis will be on predictors aside from this one. By randomly leaving it out, some trees are forced to fit without that predictor, so they won’t all look the same. When you don’t take the subset, you are bagging. When you do take a subset, you are estimating a random forest.
You won’t need to use this on your Project 3, it’s purely for your own info. Random forests are common out in the world, and are useful to know especially since you already know the fundamental element of it – the tree.
More examples of bias, variance, and model flexibility
If we have time, we can dive back into a little more about model flexibility, bias, and variance….
Model Flexibility
Let’s return to the simulated dataset we used occasionally in the linear regression content. Recall there was a single feature \(x\) with the following properties:
# define regression function
cubic_mean = function(x) {
1 - 2 * x - 3 * x ^ 2 + 5 * x ^ 3
}We then generated some data around this function with some added noise:
# define full data generating process
gen_slr_data = function(sample_size = 100, mu) {
x = runif(n = sample_size, min = -1, max = 1)
y = mu(x) + rnorm(n = sample_size)
tibble(x, y)
}After defining the data generating process, we generate and split the data.
# simulate entire dataset
set.seed(3)
sim_slr_data = gen_slr_data(sample_size = 100, mu = cubic_mean)
# test-train split
slr_trn_idx = sample(nrow(sim_slr_data), size = 0.8 * nrow(sim_slr_data))
slr_trn = sim_slr_data[slr_trn_idx, ]
slr_tst = sim_slr_data[-slr_trn_idx, ]
# estimation-validation split
slr_est_idx = sample(nrow(slr_trn), size = 0.8 * nrow(slr_trn))
slr_est = slr_trn[slr_est_idx, ]
slr_val = slr_trn[-slr_est_idx, ]
# check data
head(slr_trn, n = 10)# A tibble: 10 × 2
x y
<dbl> <dbl>
1 0.573 -1.18
2 0.807 0.576
3 0.272 -0.973
4 -0.813 -1.78
5 -0.161 0.833
6 0.736 1.07
7 -0.242 2.97
8 0.520 -1.64
9 -0.664 0.269
10 -0.777 -2.02
For validating models, we will use RMSE.
# helper function for calculating RMSE
calc_rmse = function(actual, predicted) {
sqrt(mean((actual - predicted) ^ 2))
}Let’s check how linear, k-nearest neighbors, and decision tree models fit to this data make errors, while paying attention to their flexibility.

This picture is an idealized version of what we expect to see, but we’ll illustrate the sorts of validation “curves” that we might see in practice.
Note that in the following three sub-sections, a significant portion of the code is suppressed for visual clarity. See the source document for full details.
Linear Models
First up, linear models. We will fit polynomial models with degree from one to nine, and then validate.
# fit polynomial models
poly_mod_est_list = list(
poly_mod_1_est = lm(y ~ poly(x, degree = 1), data = slr_est),
poly_mod_2_est = lm(y ~ poly(x, degree = 2), data = slr_est),
poly_mod_3_est = lm(y ~ poly(x, degree = 3), data = slr_est),
poly_mod_4_est = lm(y ~ poly(x, degree = 4), data = slr_est),
poly_mod_5_est = lm(y ~ poly(x, degree = 5), data = slr_est),
poly_mod_6_est = lm(y ~ poly(x, degree = 6), data = slr_est),
poly_mod_7_est = lm(y ~ poly(x, degree = 7), data = slr_est),
poly_mod_8_est = lm(y ~ poly(x, degree = 8), data = slr_est),
poly_mod_9_est = lm(y ~ poly(x, degree = 9), data = slr_est)
)The plot below visualizes the results.

What do we see here? As the polynomial degree increases:
- The training error decreases.
- The validation error decreases, then increases.
This more or less matches the idealized version above, but the validation “curve” is much more jagged. This is something that we can expect in practice.
We have previously noted that training error isn’t particularly useful for validating models. That is still true. However, it can be useful for checking that everything is working as planned. In this case, since we know that training error decreases as model flexibility increases, we can verify our intuition that a higher degree polynomial is indeed more flexible.1
k-Nearest Neighbors
Next up, k-nearest neighbors. We will consider values for \(k\) that are odd and between \(1\) and \(45\) inclusive.
library(caret)
# helper function for fitting knn models
fit_knn_mod = function(neighbors) {
knnreg(y ~ x, data = slr_est, k = neighbors)
}# define values of tuning parameter k to evaluate
k_to_try = seq(from = 1, to = 45, by = 2)
# fit knn models
knn_mod_est_list = lapply(k_to_try, fit_knn_mod)The plot below visualizes the results.

Here we see the “opposite” of the usual plot. Why? Because with k-nearest neighbors, a small value of \(k\) generates a flexible model compared to larger values of \(k\). So visually, this plot is flipped. That is we see that as \(k\) increases:
- The training error increases.
- The validation error decreases, then increases.
Important to note here: the pattern above only holds “in general,” that is, there can be minor deviations in the validation pattern along the way. This is due to the random nature of selecting the data for the validation set.
Decision Trees
Lastly, we evaluate some decision tree models. We choose some arbitrary values of cp to evaluate, while holding minsplit constant at 5. These are arbitrary choices that produce a plot that is useful for discussion.
# helper function for fitting decision tree models
library(rpart)
library(rpart.plot)
tree_knn_mod = function(flex) {
rpart(y ~ x, data = slr_est, cp = flex, minsplit = 5)
}# define values of tuning parameter cp to evaluate
cp_to_try = c(0.5, 0.3, 0.1, 0.05, 0.01, 0.001, 0.0001)
# fit decision tree models
tree_mod_est_list = lapply(cp_to_try, tree_knn_mod)The plot below visualizes the results.

Based on this plot, how is cp related to model flexibility?2