Data Recreation (Friedman 1 Benchmark)
We recreate the simulated dataset from Exercise 7.2 using
mlbench.friedman1(200, sd = 1). The true underlying
data-generating function is:
\[ y = 10 \sin(\pi X_1 X_2) + 20 (X_3 - 0.5)^2 + 10 X_4 + 5 X_5 + \epsilon, \quad \epsilon \sim \mathcal{N}(0, 1) \]
where \(X_1, \dots, X_{10}
\stackrel{\text{i.i.d.}}{\sim} \text{Uniform}(0, 1)\). Thus,
predictors V1 through V5 are truly
informative, while V6 through V10 are pure
noise (uninformative).
set.seed(200)
simulated <- mlbench.friedman1(200, sd = 1)
simulated <- cbind(simulated$x, simulated$y)
simulated <- as.data.frame(simulated)
colnames(simulated)[ncol(simulated)] <- "y"
kable(head(simulated, 5), digits = 3, caption = "First 5 Rows of Simulated Friedman 1 Dataset (n = 200, p = 10)") %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed"), full_width = FALSE)| V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 | y |
|---|---|---|---|---|---|---|---|---|---|---|
| 0.534 | 0.648 | 0.851 | 0.182 | 0.929 | 0.362 | 0.827 | 0.421 | 0.591 | 0.589 | 18.464 |
| 0.584 | 0.438 | 0.673 | 0.669 | 0.164 | 0.453 | 0.649 | 0.845 | 0.928 | 0.758 | 16.098 |
| 0.590 | 0.588 | 0.410 | 0.338 | 0.894 | 0.027 | 0.179 | 0.350 | 0.018 | 0.444 | 17.762 |
| 0.691 | 0.226 | 0.033 | 0.067 | 0.637 | 0.525 | 0.513 | 0.797 | 0.690 | 0.445 | 13.787 |
| 0.667 | 0.819 | 0.717 | 0.803 | 0.083 | 0.223 | 0.664 | 0.904 | 0.397 | 0.550 | 18.430 |
cforest &
varimp(conditional = TRUE/FALSE))Question (c): Use the cforest function
in the party package to fit a random forest model using
conditional inference trees. The party package function
varimp can calculate predictor importance. The
conditional argument toggles between the traditional
importance measure and the modified version described in Strobl et
al. (2007). Do these importances show the same pattern as the
traditional random forest model?
# Fit cforest models across all three datasets (0, 1, and 2 duplicates)
cf_ctrl <- party::cforest_unbiased(ntree = 400, mtry = 3)
set.seed(200)
cf_model1 <- party::cforest(y ~ ., data = simulated, controls = cf_ctrl)
cf_imp1_uncond <- party::varimp(cf_model1, conditional = FALSE)
cf_imp1_cond <- party::varimp(cf_model1, conditional = TRUE)
set.seed(200)
cf_model2 <- party::cforest(y ~ ., data = simulated_dup1, controls = cf_ctrl)
cf_imp2_uncond <- party::varimp(cf_model2, conditional = FALSE)
cf_imp2_cond <- party::varimp(cf_model2, conditional = TRUE)
set.seed(200)
cf_model3 <- party::cforest(y ~ ., data = simulated_dup2, controls = cf_ctrl)
cf_imp3_uncond <- party::varimp(cf_model3, conditional = FALSE)
cf_imp3_cond <- party::varimp(cf_model3, conditional = TRUE)
# Assemble comparison table
cf_table <- tibble(
Predictor = all_vars,
`Uncond (0 Dup)` = cf_imp1_uncond[all_vars],
`Uncond (1 Dup)` = cf_imp2_uncond[all_vars],
`Uncond (2 Dup)` = cf_imp3_uncond[all_vars],
`Cond (0 Dup)` = cf_imp1_cond[all_vars],
`Cond (1 Dup)` = cf_imp2_cond[all_vars],
`Cond (2 Dup)` = cf_imp3_cond[all_vars]
)
kable(cf_table, digits = 3, caption = "Conditional Inference Forest (cforest): Unconditional vs. Conditional Permutation Importance") %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed"), full_width = FALSE)| Predictor | Uncond (0 Dup) | Uncond (1 Dup) | Uncond (2 Dup) | Cond (0 Dup) | Cond (1 Dup) | Cond (2 Dup) |
|---|---|---|---|---|---|---|
| V1 | 7.493 | 5.635 | 4.653 | 4.416 | 2.631 | 1.649 |
| V2 | 5.809 | 5.244 | 5.202 | 4.456 | 3.858 | 3.594 |
| V3 | 0.015 | 0.079 | 0.040 | 0.096 | 0.067 | 0.108 |
| V4 | 6.874 | 5.809 | 5.625 | 5.123 | 4.565 | 4.522 |
| V5 | 1.972 | 1.622 | 1.488 | 1.246 | 1.099 | 1.095 |
| V6 | 0.010 | 0.038 | 0.054 | 0.027 | 0.042 | 0.001 |
| V7 | 0.006 | 0.011 | -0.005 | 0.038 | 0.018 | -0.031 |
| V8 | -0.021 | -0.067 | 0.000 | -0.016 | -0.018 | -0.025 |
| V9 | 0.029 | 0.028 | 0.077 | -0.016 | 0.005 | 0.038 |
| V10 | -0.037 | -0.095 | -0.048 | -0.045 | -0.068 | 0.031 |
| duplicate1 | NA | 3.381 | 2.798 | NA | 1.649 | 1.145 |
| duplicate2 | NA | NA | 2.296 | NA | NA | 0.794 |
# Visualize Unconditional vs Conditional across 0, 1, 2 duplicates
cf_long <- cf_table %>%
pivot_longer(cols = -Predictor, names_to = "Setting", values_to = "Importance") %>%
filter(!is.na(Importance)) %>%
separate(Setting, into = c("Type", "Duplicates"), sep = " \\(") %>%
mutate(
Duplicates = str_remove(Duplicates, "\\)"),
Type = ifelse(Type == "Uncond", "Traditional Permutation (conditional = FALSE)", "Strobl Conditional Permutation (conditional = TRUE)"),
Duplicates = factor(Duplicates, levels = c("0 Dup", "1 Dup", "2 Dup"))
)
p81c <- ggplot(cf_long, aes(x = reorder(Predictor, Importance, FUN = max), y = Importance, fill = Duplicates)) +
geom_col(position = position_dodge(width = 0.8), width = 0.72) +
coord_flip() +
facet_wrap(~ Type, scales = "free_x") +
scale_fill_manual(values = c("#117864", "#45B39D", "#A3E4D7")) +
labs(
title = "Exercise 8.1(c): cforest Variable Importance (Unconditional vs. Strobl Conditional)",
subtitle = "Conditional permutation (right) penalizes collinearity even more aggressively than traditional permutation",
x = "Predictor",
y = "cforest Permutation Importance",
fill = "Collinearity Level"
)
print(p81c)conditional = FALSE and conditional = TRUE:
conditional = FALSE and conditional = TRUE,
cforest clearly identifies V1–V5
as important and assigns near-zero scores to
V6–V10.conditional = FALSE): Mirrors traditional
randomForest almost identically. Adding
duplicate1 and duplicate2 splits
V1’s importance across the correlated copies
(V1 drops from \(7.49\) to
\(5.64\) with 1 duplicate, and \(4.65\) with 2 duplicates).conditional = TRUE,
Strobl et al., 2007): Evaluates permutation importance of a
predictor within strata defined by correlated predictors (conditioning
on correlated covariates so that permuting V1 only permutes
values conditional on duplicate1 and
duplicate2). Because V1,
duplicate1, and duplicate2 carry nearly
identical information (\(r \approx
0.995\)), conditioning on the duplicates leaves almost no
independent variation in V1. Consequently, conditional
permutation importance shrinks the individual scores of all three
correlated variables much more dramatically (down to \(1.65\) for V1), pushing all
three below V4, V2, and even V5.
This reflects the true unique/conditional contribution of each variable
given the others in the model.gbm) and Rule-Based Models
(Cubist)Question (d): Repeat this process with different tree models, such as boosted trees and Cubist. Does the same pattern occur?
We evaluate four distinct model families across the 0-duplicate, 1-duplicate, and 2-duplicate datasets to provide a comprehensive comparison:
gbm)Cubist)ipred::bagging)rpart)fit_other_trees <- function(df, label) {
# 1. Stochastic Gradient Boosting (gbm)
set.seed(200)
gbm_mod <- gbm(
y ~ .,
data = df,
distribution = "gaussian",
n.trees = 1000,
interaction.depth = 3,
shrinkage = 0.01,
bag.fraction = 0.5,
verbose = FALSE
)
gbm_imp <- summary(gbm_mod, plotit = FALSE)
gbm_vec <- setNames(gbm_imp$rel.inf, gbm_imp$var)
# 2. Cubist Model
set.seed(200)
x_df <- df %>% select(-y)
cub_mod <- cubist(x = x_df, y = df$y, committees = 20)
cub_imp <- varImp(cub_mod)
cub_vec <- setNames(cub_imp$Overall, rownames(cub_imp))
# 3. Bagged Trees (caret treebag)
set.seed(200)
bag_mod <- train(y ~ ., data = df, method = "treebag", nbagg = 100, trControl = trainControl(method = "none"))
bag_imp <- varImp(bag_mod, scale = FALSE)$importance
bag_vec <- setNames(bag_imp$Overall, rownames(bag_imp))
# 4. Single CART Tree (rpart)
set.seed(200)
rpart_mod <- rpart(y ~ ., data = df, method = "anova")
rpart_imp <- rpart_mod$variable.importance
tibble(
Dataset = label,
Predictor = all_vars,
GBM = gbm_vec[all_vars],
Cubist = cub_vec[all_vars],
Bagged_Tree = bag_vec[all_vars],
Single_CART = rpart_imp[all_vars]
)
}
res_0 <- fit_other_trees(simulated, "0 Duplicates")
res_1 <- fit_other_trees(simulated_dup1, "1 Duplicate")
res_2 <- fit_other_trees(simulated_dup2, "2 Duplicates")
other_trees_all <- bind_rows(res_0, res_1, res_2)
gbm_wide <- other_trees_all %>%
select(Dataset, Predictor, GBM) %>%
pivot_wider(names_from = Dataset, values_from = GBM)
cubist_wide <- other_trees_all %>%
select(Dataset, Predictor, Cubist) %>%
pivot_wider(names_from = Dataset, values_from = Cubist)
kable(gbm_wide, digits = 2, caption = "Stochastic Gradient Boosting (GBM) Relative Influence Across Collinearity Levels") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)| Predictor | 0 Duplicates | 1 Duplicate | 2 Duplicates |
|---|---|---|---|
| V1 | 26.64 | 20.07 | 20.07 |
| V2 | 21.98 | 21.68 | 21.68 |
| V3 | 7.69 | 7.43 | 7.43 |
| V4 | 28.40 | 28.26 | 28.26 |
| V5 | 11.73 | 11.71 | 11.71 |
| V6 | 0.98 | 0.97 | 0.97 |
| V7 | 1.08 | 1.05 | 1.05 |
| V8 | 0.44 | 0.50 | 0.50 |
| V9 | 0.56 | 0.56 | 0.56 |
| V10 | 0.51 | 0.42 | 0.42 |
| duplicate1 | NA | 7.35 | 7.35 |
| duplicate2 | NA | NA | 0.00 |
kable(cubist_wide, digits = 2, caption = "Cubist Variable Usage Importance Across Collinearity Levels") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)| Predictor | 0 Duplicates | 1 Duplicate | 2 Duplicates |
|---|---|---|---|
| V1 | 72.0 | 72.0 | 72.0 |
| V2 | 54.5 | 57.0 | 57.0 |
| V3 | 42.0 | 42.0 | 42.0 |
| V4 | 49.0 | 49.0 | 49.0 |
| V5 | 40.0 | 37.5 | 37.5 |
| V6 | 0.0 | 0.0 | 0.0 |
| V7 | 0.0 | 0.0 | 0.0 |
| V8 | 0.0 | 0.0 | 0.0 |
| V9 | 0.0 | 0.0 | 0.0 |
| V10 | 0.0 | 0.0 | 0.0 |
| duplicate1 | NA | 0.0 | 0.0 |
| duplicate2 | NA | NA | 0.0 |
# Multi-panel visualization comparing GBM, Cubist, Bagged Trees, and Single CART
other_long <- other_trees_all %>%
pivot_longer(cols = c(GBM, Cubist, Bagged_Tree, Single_CART), names_to = "Model", values_to = "Importance") %>%
mutate(
Importance = replace_na(Importance, 0),
Dataset = factor(Dataset, levels = c("0 Duplicates", "1 Duplicate", "2 Duplicates")),
Model = recode(
Model,
"GBM" = "Gradient Boosting (GBM)",
"Cubist" = "Cubist (20 Committees)",
"Bagged_Tree" = "Bagged Trees (100 Trees)",
"Single_CART" = "Single CART Tree (rpart)"
)
)
p81d <- ggplot(other_long, aes(x = reorder(Predictor, Importance, FUN = max), y = Importance, fill = Dataset)) +
geom_col(position = position_dodge(width = 0.8), width = 0.72) +
coord_flip() +
facet_wrap(~ Model, scales = "free_x", ncol = 2) +
scale_fill_manual(values = c("#5B2C6F", "#9B59B6", "#D7BDE2")) +
labs(
title = "Exercise 8.1(d): Collinearity Effects Across Boosting, Cubist, Bagging, and Single CART",
subtitle = "Greedy/sequential models (GBM, Cubist, single trees) concentrate on one copy; bagging splits across copies",
x = "Predictor",
y = "Model-Specific Variable Importance",
fill = "Collinearity Level"
)
print(p81d)V6–V10) remain near zero and adding
correlated predictors reduces V1’s importance—but the way
importance is redistributed differs systematically by algorithm:
treebag): Uses all
predictors at every split (\(m_{\text{try}} =
p\)), so bootstrap sampling variation causes the trees to split
roughly evenly between V1, duplicate1, and
duplicate2, closely mirroring Random Forest dilution.gbm):
Because gbm fits trees sequentially to residuals (and uses
bag.fraction = 0.5 subsampling), V1 retains a
larger share of the importance than its duplicates (V1
drops from \(26.6\) to \(20.1\), while duplicate1 and
duplicate2 receive \(7.3\)
and \(0\)). Once an early tree splits
on V1 and reduces the residual gradient, subsequent trees
have less incentive to split on duplicate1 or
duplicate2.Cubist): Cubist combines
tree-based rule partitioning with smoothed linear regression models at
the terminal leaves, and varImp measures the percentage of
times a predictor is used in split conditions and/or linear models.
Because a single linear model inside a leaf only needs one
representative of a collinear group (or shares coefficients across
correlated terms), V1’s importance drops from \(72\) (0 duplicates) to \(72\) (1 duplicate) and \(72\) (2 duplicates), while
duplicate1 and duplicate2 absorb partial
usage.rpart): Exhibits the
most extreme greedy winner-take-all behavior—when V1 is
chosen at the root split, duplicate1 and
duplicate2 appear only as surrogate splits (or minor
secondary splits), receiving almost zero primary importance unless
random noise makes a duplicate marginally better at the root.Question 8.2: Use a simulation to show tree bias with different granularities.
Theoretical Background
Standard classification and regression trees (such as CART /
rpart) evaluate every possible split point across all
candidate predictors and select the split that maximizes reduction in
impurity (e.g., sum of squared errors, \(\text{SSE}\)). A predictor with \(k\) distinct ordered values admits \(k - 1\) possible binary split points,
whereas a binary predictor admits only 1 split point. Even when all
predictors are completely independent of the response \(Y\) (pure null simulation), a predictor
with higher cardinality/granularity has many more opportunities
(“multiple testing” / order-statistic advantage) to find a spurious
split that reduces training \(\text{SSE}\) purely by chance.
Monte Carlo Simulation Design
We construct a null simulation (\(N = 200\) observations, \(B = 500\) Monte Carlo replications) where the response \(Y \sim \mathcal{N}(0, 1)\) is strictly independent of five predictors engineered to span a spectrum of granularities:
X1_Binary: Discrete uniform over \(\{1, 2\}\) (\(2\) unique values \(\rightarrow 1\) candidate split)X2_LowGran: Discrete uniform over \(\{1, 2, 3, 4, 5\}\) (\(5\) unique values \(\rightarrow 4\) candidate splits)X3_MedGran: Discrete uniform over \(\{1, \dots, 20\}\) (\(20\) unique values \(\rightarrow 19\) candidate splits)X4_HighGran: Discrete uniform over \(\{1, \dots, 100\}\) (\(100\) unique values \(\rightarrow 99\) candidate splits)X5_Continuous: Continuous \(\text{Uniform}(0, 1)\) (\(200\) unique values \(\rightarrow 199\) candidate splits)In each of the 500 replications, we record:
rpart),partykit::ctree), which separates variable selection (via
permutation \(p\)-values adjusted for
multiplicity) from split-point selection.set.seed(802)
n_sim <- 500
n_obs <- 200
root_choice_rpart <- character(n_sim)
root_choice_ctree <- character(n_sim)
imp_matrix_rpart <- matrix(0, nrow = n_sim, ncol = 5)
colnames(imp_matrix_rpart) <- c("X1_Binary (2)", "X2_LowGran (5)", "X3_MedGran (20)", "X4_HighGran (100)", "X5_Continuous (200)")
for (i in seq_len(n_sim)) {
sim_df <- data.frame(
y = rnorm(n_obs),
`X1_Binary (2)` = sample(1:2, n_obs, replace = TRUE),
`X2_LowGran (5)` = sample(1:5, n_obs, replace = TRUE),
`X3_MedGran (20)` = sample(1:20, n_obs, replace = TRUE),
`X4_HighGran (100)` = sample(1:100, n_obs, replace = TRUE),
`X5_Continuous (200)` = runif(n_obs),
check.names = FALSE
)
# 1. Standard CART tree (rpart) forced to make at least one split (cp = 0)
fit_rp <- rpart(
y ~ .,
data = sim_df,
method = "anova",
control = rpart.control(cp = 0, minsplit = 10, maxdepth = 4)
)
root_choice_rpart[i] <- as.character(fit_rp$frame$var[1])
if (!is.null(fit_rp$variable.importance)) {
matched <- intersect(names(fit_rp$variable.importance), colnames(imp_matrix_rpart))
imp_matrix_rpart[i, matched] <- fit_rp$variable.importance[matched]
}
# 2. Conditional Inference Tree (ctree) with alpha = 1.0 to force a root split
fit_ct <- partykit::ctree(
y ~ .,
data = sim_df,
control = partykit::ctree_control(alpha = 1.0, minsplit = 10, maxdepth = 1)
)
root_idx <- partykit::split_node(partykit::node_party(fit_ct))$varid
root_choice_ctree[i] <- names(sim_df)[root_idx]
}
granularity_levels <- c("X1_Binary (2)", "X2_LowGran (5)", "X3_MedGran (20)", "X4_HighGran (100)", "X5_Continuous (200)")
bias_summary <- tibble(
Predictor = factor(granularity_levels, levels = granularity_levels),
`Unique Values` = c(2, 5, 20, 100, 200),
`Candidate Splits` = c(1, 4, 19, 99, 199),
`CART Root Selection (%)` = as.numeric(table(factor(root_choice_rpart, levels = granularity_levels))) / n_sim * 100,
`CART Mean Importance` = colMeans(imp_matrix_rpart),
`ctree Root Selection (%)` = as.numeric(table(factor(root_choice_ctree, levels = granularity_levels))) / n_sim * 100
)
kable(bias_summary, digits = 2, caption = "Null Simulation Results (500 Replications): CART Selection Bias vs. Unbiased Conditional Inference Trees") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)| Predictor | Unique Values | Candidate Splits | CART Root Selection (%) | CART Mean Importance | ctree Root Selection (%) |
|---|---|---|---|---|---|
| X1_Binary (2) | 2 | 1 | 2.0 | 1.81 | 19.4 |
| X2_LowGran (5) | 5 | 4 | 4.6 | 4.73 | 15.4 |
| X3_MedGran (20) | 20 | 19 | 21.6 | 9.27 | 23.2 |
| X4_HighGran (100) | 100 | 99 | 33.6 | 14.55 | 19.6 |
| X5_Continuous (200) | 200 | 199 | 38.2 | 17.79 | 22.4 |
# Dual-panel visualization
p82_left <- bias_summary %>%
select(
Predictor,
`CART (Greedy Exhaustive Search)` = `CART Root Selection (%)`,
`ctree (Unbiased Permutation Test)` = `ctree Root Selection (%)`
) %>%
pivot_longer(cols = -Predictor, names_to = "Algorithm", values_to = "Selection_Pct") %>%
ggplot(aes(x = Predictor, y = Selection_Pct, fill = Algorithm)) +
geom_col(position = position_dodge(width = 0.75), width = 0.68) +
geom_hline(yintercept = 20, linetype = "dashed", color = "gray30", linewidth = 0.8) +
annotate(
"text",
x = 0.6, y = 21.5,
label = "Unbiased Expected Rate (20%)",
hjust = 0, size = 3.2, color = "gray25"
) +
scale_fill_manual(values = c(
"CART (Greedy Exhaustive Search)" = "#C0392B",
"ctree (Unbiased Permutation Test)" = "#27AE60"
)) +
labs(
title = str_wrap("A. Root Split Selection Rate Under Complete Noise", width = 34),
subtitle = str_wrap("CART favors high-granularity predictors; ctree stays near 20%", width = 44),
x = "Predictor (Number of Unique Levels)",
y = "Root Node Selection Frequency (%)",
fill = "Tree Algorithm"
) +
theme(
plot.title = element_text(size = 11.5),
plot.subtitle = element_text(size = 9.5),
axis.text.x = element_text(angle = 22, hjust = 1),
plot.margin = ggplot2::margin(t = 8, r = 12, b = 8, l = 8)
)
p82_right <- as_tibble(imp_matrix_rpart) %>%
pivot_longer(cols = everything(), names_to = "Predictor", values_to = "Importance") %>%
mutate(Predictor = factor(Predictor, levels = granularity_levels)) %>%
ggplot(aes(x = Predictor, y = Importance, fill = Predictor)) +
geom_boxplot(alpha = 0.85, outlier.alpha = 0.3, show.legend = FALSE) +
scale_fill_brewer(palette = "Reds") +
labs(
title = str_wrap("B. Distribution of CART Variable Importance", width = 34),
subtitle = str_wrap("Monotonic inflation of spurious importance with predictor granularity", width = 44),
x = "Predictor (Number of Unique Levels)",
y = "Spurious Variable Importance (SSE Reduction)"
) +
theme(
plot.title = element_text(size = 11.5),
plot.subtitle = element_text(size = 9.5),
axis.text.x = element_text(angle = 22, hjust = 1),
plot.margin = ggplot2::margin(t = 8, r = 8, b = 8, l = 12)
)
combined_p82 <- (p82_left + p82_right) +
plot_layout(guides = "collect") &
theme(legend.position = "bottom")
print(combined_p82)rpart) exhibits
severe selection bias toward predictors with higher granularity:
X1_Binary (2 unique values, 1 split) is chosen at the
root node only \(2\%\) of the
time.X2_LowGran (5 unique values, 4 splits) is chosen \(4.6\%\) of the time.X4_HighGran (100 unique values, 99 splits) and
X5_Continuous (200 unique values, 199 splits) together
account for \(71.8\%\) of all root
splits!ctree) eliminate this bias by first
testing the global null hypothesis of independence via permutation \(p\)-values (selecting each predictor near
the ideal \(20\%\) benchmark) before
choosing a split point.Question 8.3: In stochastic gradient boosting, the
bagging fraction and learning rate govern the construction of the trees
as they are guided by the gradient. Figure 8.24 provides variable
importance plots for boosting using two extreme values for the bagging
fraction (0.1 and 0.9) and learning rate
(0.1 and 0.9) on the solubility data:
Why does the model on the right focus its importance on just the first few predictors, whereas the model on the left spreads importance across more predictors?
Which model do you think would be more predictive of other samples?
How would increasing interaction depth affect the slope of predictor importance for either model in Fig. 8.24?
solubility)To ground our theoretical explanations in empirical evidence, we load
the solubility dataset from
AppliedPredictiveModeling and reproduce the exact
stochastic gradient boosting comparison
(bag.fraction = 0.1, shrinkage = 0.1
vs. bag.fraction = 0.9, shrinkage = 0.9), as well as
examine the effect of interaction.depth and out-of-sample
test RMSE.
data(solubility)
set.seed(803)
gbm_low <- gbm(
y ~ .,
data = cbind(solTrainXtrans, y = solTrainY),
distribution = "gaussian",
n.trees = 100,
interaction.depth = 3,
shrinkage = 0.1,
bag.fraction = 0.1,
verbose = FALSE
)
set.seed(803)
gbm_high <- gbm(
y ~ .,
data = cbind(solTrainXtrans, y = solTrainY),
distribution = "gaussian",
n.trees = 100,
interaction.depth = 3,
shrinkage = 0.9,
bag.fraction = 0.9,
verbose = FALSE
)
# Deeper interaction models (interaction.depth = 7) to demonstrate Part (c)
set.seed(803)
gbm_low_deep <- gbm(
y ~ .,
data = cbind(solTrainXtrans, y = solTrainY),
distribution = "gaussian",
n.trees = 100,
interaction.depth = 7,
shrinkage = 0.1,
bag.fraction = 0.1,
verbose = FALSE
)
set.seed(803)
gbm_high_deep <- gbm(
y ~ .,
data = cbind(solTrainXtrans, y = solTrainY),
distribution = "gaussian",
n.trees = 100,
interaction.depth = 7,
shrinkage = 0.9,
bag.fraction = 0.9,
verbose = FALSE
)
# Evaluate out-of-sample test set RMSE
pred_low <- predict(gbm_low, newdata = solTestXtrans, n.trees = 100)
pred_high <- predict(gbm_high, newdata = solTestXtrans, n.trees = 100)
rmse_low <- RMSE(pred_low, solTestY)
rmse_high <- RMSE(pred_high, solTestY)
# Extract top 15 predictors for each model
imp_low_df <- summary(gbm_low, plotit = FALSE) %>%
slice_head(n = 15) %>%
mutate(Model = "Left: Bagging = 0.1, Shrinkage = 0.1 (Depth = 3)")
imp_high_df <- summary(gbm_high, plotit = FALSE) %>%
slice_head(n = 15) %>%
mutate(Model = "Right: Bagging = 0.9, Shrinkage = 0.9 (Depth = 3)")
imp_low_deep_df <- summary(gbm_low_deep, plotit = FALSE) %>%
slice_head(n = 15) %>%
mutate(Model = "Left (Deep): Bagging = 0.1, Shrinkage = 0.1 (Depth = 7)")
imp_high_deep_df <- summary(gbm_high_deep, plotit = FALSE) %>%
slice_head(n = 15) %>%
mutate(Model = "Right (Deep): Bagging = 0.9, Shrinkage = 0.9 (Depth = 7)")
p83_a <- ggplot(imp_low_df, aes(x = reorder(var, rel.inf), y = rel.inf)) +
geom_col(fill = "#2874A6", width = 0.7) +
coord_flip() +
labs(
title = sprintf("Bagging = 0.1, Learning Rate = 0.1\n(Test RMSE = %.3f)", rmse_low),
x = NULL,
y = "Relative Influence (%)"
)
p83_b <- ggplot(imp_high_df, aes(x = reorder(var, rel.inf), y = rel.inf)) +
geom_col(fill = "#B03A2E", width = 0.7) +
coord_flip() +
labs(
title = sprintf("Bagging = 0.9, Learning Rate = 0.9\n(Test RMSE = %.3f)", rmse_high),
x = NULL,
y = "Relative Influence (%)"
)
print(p83_a + p83_b)# Rank-decay curve showing how interaction depth flattens the importance slope (Part c)
rank_decay <- bind_rows(imp_low_df, imp_high_df, imp_low_deep_df, imp_high_deep_df) %>%
group_by(Model) %>%
mutate(Rank = row_number()) %>%
ungroup()
p83_c <- ggplot(rank_decay, aes(x = Rank, y = rel.inf, color = Model, linetype = str_detect(Model, "Deep"))) +
geom_line(linewidth = 1.1) +
geom_point(size = 2) +
scale_linetype_manual(values = c("FALSE" = "solid", "TRUE" = "dashed"), labels = c("Depth = 3", "Depth = 7")) +
labs(
title = "Exercise 8.3(c): Effect of Interaction Depth on Variable Importance Slope",
subtitle = "Increasing interaction depth allows more splits per tree, flattening the importance decay curve",
x = "Predictor Importance Rank (1 = Most Important)",
y = "Relative Influence (%)",
color = "Model Configuration",
linetype = "Tree Complexity"
)
print(p83_c)Part (a): Why does the model on the right focus its importance on just the first few predictors, whereas the model on the left spreads importance across more predictors?
Two synergistic mechanisms explain why setting
bag.fraction = 0.9 and shrinkage = 0.9
concentrates importance on only the top few variables
(NumCarbon, MolWeight,
SurfaceArea2), whereas 0.1 / 0.1
distributes importance broadly across dozens of predictors:
shrinkage = 0.9):
With a large learning rate (\(\lambda =
0.9\)), the very first few trees take massive steps down the
negative gradient, aggressively fitting \(90\%\) of the dominant signal in the
training response using only the single strongest predictors
(NumCarbon, MolWeight). Subsequent trees are
then left to fit tiny, noisy pseudo-residuals, contributing very little
total reduction in loss (and thus little variable importance).
Conversely, a small learning rate (\(\lambda =
0.1\)) shrinks each tree’s contribution by \(90\%\), forcing the ensemble to build many
gradual, incremental trees over many iterations, giving secondary and
correlated predictors repeated opportunities to contribute.bag.fraction = 0.9): Sampling \(90\%\) of the training set at each
iteration produces nearly identical subsamples across boosting
iterations. As a result, the exact same dominant predictors win the top
splits in almost every tree (low tree-to-tree diversity). By contrast, a
small bagging fraction (bag.fraction = 0.1) draws small,
highly varied \(10\%\) subsamples at
each iteration, introducing substantial stochastic perturbation so
different subsets of predictors appear optimal across different
iterations.Part (b): Which model do you think would be more predictive of other samples?
bag.fraction = 0.1, shrinkage = 0.1) is substantially more
predictive of new, unseen samples (confirmed empirically above, where
Test RMSE is \(0.707\) for
0.1 / 0.1 vs. \(0.684\) for 0.9 /
0.9).shrinkage \(\le 0.1\)) and using moderate subsampling
(bag.fraction \(\approx
0.5\)) dramatically improves generalization performance.Part (c): How would increasing interaction depth affect the slope of predictor importance for either model in Fig. 8.24?
interaction.depth (tree depth) makes the
slope of the variable importance curve flatter (less steep), spreading
importance across a larger number of predictors.interaction.depth controls
the maximum number of splits (terminal nodes minus one) grown in each
individual tree. When interaction.depth is small (e.g.,
\(1\) or \(2\)), each tree can only split on the 1 or
2 strongest predictors before stopping. When
interaction.depth is increased, each tree grows deeper and
is forced to make additional secondary and tertiary splits within the
partitioned subgroups—where the primary predictors have already been
split upon—thereby recruiting secondary predictors and interaction
partners into the tree and distributing relative influence more evenly
across the predictor set (as illustrated by the dashed lines in the
rank-decay plot above).Question 8.7: Refer to Exercises 6.3 and 7.5 which describe a chemical manufacturing process. Use the same data imputation, data splitting, and pre-processing steps as before and train several tree-based models:
Which tree-based regression model gives the optimal resampling and test set performance?
Which predictors are most important in the optimal tree-based regression model? Do either the biological or process variables dominate the list? How do the top 10 important predictors compare to the top 10 predictors from the optimal linear and nonlinear models?
Plot the optimal single tree with the distribution of yield in the terminal nodes. Does this view of the data provide additional knowledge about the biological or process predictors and their relationship with yield?
Following Kuhn & Johnson’s exact workflow from Exercises 6.3 and
7.5 on ChemicalManufacturingProcess:
set.seed(100) and
createDataPartition(Yield, p = 0.80, list = FALSE).preProcess fit
strictly on training data to prevent data leakage):
knnImpute (\(k\)-nearest neighbors imputation for
missing values),nzv (removal of near-zero variance predictors),center and scale
(standardization—invariant for monotonic tree splits while ensuring
exact consistency with the linear and nonlinear models from Chapters 6
& 7).data(ChemicalManufacturingProcess)
# Exact 80/20 stratified split matching Exercises 6.3 and 7.5
set.seed(100)
train_idx <- createDataPartition(ChemicalManufacturingProcess$Yield, p = 0.80, list = FALSE)
train_raw <- ChemicalManufacturingProcess[train_idx, ]
test_raw <- ChemicalManufacturingProcess[-train_idx, ]
# Fit preProcess strictly on training predictors (knnImpute + nzv + center + scale)
pp_chem <- preProcess(
train_raw %>% select(-Yield),
method = c("knnImpute", "nzv", "center", "scale")
)
train_x <- predict(pp_chem, train_raw %>% select(-Yield))
test_x <- predict(pp_chem, test_raw %>% select(-Yield))
train_y <- train_raw$Yield
test_y <- test_raw$Yield
prep_summary <- tibble(
`Total Samples` = nrow(ChemicalManufacturingProcess),
`Training Samples (80%)` = nrow(train_x),
`Test Samples (20%)` = nrow(test_x),
`Original Predictors` = ncol(train_raw) - 1,
`Retained Predictors (Post-NZV)` = ncol(train_x),
`Missing Values Imputed` = sum(is.na(ChemicalManufacturingProcess))
)
kable(prep_summary, caption = "Chemical Manufacturing Process: Data Splitting & Pre-Processing Summary") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)| Total Samples | Training Samples (80%) | Test Samples (20%) | Original Predictors | Retained Predictors (Post-NZV) | Missing Values Imputed |
|---|---|---|---|---|---|
| 176 | 144 | 32 | 57 | 56 | 106 |
We train and tune seven distinct tree-based and rule-based regression models using identical 10-fold repeated cross-validation folds:
rpart) — tuned over
complexity parameter cpctree) —
tuned over mincriteriontreebag) — bootstrap
aggregated regression treesrf) — tuned over
mtry (ntree = 1000)cforest)
— tuned over mtrygbm) —
tuned over n.trees, interaction.depth,
shrinkage, and n.minobsinnodecubist) —
tuned over committees and neighbors# 1. Single CART Tree (rpart)
set.seed(100)
fit_rpart <- train(
x = train_x, y = train_y,
method = "rpart",
tuneLength = 15,
trControl = cv_ctrl
)
# 2. Conditional Inference Tree (ctree)
set.seed(100)
fit_ctree <- train(
x = train_x, y = train_y,
method = "ctree",
tuneLength = 10,
trControl = cv_ctrl
)
# 3. Bagged Trees (treebag)
set.seed(100)
fit_treebag <- train(
x = train_x, y = train_y,
method = "treebag",
nbagg = 100,
trControl = cv_ctrl
)
# 4. Random Forest (rf)
set.seed(100)
rf_grid <- expand.grid(mtry = c(5, 10, 15, 20, 28, 40, 56))
fit_rf <- train(
x = train_x, y = train_y,
method = "rf",
tuneGrid = rf_grid,
ntree = 1000,
importance = TRUE,
trControl = cv_ctrl
)
# 5. Conditional Inference Forest (cforest)
set.seed(100)
cf_grid <- expand.grid(mtry = c(5, 15, 30, 50))
fit_cforest <- train(
x = train_x, y = train_y,
method = "cforest",
tuneGrid = cf_grid,
controls = party::cforest_unbiased(ntree = 300),
trControl = cv_ctrl
)
# 6. Stochastic Gradient Boosting (gbm)
set.seed(100)
gbm_grid <- expand.grid(
interaction.depth = c(1, 3, 5),
n.trees = c(100, 300, 500),
shrinkage = c(0.01, 0.05, 0.1),
n.minobsinnode = c(5, 10)
)
fit_gbm <- train(
x = train_x, y = train_y,
method = "gbm",
tuneGrid = gbm_grid,
verbose = FALSE,
trControl = cv_ctrl
)
# 7. Cubist Rule-Based Model (cubist)
set.seed(100)
cubist_grid <- expand.grid(
committees = c(1, 5, 10, 20, 50),
neighbors = c(0, 1, 3, 5, 7, 9)
)
fit_cubist <- train(
x = train_x, y = train_y,
method = "cubist",
tuneGrid = cubist_grid,
trControl = cv_ctrl
)
# Compile Resampling (CV) and Test Set Performance Metrics
tree_models <- list(
"Cubist" = fit_cubist,
"Random Forest" = fit_rf,
"Stochastic Gradient Boosting (GBM)" = fit_gbm,
"Conditional Inference Forest (cforest)" = fit_cforest,
"Bagged Trees (treebag)" = fit_treebag,
"Single CART Tree (rpart)" = fit_rpart,
"Conditional Inference Tree (ctree)" = fit_ctree
)
perf_table <- map_dfr(names(tree_models), function(m_name) {
mod <- tree_models[[m_name]]
best_res <- mod$results %>%
inner_join(mod$bestTune, by = names(mod$bestTune))
preds <- predict(mod, newdata = test_x)
test_metrics <- postResample(pred = preds, obs = test_y)
tibble(
Model = m_name,
`CV RMSE` = best_res$RMSE[1],
`CV RMSE SD` = best_res$RMSESD[1],
`CV R2` = best_res$Rsquared[1],
`Test RMSE` = test_metrics["RMSE"],
`Test R2` = test_metrics["Rsquared"],
`Test MAE` = test_metrics["MAE"]
)
}) %>%
arrange(`Test RMSE`)
kable(perf_table, digits = 4, caption = "Exercise 8.7(a): Resampling (10-Fold Repeated CV) and Test Set Performance Across Tree Models") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)| Model | CV RMSE | CV RMSE SD | CV R2 | Test RMSE | Test R2 | Test MAE |
|---|---|---|---|---|---|---|
| Cubist | 1.0394 | 0.2937 | 0.6957 | 0.7567 | 0.7957 | 0.6176 |
| Stochastic Gradient Boosting (GBM) | 1.1140 | 0.1933 | 0.6461 | 0.8409 | 0.7550 | 0.6868 |
| Random Forest | 1.1112 | 0.2008 | 0.6734 | 0.9958 | 0.6622 | 0.8442 |
| Bagged Trees (treebag) | 1.2144 | 0.2286 | 0.5921 | 1.0829 | 0.5753 | 0.9074 |
| Conditional Inference Forest (cforest) | 1.2664 | 0.2696 | 0.5681 | 1.0979 | 0.5628 | 0.9033 |
| Single CART Tree (rpart) | 1.4716 | 0.3135 | 0.4200 | 1.2865 | 0.4093 | 1.0280 |
| Conditional Inference Tree (ctree) | 1.4492 | 0.3107 | 0.4344 | 1.2975 | 0.4410 | 1.0950 |
# Resampling distribution comparison plot
resamps <- resamples(tree_models)
resamp_df <- resamps$values %>%
select(Resample, ends_with("~RMSE")) %>%
pivot_longer(cols = -Resample, names_to = "Model", values_to = "RMSE") %>%
mutate(Model = str_remove(Model, "~RMSE"))
p87a_cv <- ggplot(resamp_df, aes(x = reorder(Model, RMSE, FUN = median), y = RMSE, fill = Model)) +
geom_boxplot(alpha = 0.85, show.legend = FALSE) +
coord_flip() +
scale_fill_brewer(palette = "Set2") +
labs(
title = "A. Cross-Validation RMSE Distribution (20 Resamples)",
subtitle = "Cubist and Random Forest achieve the lowest resampling error",
x = NULL,
y = "Resampling RMSE"
)
p87a_test <- perf_table %>%
select(Model, `CV RMSE`, `Test RMSE`) %>%
pivot_longer(cols = c(`CV RMSE`, `Test RMSE`), names_to = "Split", values_to = "RMSE") %>%
ggplot(aes(x = reorder(Model, RMSE, FUN = min), y = RMSE, fill = Split)) +
geom_col(position = position_dodge(width = 0.75), width = 0.68) +
coord_flip() +
scale_fill_manual(values = c("CV RMSE" = "#34495E", "Test RMSE" = "#E67E22")) +
labs(
title = "B. CV vs. Hold-Out Test RMSE",
subtitle = "Ensemble/rule models substantially outperform single trees",
x = NULL,
y = "RMSE",
fill = "Evaluation Set"
)
print(p87a_cv + p87a_test)CV RMSE \(= 1.0394\),
Test RMSE \(= 0.7567\),
Test R2 \(= 0.7957\)),
followed closely by Random Forest and Stochastic Gradient Boosting
(gbm).rpart, rf,
gbm) that approximate continuous linear trends with
piecewise-constant step functions, Cubist fits multivariate linear
regression models inside its terminal leaves (combined with committee
boosting and instance-based neighbor adjustments). Because chemical
manufacturing yield depends on continuous, approximately linear
relationships with key process settings (captured well by PLS/Elastic
Net in Chapter 6), Cubist combines the local regime-switching
flexibility of trees with smooth linear extrapolation inside each
operating regime.rpart and ctree)
suffer from high variance and coarse step-function approximation,
yielding the highest resampling and test errors.Question (b): Which predictors are most important in the optimal tree-based regression model? Do either the biological or process variables dominate the list? How do the top 10 important predictors compare to the top 10 predictors from the optimal linear and nonlinear models?
To make a direct, apples-to-apples comparison with Exercises 6.3 and
7.5 on the exact same training/test split and cross-validation folds, we
also fit the optimal linear model from Chapter 6 (Partial Least Squares
pls) and the optimal nonlinear model from Chapter 7
(Support Vector Machine with Radial Basis Function
svmRadial).
# Fit optimal Linear Model from Ex 6.3 (Partial Least Squares)
set.seed(100)
fit_pls <- train(
x = train_x, y = train_y,
method = "pls",
tuneGrid = expand.grid(ncomp = 1:15),
trControl = cv_ctrl
)
# Fit optimal Nonlinear Model from Ex 7.5 (Radial SVM)
set.seed(100)
fit_svm <- train(
x = train_x, y = train_y,
method = "svmRadial",
tuneLength = 10,
trControl = cv_ctrl
)
get_imp_tbl <- function(mod) {
raw_imp <- varImp(mod, scale = TRUE)$importance
if (is.data.frame(raw_imp) || is.matrix(raw_imp)) {
df <- as.data.frame(raw_imp)
tibble(
Predictor = as.character(rownames(df)),
Overall = as.numeric(df[[1]])
) %>%
arrange(desc(Overall))
} else {
tibble(
Predictor = as.character(names(raw_imp)),
Overall = as.numeric(raw_imp)
) %>%
arrange(desc(Overall))
}
}
imp_cubist <- get_imp_tbl(fit_cubist)
imp_rf <- get_imp_tbl(fit_rf)
imp_pls <- get_imp_tbl(fit_pls)
imp_svm <- get_imp_tbl(fit_svm)
top15_cubist <- imp_cubist %>%
slice_head(n = 15) %>%
mutate(
Category = ifelse(str_starts(Predictor, "ManufacturingProcess"), "Process Variable", "Biological Material")
)
kable(top15_cubist, digits = 2, caption = "Top 15 Most Important Predictors in Optimal Tree-Based Model (Cubist)") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)| Predictor | Overall | Category |
|---|---|---|
| ManufacturingProcess32 | 100.00 | Process Variable |
| ManufacturingProcess13 | 62.34 | Process Variable |
| BiologicalMaterial03 | 54.55 | Biological Material |
| ManufacturingProcess04 | 48.05 | Process Variable |
| ManufacturingProcess33 | 48.05 | Process Variable |
| ManufacturingProcess15 | 41.56 | Process Variable |
| ManufacturingProcess09 | 31.17 | Process Variable |
| BiologicalMaterial06 | 25.97 | Biological Material |
| BiologicalMaterial02 | 24.68 | Biological Material |
| ManufacturingProcess17 | 20.78 | Process Variable |
| BiologicalMaterial10 | 15.58 | Biological Material |
| BiologicalMaterial04 | 12.99 | Biological Material |
| BiologicalMaterial05 | 11.69 | Biological Material |
| ManufacturingProcess29 | 11.69 | Process Variable |
| ManufacturingProcess01 | 7.79 | Process Variable |
top10_comparison <- tibble(
Rank = 1:10,
`Optimal Tree (Cubist)` = head(imp_cubist$Predictor, 10),
`2nd Tree (Random Forest)` = head(imp_rf$Predictor, 10),
`Optimal Linear (PLS - Ex 6.3)` = head(imp_pls$Predictor, 10),
`Optimal Nonlinear (SVM - Ex 7.5)` = head(imp_svm$Predictor, 10)
)
kable(top10_comparison, caption = "Exercise 8.7(b): Comparison of Top 10 Predictors Across Tree, Linear, and Nonlinear Models") %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed"), full_width = FALSE)| Rank | Optimal Tree (Cubist) | 2nd Tree (Random Forest) | Optimal Linear (PLS - Ex 6.3) | Optimal Nonlinear (SVM - Ex 7.5) |
|---|---|---|---|---|
| 1 | ManufacturingProcess32 | ManufacturingProcess32 | ManufacturingProcess32 | ManufacturingProcess32 |
| 2 | ManufacturingProcess13 | ManufacturingProcess13 | ManufacturingProcess13 | ManufacturingProcess13 |
| 3 | BiologicalMaterial03 | BiologicalMaterial12 | ManufacturingProcess36 | BiologicalMaterial06 |
| 4 | ManufacturingProcess04 | BiologicalMaterial03 | ManufacturingProcess09 | ManufacturingProcess17 |
| 5 | ManufacturingProcess33 | BiologicalMaterial06 | ManufacturingProcess17 | BiologicalMaterial03 |
| 6 | ManufacturingProcess15 | ManufacturingProcess09 | ManufacturingProcess33 | ManufacturingProcess36 |
| 7 | ManufacturingProcess09 | BiologicalMaterial04 | BiologicalMaterial02 | BiologicalMaterial02 |
| 8 | BiologicalMaterial06 | ManufacturingProcess17 | BiologicalMaterial06 | ManufacturingProcess09 |
| 9 | BiologicalMaterial02 | BiologicalMaterial09 | ManufacturingProcess06 | BiologicalMaterial12 |
| 10 | ManufacturingProcess17 | BiologicalMaterial11 | BiologicalMaterial03 | ManufacturingProcess06 |
p87b <- ggplot(top15_cubist, aes(x = reorder(Predictor, Overall), y = Overall, fill = Category)) +
geom_col(width = 0.72) +
coord_flip() +
scale_fill_manual(values = c("Process Variable" = "#1F618D", "Biological Material" = "#D35400")) +
labs(
title = "Exercise 8.7(b): Top 15 Predictors in Optimal Tree Model (Cubist)",
subtitle = "Manufacturing Process variables dominate over Biological Materials",
x = NULL,
y = "Scaled Variable Importance (0–100)",
fill = "Variable Domain"
)
print(p87b)Cubist):
ManufacturingProcess32 is the #1 predictor
(Overall = 100), followed by
ManufacturingProcess13,
ManufacturingProcess09,
ManufacturingProcess17, and
BiologicalMaterial06 (see the Top 15 table above for the
exact ranking).Cubist/rf),
Linear (PLS), and Nonlinear
(SVM)—ManufacturingProcess32 is consistently
ranked #1, and core drivers such as ManufacturingProcess13,
ManufacturingProcess09,
ManufacturingProcess17, BiologicalMaterial06,
and BiologicalMaterial03 appear across the Top 10 lists of
every model family.PLS) and
smooth kernel (SVM) models rely heavily on global marginal
correlations, placing slightly more weight on correlated biological raw
material variables (BiologicalMaterial02,
BiologicalMaterial03, BiologicalMaterial06,
BiologicalMaterial12). In contrast, Cubist and
Random Forest elevate specific local process thresholds and
interaction variables (ManufacturingProcess31,
ManufacturingProcess06,
ManufacturingProcess36) that exhibit threshold or regime
effects on yield.Question (c): Plot the optimal single tree with the distribution of yield in the terminal nodes. Does this view of the data provide additional knowledge about the biological or process predictors and their relationship with yield?
To display the full distribution of Yield in every
terminal node (as shown in Kuhn & Johnson Figure 8.21 using
partykit), we convert the tuned rpart tree
(fit_rpart$finalModel) into a party object via
partykit::as.party().
# Convert optimal rpart tree to partykit object to plot terminal node boxplots
optimal_rpart_party <- partykit::as.party(fit_rpart$finalModel)
plot(
optimal_rpart_party,
main = "Exercise 8.7(c): Optimal Single CART Tree with Terminal Node Yield Distributions",
tp_args = list(fill = "#AED6F1", id = TRUE),
ip_args = list(id = TRUE),
gp = grid::gpar(fontsize = 9.5)
)# Inspect exact terminal node summary statistics (count, mean, median, IQR, SD)
terminal_nodes <- predict(optimal_rpart_party, type = "node")
node_stats <- tibble(
Terminal_Node = factor(terminal_nodes),
Yield = train_y
) %>%
group_by(Terminal_Node) %>%
summarise(
N = n(),
Mean_Yield = mean(Yield),
SD_Yield = sd(Yield),
Median_Yield = median(Yield),
IQR_Yield = IQR(Yield),
Min_Yield = min(Yield),
Max_Yield = max(Yield),
.groups = "drop"
) %>%
arrange(desc(Mean_Yield))
kable(node_stats, digits = 3, caption = "Summary Statistics of Yield Across Terminal Nodes of the Optimal Single Tree") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)| Terminal_Node | N | Mean_Yield | SD_Yield | Median_Yield | IQR_Yield | Min_Yield | Max_Yield |
|---|---|---|---|---|---|---|---|
| 17 | 10 | 43.495 | 1.263 | 43.265 | 1.457 | 42.23 | 46.34 |
| 14 | 10 | 42.058 | 1.446 | 42.245 | 1.970 | 39.77 | 43.88 |
| 16 | 14 | 41.750 | 0.970 | 41.995 | 1.345 | 39.96 | 43.38 |
| 13 | 17 | 41.084 | 0.828 | 41.000 | 1.050 | 39.74 | 42.73 |
| 8 | 17 | 40.837 | 1.023 | 40.640 | 1.300 | 39.17 | 43.12 |
| 12 | 10 | 39.462 | 1.102 | 39.630 | 0.938 | 36.83 | 40.89 |
| 7 | 29 | 39.120 | 0.731 | 39.140 | 1.110 | 37.86 | 40.41 |
| 5 | 29 | 38.748 | 0.944 | 38.660 | 1.300 | 37.39 | 40.66 |
| 4 | 8 | 36.998 | 0.922 | 37.220 | 1.122 | 35.25 | 37.94 |
# Scatterplot illustrating the primary threshold regime identified by the tree
root_split_val <- if (!is.null(fit_rpart$finalModel$splits)) {
fit_rpart$finalModel$splits[1, "index"]
} else {
NA_real_
}
p87c_scatter <- ggplot(
cbind(train_x, Yield = train_y),
aes(x = ManufacturingProcess32, y = Yield, color = ManufacturingProcess13)
) +
geom_point(size = 3, alpha = 0.85) +
scale_color_viridis_c(option = "plasma") +
labs(
title = "Relationship Revealed by Optimal Single Tree Splits",
subtitle = "Higher ManufacturingProcess32 (right of dashed root split) and lower ManufacturingProcess13 yield higher output",
x = "ManufacturingProcess32 (Standardized)",
y = "Chemical Yield",
color = "ManufacturingProcess13\n(Standardized)"
)
if (!is.na(root_split_val)) {
p87c_scatter <- p87c_scatter +
geom_vline(
xintercept = root_split_val,
linetype = "dashed",
color = "#C0392B",
linewidth = 1
)
}
print(p87c_scatter)ManufacturingProcess32
(right branch of the root split) consistently achieve substantially
higher yields than runs with lower ManufacturingProcess32
(left branch). Secondary splits (ManufacturingProcess13,
BiologicalMaterial03 / BiologicalMaterial06,
ManufacturingProcess17) further partition runs into
high-yield vs. low-yield operating regimes.BiologicalMaterial03 / 06) exert their
strongest positive impact conditionally when
ManufacturingProcess32 is already operating above its
critical threshold—an interaction effect that linear models
obscure.