library(tidyverse)
library(broom)
library(stargazer)
library(skimr)
library(knitr)Classwork 8
Linear Regression with Wildfire Smoke Data
This classwork follows the linear-regression exercise from DANL 320 using the wildfire example data. Lecture 10 uses DANL 320 Lecture 2, pages 25–31 and 47–53.
One row is a county-month. The outcome, pm25, is total monthly monitor PM2.5 in µg/m³. The satellite smoke, weather, and Canadian fire inputs are observed monthly values. The random split below evaluates held-out rows in this historical sample; it does not evaluate an advance forecast for an unseen year.
R packages
Question 1
Read the wildfire PM2.5 data and prepare the wildfire data.frame below. The codebook provides the original column descriptions, units, and sources.
- Which variables are continuous? Which are categorical?
- For each continuous variable, provide descriptive statistics.
- For each categorical variable, provide the frequency of each distinct value.
The preparation keeps counties observed in at least 11 years, as in the original Classwork 8 file. It selects the target and satellite/weather predictors and gives several columns shorter names. Monitor-derived PM2.5 products are excluded from the predictors because they may already incorporate the readings we are trying to predict.
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))
wildfire |>
summarise(rows = n(), counties = n_distinct(county),
first_year = min(year), last_year = max(year)) |>
kable()| rows | counties | first_year | last_year |
|---|---|---|---|
| 36732 | 229 | 2011 | 2024 |
Variable description
| Variable | Description |
|---|---|
pm25 |
Total monthly monitor PM2.5, µg/m³; the outcome |
county |
County identifier, treated as a factor |
month |
Calendar month, treated as a factor; January is the reference |
year |
Calendar year, used as a numeric trend |
hms_pw_plume_days |
Population-weighted smoke-plume days |
hms_medium_plus_days |
Days with medium or heavy smoke plumes |
hms_heavy_days |
Days with heavy smoke plumes |
tmax |
Mean daily maximum temperature, °C |
prcp |
Monthly precipitation, mm |
rh |
Relative humidity, % |
wind |
10 m wind speed, m/s |
blh |
Boundary-layer height, m |
log_frp_ca |
log(1 + Canadian fire radiative power total) |
skim(wildfire)
count(wildfire, month)
count(wildfire, county)Question 2
Divide wildfire into training and test data.frames named dtrain and dtest. Use the same random-split pattern as DANL 320, with about 80% in training and 20% in testing. Lectures 11–13 and Classwork 9–11 use the same seed and split.
set.seed(1)
wildfire <- wildfire |> mutate(rnd = runif(n()))
dtrain <- wildfire |> filter(rnd > .2) |> select(-rnd)
dtest <- wildfire |> filter(rnd <= .2) |> select(-rnd)
nrow(dtrain) / nrow(wildfire)[1] 0.8004193
- Why do we use
set.seed()? - What does
runif(n())produce, and why does the cutoff produce approximately an 80/20 split? - Why do we remove
rndbefore fitting the model?
Question 3
Train the following linear regression model and inspect its summary:
\begin{aligned} \mathrm{PM2.5}_i ={}& \beta_0 + \alpha_{\mathrm{county}(i)} + \gamma_{\mathrm{month}(i)} + \beta_{\mathrm{year}}\,\mathrm{year}_i \\ &+ \beta_1\,\mathrm{plume\ days}_i + \beta_2\,\mathrm{medium{+}\ days}_i + \beta_3\,\mathrm{heavy\ days}_i \\ &+ \beta_4\,\mathrm{tmax}_i + \beta_5\,\mathrm{prcp}_i + \beta_6\,\mathrm{rh}_i + \beta_7\,\mathrm{wind}_i \\ &+ \beta_8\,\mathrm{blh}_i + \beta_9\,\mathrm{log\ FRP}_i + \epsilon_i . \end{aligned}
County and month effects use one omitted reference category. The formula below lets R create those dummy variables automatically.
f_full <- pm25 ~ county + month + year +
hms_pw_plume_days + hms_medium_plus_days + hms_heavy_days +
tmax + prcp + rh + wind + blh + log_frp_ca
rmse <- function(y, yhat) sqrt(mean((y - yhat)^2))
mae <- function(y, yhat) mean(abs(y - yhat))
model <- lm(f_full, data = dtrain)
glance(model) |>
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 |
summary(model)
stargazer(model, type = "text", omit = "county")Question 4
Make predictions for the outcome using dtest and the regression result from Question 3. Compare training and test errors.
pred_train <- predict(model, newdata = dtrain)
pred_test <- predict(model, newdata = dtest)
tibble(
sample = c("Training", "Test"),
RMSE = c(rmse(dtrain$pm25, pred_train), rmse(dtest$pm25, pred_test)),
MAE = c(mae(dtrain$pm25, pred_train), mae(dtest$pm25, pred_test))
) |> kable(digits = 3)| sample | RMSE | MAE |
|---|---|---|
| Training | 1.949 | 1.399 |
| Test | 1.964 | 1.411 |
- What would a large gap between training and test error suggest?
- Which score describes performance on observations the fitted model did not use?
Question 5
Interpret the beta estimate for hms_heavy_days. State the outcome units and what the model holds constant. Does this predictive association by itself establish a causal effect of smoke?
tidy(model, conf.int = TRUE) |> filter(term == "hms_heavy_days")Question 6
- Which calendar month is most strongly associated with higher
pm25relative to January? - Interpret that month’s coefficient.
- Why do we include 11 month dummies with an intercept rather than all 12?
tidy(model) |>
filter(str_starts(term, "month")) |>
arrange(desc(estimate))Question 7
Draw coefficient plots for:
- the temperature, precipitation, humidity, wind, and boundary-layer-height variables;
- the smoke-plume variables; and
- the month dummy variables.
Use the template below, changing the selected terms for each plot. Coefficients for variables measured in different units should be interpreted in their own units.
tidy(model, conf.int = TRUE) |>
filter(term %in% c("tmax", "prcp", "rh", "wind", "blh")) |>
ggplot(aes(x = estimate, y = term, xmin = conf.low, xmax = conf.high)) +
geom_vline(xintercept = 0, linetype = "dashed") +
geom_errorbar(orientation = "y", width = 0.15) +
geom_point() +
labs(x = "Coefficient and 95% confidence interval", y = NULL) +
theme_minimal()Question 8
Draw a residual plot for the test predictions. On average, are the predictions correct? Do you see systematic errors or unusually large misses?
prediction <- dtest |>
mutate(predicted = pred_test, residual = pm25 - predicted)
ggplot(prediction, aes(x = predicted, y = residual)) +
geom_hline(yintercept = 0, linetype = "dashed") +
geom_point(alpha = 0.25, color = "#1c4982") +
labs(x = "Predicted PM2.5 (µg/m³)", y = "Observed minus predicted PM2.5 (µg/m³)") +
theme_minimal()
Question 9
Draw a histogram of pm25 and a histogram of log(1 + pm25) using the same eligible observations. What changes after the transformation?
Check the logarithm’s domain
For a finite real-valued log(1 + pm25), we need pm25 > -1. Zero is valid and maps to zero; values between −1 and 0 are also valid and have negative transformed values. At −1 the result is -Inf, and below −1 it is NaN. See the R documentation for log1p().
The source data retain negative monitor measurements. EPA’s AQS documentation explains that measurement variability near zero can produce acceptable negative values. Do not automatically replace them with zero or treat them as missing.
For Questions 9–10 only, use separate copies containing pm25 > -1. Keep wildfire, dtrain, and dtest unchanged for the earlier questions and Classwork 9. Filter the existing split without drawing new random numbers. This is a restriction for the transformation exercise, not a general cleaning rule for PM2.5 data.
stopifnot(all(is.finite(wildfire$pm25)))
tibble(
sample = c("Training", "Test"),
original_rows = c(nrow(dtrain), nrow(dtest)),
excluded_pm25_le_minus1 = c(sum(dtrain$pm25 <= -1), sum(dtest$pm25 <= -1)),
eligible_rows = c(sum(dtrain$pm25 > -1), sum(dtest$pm25 > -1))
) |> kable()| sample | original_rows | excluded_pm25_le_minus1 | eligible_rows |
|---|---|---|---|
| Training | 29401 | 5 | 29396 |
| Test | 7331 | 2 | 7329 |
wildfire_log <- wildfire |> filter(pm25 > -1)
dtrain_log <- dtrain |> filter(pm25 > -1)
dtest_log <- dtest |> filter(pm25 > -1)
stopifnot(
nrow(dtrain_log) > 0, nrow(dtest_log) > 0,
nrow(wildfire_log) == nrow(dtrain_log) + nrow(dtest_log),
all(is.finite(log1p(wildfire_log$pm25)))
)The current file excludes five training rows and two test rows, leaving 29,396 training and 7,329 test rows. Four other negative measurements remain because they satisfy the logarithm’s domain.
Compare the histograms
Use wildfire_log for both histograms so that a change in the plotted sample does not get confused with the effect of the transformation. Both plots below use 40 bins, but their horizontal scales have different units.
ggplot(wildfire_log, aes(pm25)) +
geom_histogram(bins = 40) +
labs(x = "PM2.5 (µg/m³)", y = "County-months",
title = "PM2.5: log-eligible observations") +
theme_minimal()
ggplot(wildfire_log, aes(log1p(pm25))) +
geom_histogram(bins = 40) +
labs(x = "log(1 + PM2.5)", y = "County-months",
title = "Transformed PM2.5: the same observations") +
theme_minimal()
Question 10
Train a model with log(1 + pm25) as the outcome and the same predictors. Repeat Questions 4–8 using dtrain_log and dtest_log from Question 9.
Fit and compare on the same observations
Refit the original-outcome model on dtrain_log too. Both models must use the same training rows and the same test rows for this comparison. na.action = na.fail stops the fit if a missing model value would otherwise cause a row to disappear silently.
Back-transform the log model’s predictions with expm1() before calculating errors against observed PM2.5. These are inverse-transformed log predictions; they do not automatically estimate the conditional mean of PM2.5 on its original scale. Compare their actual prediction errors rather than assuming that transforming the outcome improves accuracy.
model_raw_log_sample <- lm(f_full, data = dtrain_log, na.action = na.fail)
model_log <- lm(update(f_full, log1p(pm25) ~ .),
data = dtrain_log, na.action = na.fail)
stopifnot(
nobs(model_raw_log_sample) == nrow(dtrain_log),
nobs(model_log) == nrow(dtrain_log)
)
pred_raw_train <- predict(model_raw_log_sample, newdata = dtrain_log)
pred_raw_test <- predict(model_raw_log_sample, newdata = dtest_log)
pred_log_train <- expm1(predict(model_log, newdata = dtrain_log))
pred_log_test <- expm1(predict(model_log, newdata = dtest_log))
stopifnot(
all(is.finite(pred_raw_train)), all(is.finite(pred_raw_test)),
all(is.finite(pred_log_train)), all(is.finite(pred_log_test))
)
tibble(
model = rep(c("PM2.5 outcome", "log(1 + PM2.5) outcome"), each = 2),
sample = rep(c("Training", "Test"), times = 2),
rows = rep(c(nrow(dtrain_log), nrow(dtest_log)), times = 2),
RMSE = c(rmse(dtrain_log$pm25, pred_raw_train),
rmse(dtest_log$pm25, pred_raw_test),
rmse(dtrain_log$pm25, pred_log_train),
rmse(dtest_log$pm25, pred_log_test)),
MAE = c(mae(dtrain_log$pm25, pred_raw_train),
mae(dtest_log$pm25, pred_raw_test),
mae(dtrain_log$pm25, pred_log_train),
mae(dtest_log$pm25, pred_log_test))
) |> kable(digits = 3)| model | sample | rows | RMSE | MAE |
|---|---|---|---|---|
| PM2.5 outcome | Training | 29396 | 1.946 | 1.397 |
| PM2.5 outcome | Test | 7329 | 1.960 | 1.409 |
| log(1 + PM2.5) outcome | Training | 29396 | 1.927 | 1.347 |
| log(1 + PM2.5) outcome | Test | 7329 | 1.941 | 1.361 |
These scores describe only test observations with recorded pm25 > -1. The test sample differs from Question 4, so compare the two models within this table, rather than comparing a Question 10 score directly with a Question 4 score.
Interpret coefficients and inspect residuals
For Questions 5–7, use tidy(model_log, conf.int = TRUE) in place of tidy(model, conf.int = TRUE). The coefficients and confidence intervals are now in log-outcome units, not µg/m³. For a one-unit predictor increase, 100 * (exp(estimate) - 1) gives the percentage change in the inverse-transformed fitted value of 1 + PM2.5, holding the other included predictors constant. Month coefficients compare with January on that same transformed scale. Update the coefficient-plot axis label accordingly.
For Question 8, plot test residuals in the original PM2.5 units using the back-transformed predictions:
prediction_log <- dtest_log |>
mutate(predicted = pred_log_test, residual = pm25 - predicted)
ggplot(prediction_log, aes(x = predicted, y = residual)) +
geom_hline(yintercept = 0, linetype = "dashed") +
geom_point(alpha = 0.25, color = "#1c4982") +
labs(x = "Back-transformed predicted PM2.5 (µg/m³)",
y = "Observed minus predicted PM2.5 (µg/m³)") +
theme_minimal()
- Which model has lower test RMSE? Does it also have lower test MAE?
- Does the log model reduce the largest misses or change the residual pattern?
- Why must both models use the same training and test observations?
- Which observations does this restricted comparison leave out?
Keep the original prepared variables, dtrain, dtest, model, and pred_test from Questions 1–8 for Classwork 9, where you will compare ordinary regression with lasso, ridge, and elastic net.