library(tidyverse)
library(rpart)
library(rpart.plot)
library(ranger)
library(xgboost)
library(Matrix)
library(knitr)
theme_set(theme_bw(base_size = 13))Classwork 11
Tree-based Models: Random Forest and Gradient-Boosted Trees
This classwork follows the tree-based modeling exercise in DANL 320 Classwork 9, using the wildfire data from Classwork 8. Use Lecture 13 for bagging, random forests, out-of-bag error, and boosting.
Setup
Packages
Wildfire PM2.5 Data
Read the same wildfire county-month file used in Classwork 8. The codebook documents the original column names. The code below selects the same monitored-county sample, renames the predictors, and repeats the same 80/20 random split used in these four ML classes.
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))
set.seed(1)
wildfire <- wildfire |> mutate(rnd = runif(n()))
dtrain <- wildfire |> filter(rnd > .2) |> select(-rnd)
dtest <- wildfire |> filter(rnd <= .2) |> select(-rnd)Variable Description
| Variable | Description |
|---|---|
pm25 |
Monthly mean total PM2.5 at the county’s EPA monitors, in µg/m³. This is the outcome. |
county, month, year |
County identifier as a factor, calendar month as a factor, and calendar year. |
hms_pw_plume_days |
Population-weighted number of satellite smoke-plume days. |
hms_medium_plus_days, hms_heavy_days |
Days with medium-or-heavy and heavy overhead smoke plumes. |
tmax, prcp |
Monthly mean maximum temperature (°C) and total precipitation (mm). |
rh, wind, blh |
ERA5 relative humidity (%), wind speed (m/s), and boundary-layer height (m). |
log_frp_ca |
log(1 + Canadian fire radiative power) for the month. |
- Consider the tree-based models: (1) decision trees, (2) random forest, and (3) gradient-boosted trees.
- Outcome Variable:
pm25. - Predictors: All remaining modeling variables. The random splitting variable
rndis removed before fitting.
- Outcome Variable:
This random split follows DANL 320. It measures prediction for held-out county-months using monthly inputs that are already available. Neighboring counties and other rows from the same smoke episode can be in training. A score for a future year would require a different split and an input-timing check. The target is total monitor PM2.5, including pollution from sources other than wildfire.
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
x_train <- dtrain |> select(-pm25)
y_train <- dtrain$pm25
x_test <- dtest |> select(-pm25)
y_test <- dtest$pm25
mse <- function(y, pred) mean((y - pred)^2)
rmse <- function(y, pred) sqrt(mse(y, pred))
# These are the same rows throughout Questions 1–6.
tibble(sample = c("Training", "Test"), rows = c(nrow(dtrain), nrow(dtest))) |>
kable()| sample | rows |
|---|---|
| Training | 29401 |
| Test | 7331 |
Question 1
Fit a regression tree model with a maximum depth of 3 (maxdepth = 3). Provide an interpretation of the leaf nodes.
set.seed(1)
tree_depth3 <- rpart(f_full, data = dtrain, method = "anova",
control = rpart.control(maxdepth = 3, xval = 0))
rpart.plot(tree_depth3, type = 2, extra = 101, roundint = FALSE,
main = "Wildfire PM2.5: maximum depth 3")
Choose one path from the root to a leaf. State the conditions along that path and interpret its prediction in µg/m³.
Question 2
Fit a regression tree model without imposing a maximum depth constraint.
set.seed(1)
tree_large <- rpart(f_full, data = dtrain, method = "anova",
control = rpart.control(cp = 0.001, xval = 5))
printcp(tree_large)
Regression tree:
rpart(formula = f_full, data = dtrain, method = "anova", control = rpart.control(cp = 0.001,
xval = 5))
Variables actually used in tree construction:
[1] blh county hms_heavy_days
[4] hms_medium_plus_days hms_pw_plume_days log_frp_ca
[7] month prcp rh
[10] tmax year
Root node error: 260175/29401 = 8.8492
n= 29401
CP nsplit rel error xerror xstd
1 0.1646649 0 1.00000 1.00010 0.0175135
2 0.0856014 1 0.83534 0.84228 0.0167710
3 0.0700971 2 0.74973 0.73996 0.0115156
4 0.0419118 3 0.67964 0.68501 0.0112431
5 0.0345414 4 0.63772 0.64095 0.0086344
6 0.0336706 5 0.60318 0.61291 0.0082582
7 0.0295010 6 0.56951 0.56523 0.0076262
8 0.0264836 7 0.54001 0.55411 0.0075835
9 0.0141428 8 0.51353 0.52719 0.0074046
10 0.0111391 9 0.49939 0.50846 0.0073274
11 0.0108218 10 0.48825 0.49863 0.0072649
12 0.0106072 11 0.47742 0.49037 0.0071965
13 0.0103719 12 0.46682 0.48413 0.0071147
14 0.0084101 13 0.45645 0.47573 0.0067353
15 0.0073196 14 0.44804 0.47301 0.0068045
16 0.0047926 15 0.44072 0.47219 0.0068989
17 0.0046046 16 0.43592 0.46053 0.0067547
18 0.0045660 17 0.43132 0.45571 0.0067275
19 0.0045383 18 0.42675 0.45571 0.0067275
20 0.0041799 19 0.42221 0.45287 0.0067171
21 0.0041584 20 0.41803 0.44940 0.0067242
22 0.0038723 21 0.41388 0.45026 0.0067636
23 0.0037437 22 0.41000 0.44842 0.0069215
24 0.0035978 23 0.40626 0.44607 0.0068649
25 0.0034335 24 0.40266 0.44380 0.0068215
26 0.0032032 25 0.39923 0.44042 0.0067935
27 0.0031555 26 0.39603 0.43842 0.0067819
28 0.0030455 27 0.39287 0.43800 0.0067803
29 0.0025803 28 0.38982 0.43206 0.0067667
30 0.0023934 29 0.38724 0.42813 0.0066422
31 0.0023880 30 0.38485 0.42705 0.0066309
32 0.0023714 32 0.38007 0.42705 0.0066309
33 0.0020268 33 0.37770 0.42388 0.0065311
34 0.0019816 34 0.37568 0.42126 0.0065160
35 0.0019263 35 0.37369 0.42019 0.0064999
36 0.0018679 37 0.36984 0.41923 0.0064789
37 0.0018239 38 0.36797 0.41650 0.0065108
38 0.0017740 39 0.36615 0.41324 0.0064330
39 0.0017659 40 0.36438 0.41263 0.0064292
40 0.0016933 41 0.36261 0.41121 0.0064238
41 0.0016773 42 0.36092 0.41061 0.0064225
42 0.0015765 43 0.35924 0.40963 0.0064240
43 0.0014808 44 0.35766 0.40636 0.0063529
44 0.0014437 45 0.35618 0.40319 0.0063259
45 0.0014394 46 0.35474 0.40201 0.0063188
46 0.0014092 47 0.35330 0.40207 0.0063195
47 0.0013894 48 0.35189 0.40108 0.0062959
48 0.0013858 49 0.35050 0.40093 0.0062958
49 0.0013426 50 0.34912 0.40060 0.0062938
50 0.0013188 51 0.34777 0.39762 0.0061223
51 0.0013099 52 0.34645 0.39760 0.0061254
52 0.0012823 53 0.34514 0.39688 0.0061171
53 0.0012554 55 0.34258 0.39589 0.0061176
54 0.0012441 56 0.34132 0.39536 0.0061111
55 0.0012060 57 0.34008 0.39476 0.0061096
56 0.0011245 58 0.33887 0.39158 0.0060247
57 0.0011097 59 0.33775 0.39069 0.0060285
58 0.0010863 60 0.33664 0.39126 0.0060561
59 0.0010756 61 0.33555 0.39105 0.0060459
60 0.0010407 62 0.33448 0.38988 0.0060852
61 0.0010178 63 0.33344 0.38888 0.0060944
62 0.0010149 64 0.33242 0.38888 0.0060944
63 0.0010000 65 0.33140 0.38848 0.0060939
This leaves maxdepth at its package default and uses a smaller complexity penalty so that the tree can grow further. Compare the number of leaves with Question 1. Does a lower training error alone establish an improvement?
Question 3
Prune regression trees using cross-validation (CV). Plot the CV error versus tree size, choose the lowest mean CV error, and compare the pruned tree with the tree from Question 1.
plotcp(tree_large)
best_cp <- tree_large$cptable[which.min(tree_large$cptable[, "xerror"]), "CP"]
tree_pruned <- prune(tree_large, cp = best_cp)
printcp(tree_pruned)
Regression tree:
rpart(formula = f_full, data = dtrain, method = "anova", control = rpart.control(cp = 0.001,
xval = 5))
Variables actually used in tree construction:
[1] blh county hms_heavy_days
[4] hms_medium_plus_days hms_pw_plume_days log_frp_ca
[7] month prcp rh
[10] tmax year
Root node error: 260175/29401 = 8.8492
n= 29401
CP nsplit rel error xerror xstd
1 0.1646649 0 1.00000 1.00010 0.0175135
2 0.0856014 1 0.83534 0.84228 0.0167710
3 0.0700971 2 0.74973 0.73996 0.0115156
4 0.0419118 3 0.67964 0.68501 0.0112431
5 0.0345414 4 0.63772 0.64095 0.0086344
6 0.0336706 5 0.60318 0.61291 0.0082582
7 0.0295010 6 0.56951 0.56523 0.0076262
8 0.0264836 7 0.54001 0.55411 0.0075835
9 0.0141428 8 0.51353 0.52719 0.0074046
10 0.0111391 9 0.49939 0.50846 0.0073274
11 0.0108218 10 0.48825 0.49863 0.0072649
12 0.0106072 11 0.47742 0.49037 0.0071965
13 0.0103719 12 0.46682 0.48413 0.0071147
14 0.0084101 13 0.45645 0.47573 0.0067353
15 0.0073196 14 0.44804 0.47301 0.0068045
16 0.0047926 15 0.44072 0.47219 0.0068989
17 0.0046046 16 0.43592 0.46053 0.0067547
18 0.0045660 17 0.43132 0.45571 0.0067275
19 0.0045383 18 0.42675 0.45571 0.0067275
20 0.0041799 19 0.42221 0.45287 0.0067171
21 0.0041584 20 0.41803 0.44940 0.0067242
22 0.0038723 21 0.41388 0.45026 0.0067636
23 0.0037437 22 0.41000 0.44842 0.0069215
24 0.0035978 23 0.40626 0.44607 0.0068649
25 0.0034335 24 0.40266 0.44380 0.0068215
26 0.0032032 25 0.39923 0.44042 0.0067935
27 0.0031555 26 0.39603 0.43842 0.0067819
28 0.0030455 27 0.39287 0.43800 0.0067803
29 0.0025803 28 0.38982 0.43206 0.0067667
30 0.0023934 29 0.38724 0.42813 0.0066422
31 0.0023880 30 0.38485 0.42705 0.0066309
32 0.0023714 32 0.38007 0.42705 0.0066309
33 0.0020268 33 0.37770 0.42388 0.0065311
34 0.0019816 34 0.37568 0.42126 0.0065160
35 0.0019263 35 0.37369 0.42019 0.0064999
36 0.0018679 37 0.36984 0.41923 0.0064789
37 0.0018239 38 0.36797 0.41650 0.0065108
38 0.0017740 39 0.36615 0.41324 0.0064330
39 0.0017659 40 0.36438 0.41263 0.0064292
40 0.0016933 41 0.36261 0.41121 0.0064238
41 0.0016773 42 0.36092 0.41061 0.0064225
42 0.0015765 43 0.35924 0.40963 0.0064240
43 0.0014808 44 0.35766 0.40636 0.0063529
44 0.0014437 45 0.35618 0.40319 0.0063259
45 0.0014394 46 0.35474 0.40201 0.0063188
46 0.0014092 47 0.35330 0.40207 0.0063195
47 0.0013894 48 0.35189 0.40108 0.0062959
48 0.0013858 49 0.35050 0.40093 0.0062958
49 0.0013426 50 0.34912 0.40060 0.0062938
50 0.0013188 51 0.34777 0.39762 0.0061223
51 0.0013099 52 0.34645 0.39760 0.0061254
52 0.0012823 53 0.34514 0.39688 0.0061171
53 0.0012554 55 0.34258 0.39589 0.0061176
54 0.0012441 56 0.34132 0.39536 0.0061111
55 0.0012060 57 0.34008 0.39476 0.0061096
56 0.0011245 58 0.33887 0.39158 0.0060247
57 0.0011097 59 0.33775 0.39069 0.0060285
58 0.0010863 60 0.33664 0.39126 0.0060561
59 0.0010756 61 0.33555 0.39105 0.0060459
60 0.0010407 62 0.33448 0.38988 0.0060852
61 0.0010178 63 0.33344 0.38888 0.0060944
62 0.0010149 64 0.33242 0.38888 0.0060944
63 0.0010000 65 0.33140 0.38848 0.0060939
The CV errors use training rows only. Keep the test rows for the final comparison in Question 6. The CV-optimal tree can have many leaves on this larger file. Use the code below to inspect that tree in a separate, enlarged plotting window rather than compressing all of its labels into the page.
rpart.plot(tree_pruned, type = 2, extra = 101, roundint = FALSE,
varlen = 8, faclen = 1, main = "Wildfire PM2.5: CV-pruned tree")Question 4
Fit and tune a random forest model using different mtry values. Plot the variable importance measures.
p <- ncol(x_train)
rf_grid <- tibble(mtry = c(2, 6, p))
rf_results <- tibble()
for (m in rf_grid$mtry) {
fit <- ranger(
f_full, data = dtrain, num.trees = 150, mtry = m,
min.node.size = 10, respect.unordered.factors = "order",
num.threads = 2, seed = 1917
)
rf_results <- bind_rows(rf_results,
tibble(mtry = m, oob_mse = fit$prediction.error))
}
rf_results |> kable(digits = 3)| mtry | oob_mse |
|---|---|
| 2 | 2.021 |
| 6 | 1.939 |
| 12 | 1.999 |
ggplot(rf_results, aes(mtry, oob_mse)) +
geom_line() + geom_point() +
labs(title = "Random Forest Tuning Results",
x = "mtry", y = "Out-of-bag MSE")
mtry controls the number of predictors considered at a split. Here, mtry = p is bagging. For regression, ranger reports OOB mean squared error in prediction.error; take its square root to express it in PM2.5 units.
best_mtry <- rf_results |> slice_min(oob_mse, n = 1, with_ties = FALSE) |> pull(mtry)
final_wildfire_rf <- ranger(
f_full, data = dtrain, num.trees = 300, mtry = best_mtry,
min.node.size = 10, importance = "permutation",
respect.unordered.factors = "order", num.threads = 2, seed = 1917
)
importance <- tibble(
variable = names(final_wildfire_rf$variable.importance),
importance = unname(final_wildfire_rf$variable.importance)
)
importance_plot <- ggplot(importance, aes(importance, reorder(variable, importance))) +
geom_col(fill = "#1c4982") +
labs(title = "Wildfire PM2.5: Random Forest Variable Importance",
x = "Increase in OOB MSE after shuffling", y = NULL)
importance_plot
Which predictors does the forest rely on most? Explain why permutation importance describes predictive contribution rather than a causal effect. A high importance value does not show whether the association is positive or negative.
Question 5
Fit and tune an XGBoost model using the hyperparameter grid below. Plot its variable importance measures.
Matrix input
XGBoost requires a numeric matrix. model.matrix() converts the factors to dummy variables. Build both matrices from factors with the same levels and confirm that the columns match.
x_train_mat <- sparse.model.matrix(f_full, data = dtrain)[, -1, drop = FALSE]
x_test_mat <- sparse.model.matrix(f_full, data = dtest)[, -1, drop = FALSE]
stopifnot(identical(colnames(x_train_mat), colnames(x_test_mat)))
dMat_train <- xgb.DMatrix(x_train_mat, label = y_train)Cross-validated tuning
This small grid keeps the DANL 320 tuning workflow practical for the larger wildfire file. It compares learning rates and tree depths. For each combination, CV chooses the number of boosting rounds using training folds only.
xgb_grid <- crossing(eta = c(0.05, 0.1), max_depth = c(2L, 4L))
set.seed(1937)
fold_id <- sample(rep(1:3, length.out = nrow(dtrain)))
cv_folds <- lapply(1:3, function(k) which(fold_id == k))
xgb_results_lst <- vector("list", nrow(xgb_grid))
xgb_cv_fits <- vector("list", nrow(xgb_grid))
for (i in seq_len(nrow(xgb_grid))) {
params <- list(
objective = "reg:squarederror", eta = xgb_grid$eta[i],
max_depth = xgb_grid$max_depth[i], gamma = 0,
colsample_bytree = 1, min_child_weight = 1, subsample = 1,
tree_method = "hist", max_bin = 64, nthread = 2, seed = 1937
)
cv_fit <- xgb.cv(params = params, data = dMat_train, folds = cv_folds,
nrounds = 150, early_stopping_rounds = 10,
metrics = "rmse", verbose = 0)
log <- cv_fit$evaluation_log
best_round <- which.min(log$test_rmse_mean)
xgb_results_lst[[i]] <- tibble(
eta = xgb_grid$eta[i], max_depth = xgb_grid$max_depth[i],
nrounds = best_round, cv_rmse = log$test_rmse_mean[best_round]
)
xgb_cv_fits[[i]] <- cv_fit
}
xgb_results <- bind_rows(xgb_results_lst)
xgb_results |> arrange(cv_rmse) |> kable(digits = 3)| eta | max_depth | nrounds | cv_rmse |
|---|---|---|---|
| 0.10 | 4 | 150 | 1.866 |
| 0.05 | 4 | 150 | 2.022 |
| 0.10 | 2 | 150 | 2.112 |
| 0.05 | 2 | 150 | 2.260 |
Why do eta and nrounds need to be considered together? Explain why the held-out test file does not appear in the CV code.
Final XGBoost model
best_i <- which.min(xgb_results$cv_rmse)
best_xgb <- xgb_results[best_i, ]
final_params <- list(
objective = "reg:squarederror", eta = best_xgb$eta,
max_depth = best_xgb$max_depth, gamma = 0,
colsample_bytree = 1, min_child_weight = 1, subsample = 1,
tree_method = "hist", max_bin = 64, nthread = 2, seed = 1937
)
xgb_fit_final <- xgb.train(params = final_params, data = dMat_train,
nrounds = best_xgb$nrounds, verbose = 0)
xgb_importance <- xgb.importance(model = xgb_fit_final)
xgb_importance |> head(12) |> kable(digits = 3)| Feature | Gain | Cover | Frequency |
|---|---|---|---|
| hms_medium_plus_days | 0.199 | 0.029 | 0.056 |
| tmax | 0.153 | 0.050 | 0.143 |
| year | 0.140 | 0.057 | 0.144 |
| log_frp_ca | 0.067 | 0.027 | 0.069 |
| month6 | 0.066 | 0.001 | 0.015 |
| blh | 0.030 | 0.030 | 0.065 |
| wind | 0.029 | 0.015 | 0.044 |
| prcp | 0.027 | 0.024 | 0.067 |
| hms_heavy_days | 0.021 | 0.006 | 0.036 |
| hms_pw_plume_days | 0.014 | 0.004 | 0.060 |
| county46033 | 0.013 | 0.023 | 0.007 |
| county36031 | 0.012 | 0.021 | 0.006 |
The XGBoost Gain column measures the feature’s share of training loss improvement from splits. It uses a different scale from the forest’s permutation importance, so compare rankings rather than numerical magnitudes across these two methods.
xgb_importance_plot <- xgb_importance |>
as_tibble() |>
slice_max(Gain, n = 12) |>
ggplot(aes(Gain, reorder(Feature, Gain))) +
geom_col(fill = "#d55e00") +
labs(title = "Wildfire PM2.5: XGBoost Variable Importance",
x = "Gain", y = NULL)
xgb_importance_plot
boosting_log <- as_tibble(xgb_cv_fits[[best_i]]$evaluation_log)
boosting_plot <- boosting_log |>
select(iter, train_rmse_mean, test_rmse_mean) |>
pivot_longer(-iter, names_to = "sample", values_to = "rmse") |>
mutate(sample = recode(sample, train_rmse_mean = "Training",
test_rmse_mean = "Cross-validation")) |>
ggplot(aes(iter, rmse, color = sample)) +
geom_line(linewidth = 0.9) +
scale_color_manual(values = c("Training" = "#1c4982", "Cross-validation" = "#d55e00")) +
labs(title = "Wildfire PM2.5: Boosting in Action",
x = "Number of trees", y = "RMSE (µg/m³)", color = NULL) +
theme(legend.position = "top")
boosting_plot
Question 6
Compare the Mean Squared Errors (MSEs) on the test data across the different tree-based models. Analyze and discuss the differences in predictive performance among these models.
pred_depth3 <- predict(tree_depth3, newdata = dtest)
pred_pruned <- predict(tree_pruned, newdata = dtest)
rf_test_pred <- predict(final_wildfire_rf, data = dtest)$predictions
xgb_test_pred <- predict(xgb_fit_final, x_test_mat)
ols_test_pred <- predict(lm(f_full, data = dtrain), newdata = dtest)
results <- tibble(
model = c("OLS", "Depth-3 tree", "CV-pruned tree", "Random forest", "XGBoost"),
mse = c(mse(y_test, ols_test_pred), mse(y_test, pred_depth3),
mse(y_test, pred_pruned), mse(y_test, rf_test_pred), mse(y_test, xgb_test_pred))
) |>
mutate(rmse = sqrt(mse))
results |> kable(digits = 3)| model | mse | rmse |
|---|---|---|
| OLS | 3.857 | 1.964 |
| Depth-3 tree | 5.326 | 2.308 |
| CV-pruned tree | 3.636 | 1.907 |
| Random forest | 2.025 | 1.423 |
| XGBoost | 3.499 | 1.871 |
stopifnot(all(is.finite(results$mse)))- Which model has the smallest test MSE? Is its improvement over the simpler tree large enough to matter for this outcome?
- Does the OOB or CV ranking agree with the final test ranking? Why can they differ?
- Which model would you choose for this exercise, considering accuracy, computation, and interpretation?
Keep this final comparison separate from tuning: do not repeatedly adjust the grid to improve these same test results.