library(tidyverse)
library(rpart)
library(rpart.plot)
library(broom)
library(skimr)
library(rmarkdown)Classwork 10
Decision Trees and Pruning with Wildfire Smoke Data
This classwork follows the regression-tree, tuning, pruning, and classification-tree exercises from DANL 320. We use the same wildfire-smoke table and training/test rows as Classes 1 and 2.
The outcome is monthly total monitor PM2.5, in µg/m³. This 80/20 random split evaluates held-out county-month rows within the observed panel. It is not a forecast for a future year.
Setup
Wildfire smoke data
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)
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))wildfire |> select(-rnd) |> paged_table()Variable description
| Variable | Description |
|---|---|
pm25 |
Monthly mean total PM2.5 at the county’s monitors, µg/m³ |
county, month, year |
County identifier, calendar month, and year |
hms_pw_plume_days |
Plume days weighted by the share of residents under a plume |
hms_medium_plus_days, hms_heavy_days |
Days under medium/heavy or heavy overhead smoke plumes |
tmax, prcp |
Mean daily maximum temperature (°C), monthly precipitation (mm) |
rh, wind, blh |
Relative humidity (%), wind speed (m/s), boundary-layer height (m) |
log_frp_ca |
log(1 + Canadian fire-radiative-power total) |
Use the codebook for the original names and sources. Monitor-derived PM2.5 products are excluded from the predictors. An overhead smoke plume is not a direct reading of smoke at the surface.
Part 1. Regression trees with wildfire smoke data
Explore the variables
dtrain |>
select(pm25, hms_medium_plus_days, tmax, rh) |>
skim()| Name | select(dtrain, pm25, hms_… |
| Number of rows | 29401 |
| Number of columns | 4 |
| _______________________ | |
| Column type frequency: | |
| numeric | 4 |
| ________________________ | |
| Group variables | None |
Variable type: numeric
| skim_variable | n_missing | complete_rate | mean | sd | p0 | p25 | p50 | p75 | p100 | hist |
|---|---|---|---|---|---|---|---|---|---|---|
| pm25 | 0 | 1 | 7.85 | 2.97 | -6.20 | 5.93 | 7.56 | 9.39 | 36.73 | ▁▇▁▁▁ |
| hms_medium_plus_days | 0 | 1 | 1.51 | 3.67 | 0.00 | 0.00 | 0.00 | 1.00 | 28.00 | ▇▁▁▁▁ |
| tmax | 0 | 1 | 15.71 | 10.39 | -16.44 | 6.85 | 16.66 | 25.41 | 35.87 | ▁▅▇▇▇ |
| rh | 0 | 1 | 68.10 | 6.73 | 33.70 | 63.50 | 68.50 | 72.90 | 89.30 | ▁▁▆▇▁ |
dtrain |>
ggplot(aes(x = hms_medium_plus_days, y = pm25)) +
geom_point(alpha = 0.12) +
geom_smooth(method = lm, color = "steelblue") +
labs(x = "Medium/heavy-plume days", y = "Monitor PM2.5 (µg/m³)") +
theme_bw()
Question 1. Fit an initial regression tree
Fit a simple regression tree using three predictors, hms_medium_plus_days, tmax, and rh.
- Do not specify any
controloptions inrpart(). method = "anova"fits a regression tree. Each terminal node predicts the mean training PM2.5 in that node.
f_tree <- pm25 ~ hms_medium_plus_days + tmax + rh
initial_tree <- rpart(
f_tree,
data = dtrain,
method = "anova"
)
rpart.plot(initial_tree, tweak = 0.9)
Answer the following in complete sentences:
- Which variable appears at the first split?
- What does that suggest about the predictor’s importance in this tree?
- Choose one terminal node and explain what its predicted value means, including the units.
Question 2. Grow a larger tree
Now let the algorithm grow a much more flexible tree. Keep the same three predictors in f_tree and permit smaller splits before pruning.
set.seed(320)
wildfire_tree <- rpart(
f_tree,
data = dtrain,
method = "anova",
control = rpart.control(cp = 0, xval = 5, minsplit = 40, maxdepth = 8)
)
# Count terminal nodes without trying to fit a very large tree on one page.
tibble(
tree = c("Initial tree", "Larger tree"),
leaves = c(sum(initial_tree$frame$var == "<leaf>"),
sum(wildfire_tree$frame$var == "<leaf>"))
) |> paged_table()plotcp(wildfire_tree)
Answer the following:
- Compared with the first tree, is this tree more or less complex?
- Why might a very large tree be a problem for out-of-sample prediction?
- Looking at
plotcp(), what kind of tree are we usually trying to choose: the biggest tree, the smallest tree, or a tree that balances fit and complexity?
Question 3. Fine-tune tree growth before pruning
Before pruning, try a few different tree-growth settings. This is a simple form of hyperparameter tuning. The goal is to see how choices like minsplit and maxdepth affect the size of the tree and the cross-validated error.
reg_tuning_grid <- tribble(
~minsplit, ~maxdepth,
20, 4,
20, 6,
40, 4,
40, 6
)
reg_tuning_results <- pmap_dfr(
reg_tuning_grid,
function(minsplit, maxdepth) {
set.seed(320)
fit <- rpart(
f_tree,
data = dtrain,
method = "anova",
control = rpart.control(
cp = 0, xval = 5, minsplit = minsplit, maxdepth = maxdepth
)
)
best <- as_tibble(fit$cptable) |>
arrange(xerror, nsplit) |>
slice(1)
tibble(minsplit, maxdepth, nsplit = best$nsplit,
cp = best$CP, xerror = best$xerror)
}
)
reg_tuning_results |> arrange(xerror) |> paged_table()The five-fold cross-validation happens inside dtrain. Reusing the seed gives the candidate trees the same random fold assignment. xerror is cross-validated prediction error relative to the root-node training error; it is not RMSE in µg/m³. The final test rows are not used to choose these settings.
Answer the following:
- Which combination of
minsplitandmaxdepthgives the smallest cross-validated error? - What does the
xerrorcolumn represent? Why do we often use it when choosing the pruning parameter? - Does a deeper tree always give the best
xerror? - Based on this table, which setting would you carry forward to pruning, and why?
Question 4. Prune the tuned tree
Fit the decision tree using the setting with the smallest cross-validated error in Question 3. Then choose a smaller subtree from its cost-complexity pruning path.
best_setting <- reg_tuning_results |>
arrange(xerror, maxdepth, minsplit) |>
slice(1)
set.seed(320)
tuned_tree <- rpart(
f_tree,
data = dtrain,
method = "anova",
control = rpart.control(
cp = 0, xval = 5,
minsplit = best_setting$minsplit,
maxdepth = best_setting$maxdepth
)
)
cp_table <- as_tibble(tuned_tree$cptable)
cp_table |> paged_table()min_row <- cp_table |> arrange(xerror, nsplit) |> slice(1)
# The 1-SE rule permits error within one standard error of the minimum.
xerror_threshold <- min_row$xerror + min_row$xstd
cp_1se <- cp_table |>
filter(xerror <= xerror_threshold) |>
arrange(nsplit) |>
slice(1) |>
pull(CP)
pruned_tree <- prune(tuned_tree, cp = cp_1se)
rpart.plot(pruned_tree, tweak = 0.85)
The CP table contains nsplit (number of splits), rel error (relative training error), xerror (relative cross-validated error), and xstd (its estimated standard error). The 1-SE rule selects the simplest tree whose xerror is within one standard error of the smallest xerror. To use the minimum-error rule instead, set xerror_threshold <- min_row$xerror and rerun the pruning step.
Compare the tuned unpruned tree and the pruned tree on the same rows:
reg_models <- list(
"Initial tree" = initial_tree,
"Larger tree" = wildfire_tree,
"Tuned tree" = tuned_tree,
"Pruned tree" = pruned_tree
)
reg_scores <- imap_dfr(reg_models, function(fit, label) {
tibble(
model = label,
leaves = sum(fit$frame$var == "<leaf>"),
train_rmse = rmse(dtrain$pm25, predict(fit, newdata = dtrain)),
test_rmse = rmse(dtest$pm25, predict(fit, newdata = dtest)),
test_mae = mae(dtest$pm25, predict(fit, newdata = dtest))
)
})
reg_scores |> paged_table()- What became simpler after pruning?
- Why can a pruned tree sometimes predict better on new data even if it fits the training data less closely?
- Did your earlier hyperparameter choices seem to matter for the final pruned result?
- Does pruning improve this particular test score? Explain the difference between a method’s aim and a guaranteed result.
Part 2. Classification trees with wildfire smoke data
A high-PM2.5 county-month
For this exercise define high_pm25 as monthly monitor PM2.5 above 10 µg/m³. This cutoff is a teaching definition, not a regulatory threshold or health recommendation. We keep the same continuous outcome and held-out rows for regression comparisons; this second part illustrates classification trees with a derived binary target.
dtrain_class <- dtrain |>
mutate(high_pm25 = factor(if_else(pm25 > 10, "yes", "no"),
levels = c("no", "yes")))
dtest_class <- dtest |>
mutate(high_pm25 = factor(if_else(pm25 > 10, "yes", "no"),
levels = c("no", "yes")))
dtrain_class |> count(high_pm25) |> paged_table()pm25 determines high_pm25 exactly. Keep it out of the classification predictors. The explicit formulas below use only smoke and weather features.
Question 5. Visualize the classification problem
dtrain_class |>
ggplot(aes(x = hms_medium_plus_days, y = tmax, color = high_pm25)) +
geom_point(alpha = 0.2) +
labs(
title = "High-PM2.5 vs. other county-months",
x = "Medium/heavy-plume days",
y = "Mean daily maximum temperature (°C)",
color = "PM2.5 above 10?"
) +
theme_bw()
Based on the scatterplot, where do high-PM2.5 months seem more likely to happen? Describe the rough region using plume days and temperature.
Question 6. Training and test data
- Confirm that
dtrain_classanddtest_classretain the 80/20 random split created in Setup. - Do not split again: changing the target’s representation does not require changing which observations are held out.
tibble(
sample = c("Training", "Test"),
rows = c(nrow(dtrain_class), nrow(dtest_class)),
share = rows / sum(rows)
) |> paged_table()stopifnot(nrow(dtrain_class) == nrow(dtrain),
nrow(dtest_class) == nrow(dtest))Why should the two classifiers below use the same test observations?
Question 7. Fit a classification tree
Fit a simple classification tree using three predictors, hms_medium_plus_days, tmax, and rh.
- Do not specify any
controloptions inrpart(). - Which predictor appears to play a larger role near the top of the tree?
class_tree <- rpart(
high_pm25 ~ hms_medium_plus_days + tmax + rh,
data = dtrain_class,
method = "class"
)
rpart.plot(class_tree, tweak = 0.9)
Question 8. Tuning
Fit a classification tree with the following hyperparameter settings:
cp = 0.0005minsplit = 30maxdepth = 5
Is the tuned tree more complex?
set.seed(320)
class_tree_tuned <- rpart(
high_pm25 ~ hms_medium_plus_days + tmax + rh,
data = dtrain_class,
method = "class",
control = rpart.control(cp = 0.0005, minsplit = 30, maxdepth = 5)
)
rpart.plot(class_tree_tuned, tweak = 0.85)
These settings are specified in advance for comparison, as in the DANL 320 exercise. If you search over settings, use training-data cross-validation to choose them before inspecting test performance.
Question 9. Classification
Build classifiers using the original and tuned classification trees. Compare them using the same test rows and a 0.5 probability threshold.
p_class <- predict(class_tree, newdata = dtest_class, type = "prob")[, "yes"]
p_tuned <- predict(class_tree_tuned, newdata = dtest_class, type = "prob")[, "yes"]
y_class <- factor(if_else(p_class >= 0.5, "yes", "no"), levels = c("no", "yes"))
y_tuned <- factor(if_else(p_tuned >= 0.5, "yes", "no"), levels = c("no", "yes"))
table(observed = dtest_class$high_pm25, predicted = y_class) predicted
observed no yes
no 5845 39
yes 1296 151
table(observed = dtest_class$high_pm25, predicted = y_tuned) predicted
observed no yes
no 5840 44
yes 1277 170
class_scores <- tibble(
model = c("Original classification tree", "Tuned classification tree"),
accuracy = c(mean(y_class == dtest_class$high_pm25),
mean(y_tuned == dtest_class$high_pm25)),
recall = c(mean(y_class[dtest_class$high_pm25 == "yes"] == "yes"),
mean(y_tuned[dtest_class$high_pm25 == "yes"] == "yes"))
)
class_scores |> paged_table()- Which tree has higher accuracy? Which detects a larger share of high-PM2.5 months?
- How do the numbers of false positives and false negatives change?
- Is the more complex tree necessarily better on the test rows?
- Compare both accuracies with the rule that always predicts the most common training class. Why can accuracy alone be misleading?
Discussion
Explain one decision-tree split, one reason for pruning, and one difference between regression and classification leaves. Bring the regression-tree results table to Class 4 so it can be compared with random forests using the same outcome and held-out rows.