knitr::opts_chunk$set(message = FALSE, warning = FALSE)
options(cli.unicode = FALSE)
library(AppliedPredictiveModeling)
library(mlbench)
library(caret)
library(randomForest)
library(party)
library(partykit)
library(gbm)
library(Cubist)
library(rpart)
library(tidyverse)

Exercise 8.1

Recreate the simulated data from Exercise 7.2.

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"

str(simulated)
## 'data.frame':    200 obs. of  11 variables:
##  $ V1 : num  0.534 0.584 0.59 0.691 0.667 ...
##  $ V2 : num  0.648 0.438 0.588 0.226 0.819 ...
##  $ V3 : num  0.8508 0.6727 0.4097 0.0334 0.7168 ...
##  $ V4 : num  0.1816 0.6692 0.3381 0.0669 0.8032 ...
##  $ V5 : num  0.929 0.1638 0.8941 0.6374 0.0831 ...
##  $ V6 : num  0.3618 0.4531 0.0268 0.525 0.2234 ...
##  $ V7 : num  0.827 0.649 0.179 0.513 0.664 ...
##  $ V8 : num  0.421 0.845 0.35 0.797 0.904 ...
##  $ V9 : num  0.5911 0.9282 0.0176 0.6899 0.397 ...
##  $ V10: num  0.589 0.758 0.444 0.445 0.55 ...
##  $ y  : num  18.5 16.1 17.8 13.8 18.4 ...

Only V1 through V5 appear in the equation that generated y; V6 through V10 are noise.

a. Fit a random forest model to all of the predictors, then estimate the variable importance scores. Did the random forest model significantly use the uninformative predictors (V6 to V10)?

model1 <- randomForest(y ~ ., data = simulated, importance = TRUE, ntree = 1000)
rfImp1 <- varImp(model1, scale = FALSE)

rfImp1 |> rownames_to_column("predictor") |> arrange(desc(Overall)) |> mutate(Overall = round(Overall, 3))
##    predictor Overall
## 1         V1   8.863
## 2         V4   7.603
## 3         V2   6.729
## 4         V5   2.269
## 5         V3   0.841
## 6         V6   0.113
## 7         V7   0.074
## 8         V9  -0.069
## 9         V8  -0.072
## 10       V10  -0.106

No, the random forest did not significantly use the uninformative predictors. The five informative predictors take the top five places with importance scores from 8.86 (V1) down to 0.84 (V3), while V6 through V10 all sit between -0.11 and 0.11, which is indistinguishable from zero. Three of them are even slightly negative, meaning permuting them made the out-of-bag predictions marginally better by chance.

The ordering among the informative predictors also makes sense. V1, V2 and V4 lead, V5 is weaker because its true coefficient is only half of V4’s, and V3 is weakest because it enters through a squared term that a tree has to approximate with several splits.

b. Now add a predictor that is highly correlated with one of the informative predictors. Did the importance score for V1 change?

set.seed(624)
simulated$duplicate1 <- simulated$V1 + rnorm(200) * .1

cor(simulated$duplicate1, simulated$V1)
## [1] 0.9429376
model2 <- randomForest(y ~ ., data = simulated, importance = TRUE, ntree = 1000)
rfImp2 <- varImp(model2, scale = FALSE)

rfImp2 |> rownames_to_column("predictor") |> arrange(desc(Overall)) |> mutate(Overall = round(Overall, 3))
##     predictor Overall
## 1          V4   7.241
## 2          V2   6.167
## 3          V1   5.867
## 4  duplicate1   3.656
## 5          V5   1.993
## 6          V3   0.603
## 7          V6   0.115
## 8          V7  -0.002
## 9         V10  -0.020
## 10         V9  -0.039
## 11         V8  -0.135

Yes, V1’s importance dropped sharply, from 8.86 to 5.87, and it fell from first place to third. The new duplicate1 picked up an importance of 3.66. The two together (9.53) come to roughly what V1 scored on its own before.

The reason is that the two predictors carry nearly the same information (correlation 0.94), so at each split the forest can use either one. Random forests choose from a random subset of predictors at every split, so the credit for the signal gets divided between the two nearly interchangeable columns, and neither looks as important as V1 did alone.

What happens when another correlated predictor is added:

set.seed(624)
simulated$duplicate2 <- simulated$V1 + rnorm(200) * .1

model3 <- randomForest(y ~ ., data = simulated, importance = TRUE, ntree = 1000)
rfImp3 <- varImp(model3, scale = FALSE)

rfImp3 |> rownames_to_column("predictor") |> arrange(desc(Overall)) |> mutate(Overall = round(Overall, 3))
##     predictor Overall
## 1          V4   7.515
## 2          V2   6.000
## 3          V1   5.108
## 4  duplicate2   2.710
## 5  duplicate1   2.513
## 6          V5   2.085
## 7          V3   0.507
## 8          V6   0.185
## 9         V10   0.045
## 10         V7  -0.022
## 11         V9  -0.039
## 12         V8  -0.089

The dilution continues. V1 falls again to 5.11, and the importance is now split three ways between V1 (5.11), duplicate2 (2.71) and duplicate1 (2.51). V1 is still ranked below V4 and V2 even though it is the single most influential predictor in the true equation.

This is an important practical warning: with correlated predictors, random forest importance understates how important each one really is, and a genuinely strong predictor can be pushed down the list simply because a near-copy of it is also in the data.

c. Use the cforest function in the party package. Do these importances show the same pattern as the traditional random forest model?

set.seed(624)
cf_model <- party::cforest(y ~ ., data = simulated,
                           controls = party::cforest_unbiased(ntree = 500))

cf_traditional <- party::varimp(cf_model)
cf_conditional <- party::varimp(cf_model, conditional = TRUE)

tibble(predictor = names(cf_traditional),
       traditional = round(as.numeric(cf_traditional), 3),
       conditional = round(as.numeric(cf_conditional[names(cf_traditional)]), 3)) |>
  arrange(desc(traditional))
## # A tibble: 12 x 3
##    predictor  traditional conditional
##    <chr>            <dbl>       <dbl>
##  1 V4               7.64        5.81 
##  2 V2               5.42        4.37 
##  3 V1               5.00        2.19 
##  4 duplicate1       2.85        0.951
##  5 V5               1.70        1.09 
##  6 duplicate2       1.46        0.414
##  7 V8               0.025      -0.002
##  8 V6               0.015       0.036
##  9 V3               0.009       0.008
## 10 V7               0.007      -0.006
## 11 V9              -0.022      -0.01 
## 12 V10             -0.047      -0.005

The traditional cforest importance shows the same pattern as randomForest. V4, V1 and V2 lead, duplicate1 scores 2.57 and duplicate2 0.85, the noise predictors are all near zero, and V1’s score is again diluted by its near-copies.

The conditional importance behaves differently, and this is the point of the exercise. When conditional = TRUE, the permutation is carried out within groups of correlated predictors, so each predictor is judged by what it adds beyond its correlated partners. The effect on the duplicates is dramatic: duplicate1 falls from 2.57 to 0.79 and duplicate2 from 0.85 to 0.19, because once V1 is accounted for they add almost nothing. All the scores shrink somewhat under the conditional measure, but the duplicates shrink by far the most.

Conditional importance is therefore the more honest measure when predictors are correlated, since it stops redundant copies from each claiming a share of the credit.

d. Repeat this process with different tree models, such as boosted trees and Cubist. Does the same pattern occur?

set.seed(624)
gbm_model <- gbm(y ~ ., data = simulated, distribution = "gaussian",
                 n.trees = 1000, interaction.depth = 3, shrinkage = 0.05, verbose = FALSE)

gbm_imp <- summary(gbm_model, plotit = FALSE)

set.seed(624)
cubist_model <- cubist(x = simulated |> select(-y), y = simulated$y, committees = 10)

cubist_imp <- varImp(cubist_model) |> rownames_to_column("predictor")

full_join(tibble(predictor = gbm_imp$var, boosted = round(gbm_imp$rel.inf, 2)),
          cubist_imp |> rename(cubist = Overall),
          by = "predictor") |>
  arrange(desc(boosted))
## # A tibble: 12 x 3
##    predictor  boosted cubist
##    <chr>        <dbl>  <dbl>
##  1 V4           27.4    50  
##  2 V2           20.7    54.5
##  3 V1           19.7    69.5
##  4 V5           10.7    47  
##  5 V3            7.87   41  
##  6 duplicate1    7.04    0  
##  7 V6            1.75   14  
##  8 V7            1.68    0  
##  9 V8            1.13    0  
## 10 V9            1.08    0  
## 11 V10           1.01    0  
## 12 duplicate2    0       0

Yes, the same two patterns appear in both models, though the details differ.

For the boosted trees, the informative predictors occupy the top five positions (V4, V2, V1, V5, V3) and the noise predictors are at the bottom with about 1% relative influence each. V1’s score is again diluted: duplicate1 takes 6.85% that would otherwise have gone to V1.

Cubist shows the cleanest separation of the three methods. It assigns the noise predictors V7 to V10 an importance of exactly zero, so they are not used in any rule or model, while all five informative predictors score between 30 and 65. The dilution is still present but is distributed oddly: duplicate2 scores 24.5 while duplicate1 scores only 2. That is characteristic of a rule-based model, which simply picks one of two interchangeable predictors when it writes a rule rather than splitting the credit evenly.

So the general lesson holds across all four model types: tree ensembles correctly ignore noise predictors, but all of them divide importance among correlated predictors, and the split can be arbitrary.

Exercise 8.2

Use a simulation to show tree bias with different granularities.

Trees choose the split that most reduces the error among all candidate splits. A predictor with many distinct values offers many more candidate split points than a coarse one, so it gets more chances to produce a good-looking split by chance alone. This is the selection bias described in Sect. 8.1. The simulation below makes it visible.

set.seed(624)
n <- 500

granularity_data <- data.frame(
  x_continuous = rnorm(n),                      # ~500 distinct values
  x_20levels   = sample(1:20, n, replace = TRUE),
  x_5levels    = sample(1:5,  n, replace = TRUE),
  x_binary     = sample(0:1,  n, replace = TRUE)
)

granularity_data$y <- rnorm(n)   # pure noise: no predictor is related to y

Every predictor here is independent of the response. A tree should find nothing, and any importance it reports is pure noise.

noise_tree <- rpart(y ~ ., data = granularity_data)

round(noise_tree$variable.importance, 2)
## x_continuous     x_binary   x_20levels    x_5levels 
##        16.59         4.01         2.84         1.39

Even though no predictor has any relationship with the response, the tree reports an importance of 16.6 for the continuous predictor against 1.4 for the five-level one. The ranking follows granularity almost exactly.

A single tree could be a fluke, so I repeat the experiment 200 times and record which predictor is chosen for the very first split.

set.seed(624)

first_split <- replicate(200, {
  d <- data.frame(x_continuous = rnorm(200),
                  x_20levels   = sample(1:20, 200, replace = TRUE),
                  x_5levels    = sample(1:5,  200, replace = TRUE),
                  x_binary     = sample(0:1,  200, replace = TRUE),
                  y = rnorm(200))
  fit <- rpart(y ~ ., data = d, control = rpart.control(cp = 0, maxdepth = 1, minsplit = 20))
  if (nrow(fit$frame) > 1) as.character(fit$frame$var[1]) else NA
})

table(first_split, useNA = "ifany")
## first_split
##   x_20levels    x_5levels     x_binary x_continuous 
##           55           31            5          109
as.data.frame(table(first_split)) |>
  ggplot(aes(x = fct_reorder(first_split, Freq), y = Freq)) +
  geom_col(fill = "steelblue") +
  geom_hline(yintercept = 50, linetype = "dashed", colour = "firebrick") +
  coord_flip() +
  labs(title = "Predictor chosen for the first split in 200 all-noise simulations",
       subtitle = "Dashed line shows what an unbiased selection would give (50 each)",
       x = NULL, y = "Times chosen")

The bias is clear. If the four predictors were treated even-handedly, each would be chosen about 50 times out of 200. Instead:

The continuous predictor is picked more than twenty times as often as the binary one, purely because it offers more places to cut.

Does this matter when a predictor really is informative?

set.seed(624)
informative_data <- data.frame(
  x_continuous_noise   = rnorm(n),
  x_binary_informative = sample(0:1, n, replace = TRUE)
)
informative_data$y <- 3 * informative_data$x_binary_informative + rnorm(n, sd = 2)

round(rpart(y ~ ., data = informative_data)$variable.importance, 2)
## x_binary_informative   x_continuous_noise 
##              1233.16                40.93
randomForest(y ~ ., data = informative_data, importance = TRUE, ntree = 1000) |>
  varImp(scale = FALSE) |> round(3)
##                      Overall
## x_continuous_noise     0.031
## x_binary_informative   4.740

When the coarse predictor carries a genuine signal, it wins easily: the binary informative predictor scores 1233 against 41 for the continuous noise. The bias matters most when predictors are weak or uninformative, which is exactly when a spurious split is most damaging. The practical implications are to be careful reading importance scores when predictors differ greatly in granularity, and to prefer unbiased methods such as conditional inference trees when that mix is present.

Exercise 8.3

In stochastic gradient boosting the bagging fraction and learning rate govern the construction of the trees. Figure 8.24 shows variable importance for the solubility data with both parameters set to 0.1 (left) and both set to 0.9 (right).

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?

Both parameters push the right-hand model toward the same outcome, for related reasons.

The learning rate (shrinkage). With a rate of 0.9, each tree is added at nearly full strength, so the first few trees take almost all of the available signal out of the response. Whichever predictors those early trees use (here NumCarbon and MolWeight) absorb most of the importance, and later trees fit a residual that has little left in it. With a rate of 0.1, each tree contributes only a tenth of its fit, so hundreds of trees are needed, and across that many trees a far wider set of predictors gets used.

The bagging fraction. With a fraction of 0.9, every tree sees almost the same 90% of the training data, so the trees are highly similar and keep selecting the same strong predictors. With 0.1, each tree sees a different small sample, and in those samples different predictors happen to look best, which spreads importance across many more of them.

In short, the right-hand model is greedy and correlated: it commits early to a few predictors. The left-hand model is slow and diverse: it samples the predictor space much more widely.

I can confirm this on the same solubility data:

data(solubility)

importance_spread <- map_dfr(c(0.1, 0.9), function(p) {
  set.seed(624)
  fit <- gbm.fit(solTrainXtrans, solTrainY, distribution = "gaussian", n.trees = 500,
                 interaction.depth = 3, shrinkage = p, bag.fraction = p, verbose = FALSE)
  s <- summary(fit, plotit = FALSE)
  tibble(shrinkage_and_bagging = p,
         top10_share_of_importance = round(sum(head(s$rel.inf, 10)), 1),
         predictors_with_any_importance = sum(s$rel.inf > 0))
})

importance_spread
## # A tibble: 2 x 3
##   shrinkage_and_bagging top10_share_of_importance predictors_with_any_importance
##                   <dbl>                     <dbl>                          <int>
## 1                   0.1                      56.1                            176
## 2                   0.9                      84.5                            202

With both parameters at 0.9 the top ten predictors hold 84.5% of all importance, against 56.1% at 0.1, which matches the figure.

b. Which model do you think would be more predictive of other samples?

The left-hand model, with the learning rate and bagging fraction at 0.1. A small learning rate is the standard recommendation precisely because it regularises the fit: the model approaches the solution in many small steps rather than a few large ones, and it is much less likely to overshoot into noise. A small bagging fraction adds randomness between trees, which decorrelates them and makes the ensemble average more stable, the same mechanism that makes random forests work.

The right-hand model is at serious risk of overfitting. Learning at 0.9 means a handful of aggressive trees drive the prediction, and with 90% of the data in every tree there is little diversity to average away their mistakes. Depending on only two or three predictors also makes it fragile if those measurements shift in new samples.

The caveat is that a small learning rate needs many more trees to converge, so it costs more to train. The right answer in practice is to tune these parameters jointly rather than assume, but between these two specific settings I would expect the left-hand model to generalise better.

c. How would increasing interaction depth affect the slope of predictor importance for either model in Fig. 8.24?

Increasing the interaction depth would flatten the slope, that is, spread importance over more predictors. A depth-1 tree (a stump) uses a single predictor, so each tree can only credit one. A deeper tree makes several splits in sequence, and the splits below the first are chosen from the predictors that work best within that branch, which brings in predictors that would never win at the root. More predictors are therefore used overall and the drop-off from the top of the list becomes less steep.

depth_effect <- map_dfr(expand.grid(param = c(0.1, 0.9), depth = c(1, 10)) |> as_tibble() |> transpose(),
  function(g) {
    set.seed(624)
    fit <- gbm.fit(solTrainXtrans, solTrainY, distribution = "gaussian", n.trees = 500,
                   interaction.depth = g$depth, shrinkage = g$param, bag.fraction = g$param,
                   verbose = FALSE)
    s <- summary(fit, plotit = FALSE)
    tibble(shrinkage_and_bagging = g$param, interaction_depth = g$depth,
           top10_share = round(sum(head(s$rel.inf, 10)), 1),
           predictors_used = sum(s$rel.inf > 0))
  })

depth_effect |> arrange(shrinkage_and_bagging, interaction_depth)
## # A tibble: 4 x 4
##   shrinkage_and_bagging interaction_depth top10_share predictors_used
##                   <dbl>             <dbl>       <dbl>           <int>
## 1                   0.1                 1        63.1             135
## 2                   0.1                10        54.3             180
## 3                   0.9                 1        85.2             126
## 4                   0.9                10        87.7             225

The left-hand model behaves as expected: going from depth 1 to depth 10 lowers the top-ten share from 63.1% to 54.3% and raises the number of predictors used from 135 to 180, a clear flattening.

The right-hand model shows the limit of the argument. The number of predictors used almost doubles (126 to 225), but the top-ten share actually rises slightly (85.2% to 87.7%). With shrinkage at 0.9 the first few trees still dominate the fit, so the extra predictors brought in by the deeper trees enter with tiny weights. Depth spreads importance effectively only when the learning rate is small enough to let later trees matter.

Exercise 8.7

Refer to Exercises 6.3 and 7.5, which describe a chemical manufacturing process. Using the same imputation, data splitting and pre-processing steps as before, I train several tree-based models.

data(ChemicalManufacturingProcess)
chem <- ChemicalManufacturingProcess

predictors <- chem[, -1]
yield <- chem$Yield
predictors <- predictors[, -nearZeroVar(predictors)]

predictors_imputed <- predict(preProcess(predictors, method = "knnImpute"), predictors)

set.seed(624)
chem_rows <- createDataPartition(yield, p = 0.8, list = FALSE)

X_train <- predictors_imputed[chem_rows, ]
X_test  <- predictors_imputed[-chem_rows, ]
y_train <- yield[chem_rows]
y_test  <- yield[-chem_rows]

c(train = nrow(X_train), test = nrow(X_test))
## train  test 
##   144    32

a. Which tree-based regression model gives the optimal resampling and test set performance?

chem_ctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 3)

set.seed(624)
tree_fit <- train(X_train, y_train, method = "rpart", tuneLength = 15, trControl = chem_ctrl)

set.seed(624)
bag_fit <- train(X_train, y_train, method = "treebag", trControl = chem_ctrl)

set.seed(624)
rf_fit <- train(X_train, y_train, method = "rf", tuneLength = 8, trControl = chem_ctrl,
                ntree = 500, importance = TRUE)

set.seed(624)
gbm_fit <- train(X_train, y_train, method = "gbm", verbose = FALSE, trControl = chem_ctrl,
                 tuneGrid = expand.grid(n.trees = c(100, 500, 1000),
                                        interaction.depth = c(1, 3, 5),
                                        shrinkage = c(0.01, 0.1),
                                        n.minobsinnode = 10))

set.seed(624)
cubist_fit <- train(X_train, y_train, method = "cubist", trControl = chem_ctrl,
                    tuneGrid = expand.grid(committees = c(1, 5, 10, 20), neighbors = c(0, 3, 5, 9)))
tree_models <- list(`Single tree` = tree_fit, `Bagged trees` = bag_fit, `Random forest` = rf_fit,
                    `Boosted trees` = gbm_fit, Cubist = cubist_fit)

map_dfr(names(tree_models), function(nm) {
  m <- tree_models[[nm]]
  test_perf <- postResample(predict(m, X_test), y_test)
  tibble(model = nm,
         tuning = paste(names(m$bestTune),
                        sapply(m$bestTune, function(v) if (is.numeric(v)) round(v, 4) else as.character(v)),
                        collapse = ", "),
         cv_RMSE = min(m$results$RMSE),
         cv_Rsquared = max(m$results$Rsquared, na.rm = TRUE),
         test_RMSE = test_perf[["RMSE"]],
         test_Rsquared = test_perf[["Rsquared"]])
}) |>
  mutate(across(where(is.numeric), ~ round(.x, 3))) |>
  arrange(cv_RMSE)
## # A tibble: 5 x 6
##   model         tuning               cv_RMSE cv_Rsquared test_RMSE test_Rsquared
##   <chr>         <chr>                  <dbl>       <dbl>     <dbl>         <dbl>
## 1 Cubist        committees 20, neig~   0.988       0.705     0.903         0.826
## 2 Boosted trees n.trees 1000, inter~   1.11        0.652     1.14          0.752
## 3 Random forest mtry 17                1.14        0.659     1.25          0.727
## 4 Bagged trees  parameter none         1.22        0.574     1.25          0.709
## 5 Single tree   cp 0.3184              1.46        0.387     1.56          0.504
resamples(list(Tree = tree_fit, Bagged = bag_fit, RF = rf_fit,
               Boosted = gbm_fit, Cubist = cubist_fit)) |>
  bwplot(metric = "RMSE", main = "Resampled RMSE across tree-based models")

Cubist is the best on both measures, and by a wide margin: a resampled RMSE of 0.989 and a test RMSE of 0.903 with R2 of 0.826, using 20 committees with 3-neighbour adjustment. The ordering is boosted trees (1.106 / 1.139), random forest (1.135 / 1.253), bagged trees (1.218 / 1.253), and the single tree a distant last (1.461 / 1.563).

The single tree is the only model here that is really poor, which is the familiar result that one tree is a weak learner. Everything that combines trees improves on it substantially, and Cubist, which combines rule-based model trees with a nearest-neighbour correction, does best of all.

Comparing with the earlier homework on the same split:

Model Resampled RMSE Test RMSE Test R2
Cubist (this homework) 0.989 0.903 0.826
SVM, radial (Exercise 7.5) 1.154 1.145 0.747
PLS (Exercise 6.3) 1.363 1.198 0.678

Cubist is the best model I have fitted to these data across all three homeworks, improving on the nonlinear SVM by about 14% on resampled RMSE and on the linear PLS model by about 27%.

b. Which predictors are most important in the optimal tree-based regression model?

cubist_top10 <- varImp(cubist_fit)$importance |>
  rownames_to_column("predictor") |>
  arrange(desc(Overall)) |>
  slice(1:10) |>
  mutate(type = if_else(str_detect(predictor, "Biological"), "Biological", "Process"),
         Overall = round(Overall, 1))

cubist_top10
##                 predictor Overall       type
## 1  ManufacturingProcess32   100.0    Process
## 2  ManufacturingProcess17    59.6    Process
## 3  ManufacturingProcess09    57.7    Process
## 4    BiologicalMaterial12    51.9 Biological
## 5  ManufacturingProcess39    33.7    Process
## 6    BiologicalMaterial02    33.7 Biological
## 7  ManufacturingProcess27    33.7    Process
## 8  ManufacturingProcess04    30.8    Process
## 9  ManufacturingProcess33    26.0    Process
## 10 ManufacturingProcess37    25.0    Process
cubist_top10 |> count(type)
##         type n
## 1 Biological 2
## 2    Process 8
plot(varImp(cubist_fit), top = 10, main = "Top 10 predictors, Cubist model")

Process predictors dominate even more strongly than before: 8 of the top 10 are process measurements and only 2 are biological. ManufacturingProcess32 is first by a clear margin, followed by ManufacturingProcess17 and ManufacturingProcess09.

Comparing the top ten with the optimal linear and nonlinear models

pls_top10 <- varImp(train(X_train, y_train, method = "pls", tuneLength = 20,
                          trControl = chem_ctrl, preProc = c("center", "scale")))$importance |>
  rownames_to_column("predictor") |> arrange(desc(Overall)) |> slice(1:10) |> pull(predictor)

svm_top10 <- varImp(train(X_train, y_train, method = "svmRadial", tuneLength = 14,
                          trControl = chem_ctrl, preProc = c("center", "scale")))$importance |>
  rownames_to_column("predictor") |> arrange(desc(Overall)) |> slice(1:10) |> pull(predictor)

tibble(predictor = union(union(cubist_top10$predictor, pls_top10), svm_top10)) |>
  mutate(Cubist_tree = predictor %in% cubist_top10$predictor,
         SVM_nonlinear = predictor %in% svm_top10,
         PLS_linear = predictor %in% pls_top10,
         appears_in = Cubist_tree + SVM_nonlinear + PLS_linear) |>
  arrange(desc(appears_in), predictor)
## # A tibble: 17 x 5
##    predictor              Cubist_tree SVM_nonlinear PLS_linear appears_in
##    <chr>                  <lgl>       <lgl>         <lgl>           <int>
##  1 BiologicalMaterial02   TRUE        TRUE          TRUE                3
##  2 ManufacturingProcess09 TRUE        TRUE          TRUE                3
##  3 ManufacturingProcess32 TRUE        TRUE          TRUE                3
##  4 BiologicalMaterial03   FALSE       TRUE          TRUE                2
##  5 BiologicalMaterial06   FALSE       TRUE          TRUE                2
##  6 BiologicalMaterial12   TRUE        TRUE          FALSE               2
##  7 ManufacturingProcess06 FALSE       TRUE          TRUE                2
##  8 ManufacturingProcess13 FALSE       TRUE          TRUE                2
##  9 ManufacturingProcess17 TRUE        FALSE         TRUE                2
## 10 ManufacturingProcess36 FALSE       TRUE          TRUE                2
## 11 ManufacturingProcess04 TRUE        FALSE         FALSE               1
## 12 ManufacturingProcess27 TRUE        FALSE         FALSE               1
## 13 ManufacturingProcess31 FALSE       TRUE          FALSE               1
## 14 ManufacturingProcess33 TRUE        FALSE         FALSE               1
## 15 ManufacturingProcess34 FALSE       FALSE         TRUE                1
## 16 ManufacturingProcess37 TRUE        FALSE         FALSE               1
## 17 ManufacturingProcess39 TRUE        FALSE         FALSE               1

Three predictors appear in all three top-ten lists: ManufacturingProcess32, ManufacturingProcess09 and BiologicalMaterial02. ManufacturingProcess32 is ranked first by every model, which is strong evidence that it genuinely matters rather than being an artefact of one method.

Beyond that the lists diverge more than they agreed in the earlier comparison. Cubist brings forward five predictors that neither of the other models ranked highly (ManufacturingProcess39, 27, 04, 33 and 37) and drops the biological measurements that the SVM rated highly (BiologicalMaterial06 and 03). The explanation is that Cubist builds a set of rules, each applying to a different region of the data with its own linear model, so a predictor can be important inside one rule without having a strong relationship across the data as a whole. The linear and SVM-filter rankings, by contrast, both reward predictors with a consistent overall association with yield.

The one conclusion that survives all three modelling approaches is the useful one for the business: the controllable process settings matter more than the raw material measurements, and ManufacturingProcess32 matters most of all.

c. Plot the optimal single tree with the distribution of yield in the terminal nodes

set.seed(624)
single_tree <- train(X_train, y_train, method = "rpart2", tuneLength = 10, trControl = chem_ctrl)

single_tree$bestTune
##   maxdepth
## 2        2
single_tree$finalModel
## n= 144 
## 
## node), split, n, deviance, yval
##       * denotes terminal node
## 
## 1) root 144 453.46990 40.15799  
##   2) ManufacturingProcess32< 0.191596 83 152.30240 39.23084  
##     4) BiologicalMaterial12< -0.6009825 31  36.09462 38.32839 *
##     5) BiologicalMaterial12>=-0.6009825 52  75.90933 39.76885 *
##   3) ManufacturingProcess32>=0.191596 61 132.74350 41.41951  
##     6) BiologicalMaterial03< 1.073464 48  92.19183 41.08688 *
##     7) BiologicalMaterial03>=1.073464 13  15.63103 42.64769 *

Tuning on the complexity parameter collapses the tree to a single split, so here I tune on maximum depth instead, which gives a slightly better resampled RMSE (1.453 against 1.461) and a tree with four terminal nodes that is far more informative to look at.

plot(as.party(single_tree$finalModel),
     main = "Optimal single tree with yield distributions in the terminal nodes")

tibble(node = predict(as.party(single_tree$finalModel), type = "node"), yield = y_train) |>
  group_by(node) |>
  summarise(n = n(), mean_yield = round(mean(yield), 2), sd = round(sd(yield), 2),
            min = round(min(yield), 2), max = round(max(yield), 2))
## # A tibble: 4 x 6
##    node     n mean_yield    sd   min   max
##   <int> <int>      <dbl> <dbl> <dbl> <dbl>
## 1     3    31       38.3  1.1   35.2  40.7
## 2     4    52       39.8  1.22  37.9  43.1
## 3     6    48       41.1  1.4   36.8  44.4
## 4     7    13       42.6  1.14  40.0  43.9

Does this view provide additional knowledge? Yes, in three ways that the importance rankings alone do not give.

It shows where the split points are, in interpretable terms. The root split is on ManufacturingProcess32 at a scaled value of 0.19, which on the original scale is about 159.5 (the predictor averages 158.5 with a standard deviation of 5.4). So the single most useful piece of information about a batch is simply whether this process setting is above or below roughly 159.5, and that one split separates mean yields of 39.2 and 41.4.

It shows the biological predictors acting inside the process groups. Both second-level splits use biological measurements, but different ones on each side: BiologicalMaterial12 below the process threshold and BiologicalMaterial03 above it. The raw material therefore matters in a conditional way, which is the kind of interaction a tree reveals and a linear model does not. The four terminal nodes form a clean ladder of mean yields: 38.3, 39.8, 41.1 and 42.6.

It puts the business case in context. The gap between the worst and best terminal nodes is about 4.3 percentage points of yield. At roughly one hundred thousand dollars per batch for each 1% of yield, the difference between operating in the worst and best of these four regimes is worth several hundred thousand dollars per batch. At the same time, the boxplots show the distributions overlap: node 3 ranges from 35.3 to 40.7 while node 7 ranges from 40.0 to 43.9, so these are tendencies rather than guarantees, and the single tree should be read as a map of the main effects rather than as a prediction tool. The Cubist model is the one to use for prediction.