library(tidyverse)
library(broom)
library(glmnet)
library(Matrix) # sparse predictor matrices
library(knitr)Classwork 9
Regularized Linear Regression — Wildfire Smoke and PM2.5
Setup
Load Data
Use the same county-month wildfire data and outcome as in Classwork 8.
wildfire_raw <- read_csv(
"https://bcdanl.github.io/data/wildfire_ml_pm25_county_month_2011_2024.csv",
col_types = cols(GEOID = col_character()),
show_col_types = FALSE
)
long_history <- wildfire_raw |>
summarise(n_years = n_distinct(year), .by = GEOID) |>
filter(n_years >= 11)
wildfire <- wildfire_raw |>
semi_join(long_history, by = "GEOID") |>
transmute(
pm25 = aqs_pm25_mean,
county = factor(GEOID),
month = factor(month, levels = 1:12),
year,
hms_pw_plume_days = hms_pop_weighted_plume_days,
hms_medium_plus_days, hms_heavy_days,
tmax = wx_tmax_mean_c,
prcp = wx_prcp_total_mm,
rh = era5_rh_pct,
wind = era5_ws10_ms,
blh = era5_blh_m,
log_frp_ca = log1p(fire_ca_frp_total_mw)
)
stopifnot(!anyNA(wildfire))Model
- The outcome is the county’s monthly mean monitor PM2.5, measured in µg/m³.
- Predictors include county and calendar-month indicators, a year trend, satellite smoke plumes, weather, and Canadian fire activity.
- We compare ordinary least squares with lasso and ridge regression using the same observations and predictors.
\text{PM2.5}_i = \beta_0 + \beta_1 X_{1,i} + \cdots + \beta_p X_{p,i} + \epsilon_i
f_full <- pm25 ~ county + month + year +
hms_pw_plume_days + hms_medium_plus_days + hms_heavy_days +
tmax + prcp + rh + wind + blh + log_frp_caChecking Data
wildfire |>
summarise(
observations = n(),
counties = n_distinct(county),
first_year = min(year), last_year = max(year),
mean_pm25 = mean(pm25), sd_pm25 = sd(pm25)
) |>
kable(digits = 2)| observations | counties | first_year | last_year | mean_pm25 | sd_pm25 |
|---|---|---|---|---|---|
| 36732 | 229 | 2011 | 2024 | 7.86 | 2.98 |
Train-Test Split
Use the same 80/20 random split as in Classwork 8. This evaluates prediction for held-out county-month rows within the observed panel; it does not evaluate forecasts for future years.
set.seed(1)
wildfire <- wildfire |>
mutate(rnd = runif(n()))
dtrain <- wildfire |> filter(rnd > .2) |> select(-rnd)
dtest <- wildfire |> filter(rnd <= .2) |> select(-rnd)
# glmnet requires a numeric predictor matrix.
# Expand factors into indicator columns and remove the intercept column;
# glmnet will fit its own unpenalized intercept.
X_train <- sparse.model.matrix(f_full, data = dtrain)[, -1]
X_test <- sparse.model.matrix(f_full, data = dtest)[, -1]
y_train <- dtrain$pm25
y_test <- dtest$pm25
stopifnot(identical(colnames(X_train), colnames(X_test)))
rmse <- function(y, yhat) sqrt(mean((y - yhat)^2))
mae <- function(y, yhat) mean(abs(y - yhat))Questions
Question 1. Linear Regression
Fit the ordinary linear regression model with all of the predictors in f_full.
model <- lm(f_full, data = dtrain)
model |>
glance() |>
select(r.squared, adj.r.squared, sigma, nobs) |>
kable(digits = 3)| r.squared | adj.r.squared | sigma | nobs |
|---|---|---|---|
| 0.571 | 0.567 | 1.958 | 29401 |
- How many predictor columns are in
X_train? Why is this larger than the number of named variables in the formula? - Which pairs of smoke or weather predictors might be correlated?
Question 2. Regularized Linear Regression
Fit 5-fold cross-validated lasso and ridge models with cv.glmnet().
alpha = 1: lasso;alpha = 0: ridge.family = "gaussian": linear regression (the default).intercept = TRUE: include an intercept without penalizing it.standardize = TRUE: standardize predictors internally, so different measurement units do not determine the penalty.
Use the same five folds when comparing lasso and ridge. The test set stays outside cross-validation.
set.seed(1)
foldid <- sample(rep(1:5, length.out = nrow(dtrain)))
model_lasso <- cv.glmnet(
x = X_train, y = y_train,
alpha = 1, family = "gaussian",
nfolds = 5, foldid = foldid,
intercept = TRUE, standardize = TRUE
)
model_ridge <- cv.glmnet(
x = X_train, y = y_train,
alpha = 0, family = "gaussian",
nfolds = 5, foldid = foldid,
intercept = TRUE, standardize = TRUE
)- Which argument controls the type of penalty? Which parameter is selected by cross-validation?
- Why should the test targets stay outside this step?
Question 3. Plots
Cross-validation error curves
plot(model_lasso, main = "Lasso: Wildfire PM2.5")
plot(model_ridge, main = "Ridge: Wildfire PM2.5")
- Locate
lambda.minandlambda.1se. Which applies the stronger penalty? - What do the error bars and the numbers across the top represent?
Coefficient paths
plot(model_lasso$glmnet.fit, xvar = "lambda",
main = "Lasso coefficient paths")
abline(v = log(model_lasso$lambda.min), lty = 2)
abline(v = log(model_lasso$lambda.1se), lty = 3)
legend("topright", legend = c("lambda.min", "lambda.1se"),
lty = c(2, 3), bty = "n")
plot(model_ridge$glmnet.fit, xvar = "lambda",
main = "Ridge coefficient paths")
abline(v = log(model_ridge$lambda.min), lty = 2)
abline(v = log(model_ridge$lambda.1se), lty = 3)
legend("topright", legend = c("lambda.min", "lambda.1se"),
lty = c(2, 3), bty = "n")
Number of nonzero coefficients
tibble(lambda = model_lasso$lambda, nzero = model_lasso$nzero) |>
ggplot(aes(log(lambda), nzero)) +
geom_line() +
geom_vline(xintercept = log(model_lasso$lambda.min), linetype = 2) +
geom_vline(xintercept = log(model_lasso$lambda.1se), linetype = 3) +
labs(x = "log(lambda)", y = "Nonzero coefficients",
title = "Lasso variable selection") +
theme_minimal(base_size = 13)
- How does increasing the penalty change the lasso coefficients and the number of selected columns?
- How does ridge differ from lasso in the coefficient-path plots?
Question 4. Coefficients and Interpretation
Extract coefficients at both cross-validation choices and compare them with OLS. The returned coefficients use the original predictor units even though glmnet standardizes internally.
coefficient_table <- function(fit, model_name) {
b_min <- coef(fit, s = "lambda.min")
b_1se <- coef(fit, s = "lambda.1se")
tibble(
term = rownames(b_min),
model = model_name,
beta_min = as.numeric(b_min),
beta_1se = as.numeric(b_1se)
)
}
betas <- bind_rows(
coefficient_table(model_lasso, "Lasso"),
coefficient_table(model_ridge, "Ridge")
) |>
left_join(tidy(model) |> select(term, beta_ols = estimate), by = "term")
betas |>
filter(!str_detect(term, "^county"), term != "(Intercept)") |>
kable(digits = 3)| term | model | beta_min | beta_1se | beta_ols |
|---|---|---|---|---|
| month2 | Lasso | 0.219 | 0.316 | 0.210 |
| month3 | Lasso | -0.830 | -0.709 | -0.832 |
| month4 | Lasso | -1.437 | -1.356 | -1.424 |
| month5 | Lasso | -1.444 | -1.340 | -1.418 |
| month6 | Lasso | 0.115 | 0.057 | 0.160 |
| month7 | Lasso | 0.000 | 0.000 | 0.052 |
| month8 | Lasso | -0.962 | -0.922 | -0.917 |
| month9 | Lasso | -2.014 | -1.986 | -1.978 |
| month10 | Lasso | -1.780 | -1.679 | -1.762 |
| month11 | Lasso | -0.730 | -0.506 | -0.733 |
| month12 | Lasso | -0.029 | 0.068 | -0.038 |
| year | Lasso | -0.220 | -0.212 | -0.220 |
| hms_pw_plume_days | Lasso | 0.006 | 0.001 | 0.007 |
| hms_medium_plus_days | Lasso | 0.307 | 0.311 | 0.306 |
| hms_heavy_days | Lasso | 0.148 | 0.129 | 0.149 |
| tmax | Lasso | -0.051 | -0.035 | -0.054 |
| prcp | Lasso | -0.005 | -0.004 | -0.005 |
| rh | Lasso | -0.037 | -0.025 | -0.038 |
| wind | Lasso | -0.525 | -0.539 | -0.518 |
| blh | Lasso | -0.003 | -0.003 | -0.004 |
| log_frp_ca | Lasso | 0.056 | 0.010 | 0.058 |
| month2 | Ridge | 0.378 | 0.576 | 0.210 |
| month3 | Ridge | -0.634 | -0.435 | -0.832 |
| month4 | Ridge | -1.194 | -1.013 | -1.424 |
| month5 | Ridge | -1.130 | -0.944 | -1.418 |
| month6 | Ridge | 0.416 | 0.466 | 0.160 |
| month7 | Ridge | 0.362 | 0.484 | 0.052 |
| month8 | Ridge | -0.590 | -0.397 | -0.917 |
| month9 | Ridge | -1.687 | -1.471 | -1.978 |
| month10 | Ridge | -1.525 | -1.343 | -1.762 |
| month11 | Ridge | -0.522 | -0.321 | -0.733 |
| month12 | Ridge | 0.134 | 0.320 | -0.038 |
| year | Ridge | -0.212 | -0.190 | -0.220 |
| hms_pw_plume_days | Ridge | 0.011 | 0.015 | 0.007 |
| hms_medium_plus_days | Ridge | 0.268 | 0.213 | 0.306 |
| hms_heavy_days | Ridge | 0.200 | 0.255 | 0.149 |
| tmax | Ridge | -0.053 | -0.041 | -0.054 |
| prcp | Ridge | -0.005 | -0.005 | -0.005 |
| rh | Ridge | -0.032 | -0.022 | -0.038 |
| wind | Ridge | -0.463 | -0.406 | -0.518 |
| blh | Ridge | -0.003 | -0.003 | -0.004 |
| log_frp_ca | Ridge | 0.049 | 0.039 | 0.058 |
Coefficient plot
betas |>
filter(model == "Lasso", term != "(Intercept)", beta_1se != 0) |>
slice_max(abs(beta_1se), n = 20, with_ties = FALSE) |>
ggplot(aes(beta_1se, fct_reorder(term, beta_1se))) +
geom_vline(xintercept = 0, color = "maroon") +
geom_segment(aes(x = 0, xend = beta_1se,
y = fct_reorder(term, beta_1se),
yend = fct_reorder(term, beta_1se))) +
geom_point() +
labs(x = "Lasso coefficient (lambda.1se)", y = NULL) +
theme_minimal(base_size = 13)
- Pick one smoke or weather coefficient and interpret its association with PM2.5, holding the other predictors fixed. Does its sign or size change across OLS, lasso, and ridge?
- Which coefficients become exactly zero? Does a zero prove that the variable has no causal effect?
- Why are raw coefficient sizes for rainfall in millimeters and temperature in degrees not directly comparable as measures of importance?
Question 5. Prediction and Evaluation
Predict the held-out PM2.5 and evaluate every model on the same test rows.
dtest_pred <- dtest |>
mutate(
OLS = as.numeric(predict(model, newdata = dtest)),
Lasso_min = as.numeric(predict(model_lasso, newx = X_test,
s = "lambda.min")),
Lasso_1se = as.numeric(predict(model_lasso, newx = X_test,
s = "lambda.1se")),
Ridge_min = as.numeric(predict(model_ridge, newx = X_test,
s = "lambda.min")),
Ridge_1se = as.numeric(predict(model_ridge, newx = X_test,
s = "lambda.1se"))
)
scores <- dtest_pred |>
pivot_longer(c(OLS, Lasso_min, Lasso_1se, Ridge_min, Ridge_1se),
names_to = "model", values_to = "prediction") |>
summarise(
test_rows = n(),
RMSE = rmse(pm25, prediction),
MAE = mae(pm25, prediction),
.by = model
)
scores |> kable(digits = 3)| model | test_rows | RMSE | MAE |
|---|---|---|---|
| OLS | 7331 | 1.964 | 1.411 |
| Lasso_min | 7331 | 1.964 | 1.410 |
| Lasso_1se | 7331 | 1.977 | 1.414 |
| Ridge_min | 7331 | 1.964 | 1.404 |
| Ridge_1se | 7331 | 1.980 | 1.403 |
Residual plot
dtest_pred |>
ggplot(aes(Lasso_1se, pm25 - Lasso_1se)) +
geom_hline(yintercept = 0, color = "maroon") +
geom_point(alpha = .25) +
labs(x = "Predicted PM2.5 (lasso, lambda.1se)",
y = "Residual: observed - predicted (µg/m³)") +
theme_minimal(base_size = 13)
- Compare RMSE across OLS, lasso, and ridge. Did the penalty improve prediction for these held-out rows?
- Compare the two lambda choices. What do you gain or lose by choosing
lambda.1se? - Where are the largest residuals? What limitation would you report with the model’s test score?
Optional: Elastic Net
Use an alpha between 0 and 1, retaining the same training folds and test rows.
model_enet <- cv.glmnet(
x = X_train, y = y_train,
alpha = .5, family = "gaussian",
nfolds = 5, foldid = foldid,
intercept = TRUE, standardize = TRUE
)
pred_enet <- as.numeric(predict(model_enet, newx = X_test,
s = "lambda.1se"))
rmse(y_test, pred_enet)- How does the elastic-net result compare with lasso and ridge?
- If you compare several values of
alpha, which data should guide that choice?