library(mlbench) # mlbench.friedman1()
library(randomForest)
library(caret)
library(party) # cforest(), varimp()
library(gbm)
library(rpart)
library(partykit) # as.party() for tree plots (masks party::cforest, so party:: is used below)
library(AppliedPredictiveModeling) # solubility + ChemicalManufacturingProcess data
library(dplyr)
library(tidyr)
library(ggplot2)
if (params$run_cubist) library(Cubist)
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) <- c(paste0("V", 1:10), "y")
Only V1–V5 are used to generate
y:
\[y = 10\sin(\pi x_1 x_2) + 20(x_3 - 0.5)^2 + 10x_4 + 5x_5 + \varepsilon\]
V6–V10 are pure noise.
model1 <- randomForest(y ~ ., data = simulated,
importance = TRUE,
ntree = 1000)
rfImp1 <- varImp(model1, scale = FALSE)
rfImp1 %>% arrange(desc(Overall))
## Overall
## V1 8.84289608
## V4 7.75934674
## V2 6.74508245
## V5 2.23628276
## V3 0.67830653
## V6 0.11429887
## V10 0.03863205
## V7 0.03724747
## V9 -0.04495617
## V8 -0.05349642
rfImp1 %>%
mutate(Predictor = reorder(rownames(rfImp1), Overall),
Type = ifelse(rownames(rfImp1) %in% paste0("V", 1:5),
"Informative", "Uninformative")) %>%
ggplot(aes(Overall, Predictor, fill = Type)) +
geom_col() +
labs(title = "Random forest permutation importance",
x = "Increase in MSE when permuted", y = NULL) +
theme_minimal()
Did the random forest significantly use the uninformative predictors (V6–V10)?
No. V6–V10 have importance scores between
-0.053 and 0.114, which is basically zero. A negative score means that
shuffling the predictor didn’t hurt the model at all. The real
predictors V1, V2 and V4 score
between 6.75 and 8.84.
V3 is also low (0.678) even though it is a real
predictor. Its effect, \(20(x_3-0.5)^2\), is small (it adds at most
5 to y) and U-shaped, so it is harder for the trees to pick
up. It still scores higher than every noise variable.
cforest)Fit cforest on the original data and on the data with
duplicate1, and compare the usual importance with the
conditional importance (Strobl et al. 2007).
set.seed(203)
cf_orig <- party::cforest(y ~ ., data = simulated[, c(paste0("V", 1:10), "y")],
controls = party::cforest_unbiased(ntree = 500))
set.seed(204)
cf_dup <- party::cforest(y ~ ., data = simulated[, c(paste0("V", 1:10), "duplicate1", "y")],
controls = party::cforest_unbiased(ntree = 500))
cf_trad_orig <- party::varimp(cf_orig)
cf_cond_orig <- party::varimp(cf_orig, conditional = TRUE)
cf_trad_dup <- party::varimp(cf_dup)
cf_cond_dup <- party::varimp(cf_dup, conditional = TRUE)
cf_tab <- data.frame(Predictor = names(cf_trad_dup)) %>%
left_join(data.frame(Predictor = names(cf_trad_orig),
`Traditional (orig)` = cf_trad_orig,
`Conditional (orig)` = cf_cond_orig, check.names = FALSE),
by = "Predictor") %>%
mutate(`Traditional (+dup1)` = cf_trad_dup,
`Conditional (+dup1)` = cf_cond_dup)
cf_tab %>% mutate(across(where(is.numeric), ~ round(.x, 3))) %>% knitr::kable()
| Predictor | Traditional (orig) | Conditional (orig) | Traditional (+dup1) | Conditional (+dup1) |
|---|---|---|---|---|
| V1 | 8.747 | 5.790 | 6.875 | 3.261 |
| V2 | 6.631 | 5.324 | 6.125 | 4.825 |
| V3 | -0.018 | -0.005 | 0.018 | 0.013 |
| V4 | 8.288 | 6.548 | 7.867 | 6.740 |
| V5 | 1.914 | 1.202 | 1.729 | 1.051 |
| V6 | -0.029 | -0.007 | 0.007 | 0.009 |
| V7 | 0.022 | 0.007 | 0.012 | 0.005 |
| V8 | -0.010 | 0.004 | -0.023 | 0.026 |
| V9 | -0.001 | -0.006 | -0.006 | 0.004 |
| V10 | 0.002 | 0.015 | -0.040 | -0.023 |
| duplicate1 | NA | NA | 2.734 | 1.301 |
Do these importances show the same pattern as the traditional random forest?
Mostly yes:
cforest importance rank V1, V2
and V4 highest, then V5, with V3
and V6–V10 near zero. This matches the random
forest.duplicate1 takes some credit from V1
(V1 = 6.87, duplicate1 = 2.73), just like in
part (b). Conditional importance asks a different question: how much
does a predictor add after accounting for the predictors it’s
correlated with? Since V1 and duplicate1 carry
the same information, neither adds much once the other is known, so both
scores drop further (V1 = 3.26, duplicate1 =
1.3).V1: 8.75 usual vs 5.79 conditional). So
compare the rankings, not the raw numbers.cforest also gives the noise variables scores closer to
zero than the regular random forest does. Its trees choose splits in a
way that doesn’t favor predictors with many possible split points (see
8.2).
Repeat the comparison (original data vs. data with
duplicate1) using boosted trees and Cubist.
predictors_orig <- paste0("V", 1:10)
predictors_dup <- c(predictors_orig, "duplicate1")
## Boosted trees
set.seed(205)
gbm_orig <- gbm(y ~ ., data = simulated[, c(predictors_orig, "y")],
distribution = "gaussian", n.trees = 1000,
interaction.depth = 3, shrinkage = 0.05, bag.fraction = 0.5)
set.seed(205)
gbm_dup <- gbm(y ~ ., data = simulated[, c(predictors_dup, "y")],
distribution = "gaussian", n.trees = 1000,
interaction.depth = 3, shrinkage = 0.05, bag.fraction = 0.5)
gbm_imp_orig <- summary(gbm_orig, plotit = FALSE)
gbm_imp_dup <- summary(gbm_dup, plotit = FALSE)
## Cubist
cub_orig <- cubist(x = simulated[, predictors_orig], y = simulated$y, committees = 100)
cub_dup <- cubist(x = simulated[, predictors_dup], y = simulated$y, committees = 100)
cub_imp_orig <- varImp(cub_orig)
cub_imp_dup <- varImp(cub_dup)
d_tab <- data.frame(Predictor = predictors_dup) %>%
left_join(data.frame(Predictor = gbm_imp_orig$var, `GBM (orig)` = gbm_imp_orig$rel.inf,
check.names = FALSE), by = "Predictor") %>%
left_join(data.frame(Predictor = gbm_imp_dup$var, `GBM (+dup1)` = gbm_imp_dup$rel.inf,
check.names = FALSE), by = "Predictor")
if (params$run_cubist) {
d_tab <- d_tab %>%
left_join(data.frame(Predictor = rownames(cub_imp_orig),
`Cubist (orig)` = cub_imp_orig$Overall,
check.names = FALSE), by = "Predictor") %>%
left_join(data.frame(Predictor = rownames(cub_imp_dup),
`Cubist (+dup1)` = cub_imp_dup$Overall,
check.names = FALSE), by = "Predictor")
}
d_tab %>% mutate(across(where(is.numeric), ~ round(.x, 2))) %>% knitr::kable()
| Predictor | GBM (orig) | GBM (+dup1) | Cubist (orig) | Cubist (+dup1) |
|---|---|---|---|---|
| V1 | 25.82 | 23.09 | 71.5 | 69.5 |
| V2 | 21.26 | 21.05 | 58.5 | 57.5 |
| V3 | 7.65 | 7.26 | 47.0 | 43.5 |
| V4 | 26.59 | 26.83 | 48.0 | 48.0 |
| V5 | 11.13 | 11.01 | 33.0 | 34.0 |
| V6 | 1.83 | 1.76 | 0.0 | 9.0 |
| V7 | 1.42 | 1.27 | 0.0 | 0.0 |
| V8 | 1.44 | 1.29 | 0.0 | 0.0 |
| V9 | 1.40 | 1.51 | 0.0 | 0.0 |
| V10 | 1.46 | 1.16 | 0.0 | 0.0 |
| duplicate1 | NA | 3.76 | NA | 0.0 |
GBM importance is relative influence: each predictor’s share (in %) of the total error reduction. Cubist importance is usage: how often each predictor is used in the rules and in the linear models inside them. The two scales are different, so compare patterns within each column, not numbers across columns.
Does the same pattern occur?
V6–V10 together get 7.5% of the importance, vs
92.5% for V1–V5. So boosting mostly ignores
the noise, like the forest. The noise gets a little credit because after
many trees, the later ones start fitting random leftovers.V1 goes
from 25.8 to 23.1, and duplicate1 only gets 3.8. The copy
takes much less credit than in the random forest. Boosting looks at
every predictor at every split and picks the best one, so
V1 keeps winning, while the random forest sometimes isn’t
allowed to choose V1 and has to use the copy.V6–V10 zero usage
(0, 0, 0, 0, 0), the cleanest result of any model. With
duplicate1 added, the copy gets 0 usage and V1
barely changes (71.5 → 69.5), so there is no dilution
at all. Once V1 is in the model, the copy adds nothing new,
so Cubist never uses it. Cubist also ranks V3 much higher
than the forests do (nearly tied with V4 and above
V5), because the small linear models in each rule can
follow the U-shape of \((x_3-0.5)^2\)
piece by piece.Summary: all three models separate the real
predictors from the noise. They handle the correlated copy differently:
the random forest gives the copy a big share of V1’s
credit, boosting gives it a small share, and Cubist ignores it. So when
predictors are correlated, a tree model’s importance scores depend on
how that model picks its splits.
Use a simulation to show tree bias with different granularities.
Make four predictors that are all pure noise but have different numbers of distinct values (granularity), and so different numbers of possible split points:
| Predictor | Values | Possible split points |
|---|---|---|
x_2 |
2 categories (1, 2) | 1 |
x_10 |
10 values | 9 |
x_50 |
50 values | 49 |
x_cont |
continuous | ~199 |
y is unrelated to all of them. A fair tree would pick
each one for the first split about 25% of the time.
set.seed(624)
n_sims <- 500
n <- 200
run_one <- function(signal = 0) {
d <- data.frame(
x_2 = sample(1:2, n, replace = TRUE),
x_10 = sample(1:10, n, replace = TRUE),
x_50 = sample(1:50, n, replace = TRUE),
x_cont = rnorm(n)
)
# Scenario 2 adds a small real effect for the LOW-granularity predictor
d$y <- signal * (d$x_2 == 2) + rnorm(n)
fit <- rpart(y ~ ., data = d,
control = rpart.control(maxdepth = 1, cp = 0, xval = 0))
as.character(fit$frame$var[1]) # predictor used at the root split
}
root_null <- replicate(n_sims, run_one(signal = 0))
root_signal <- replicate(n_sims, run_one(signal = 0.3))
sim_results <- bind_rows(
data.frame(Scenario = "All noise", Root = root_null),
data.frame(Scenario = "x_2 has a small real effect (0.3 SD)", Root = root_signal)
) %>%
count(Scenario, Root) %>%
group_by(Scenario) %>%
mutate(Proportion = n / sum(n)) %>%
ungroup() %>%
mutate(Root = factor(Root, levels = c("x_2", "x_10", "x_50", "x_cont"))) %>%
arrange(Scenario, Root)
sim_results %>% select(-n) %>%
pivot_wider(names_from = Root, values_from = Proportion, values_fill = 0) %>%
mutate(across(where(is.numeric), ~ round(.x, 3))) %>%
knitr::kable()
| Scenario | x_2 | x_10 | x_50 | x_cont |
|---|---|---|---|---|
| All noise | 0.032 | 0.146 | 0.336 | 0.486 |
| x_2 has a small real effect (0.3 SD) | 0.410 | 0.092 | 0.216 | 0.282 |
ggplot(sim_results, aes(Root, Proportion, fill = Root)) +
geom_col(show.legend = FALSE) +
geom_hline(yintercept = 0.25, linetype = "dashed") +
facet_wrap(~ Scenario) +
labs(title = "How often each predictor is chosen for the root split (500 simulations)",
subtitle = "Dashed line = 25%, the rate an unbiased tree would show when all predictors are noise",
x = "Predictor (ordered by granularity)", y = "Proportion of simulations") +
theme_minimal()
Result. When all four predictors are noise, the tree picks the continuous one for the first split 49% of the time and the two-value one only 3% of the time, far from 25% each. The more split points a predictor has, the more often it gets picked. The tree tries every possible split and keeps the best one, so a predictor with more split points has more chances to look good just by luck.
The second scenario shows why this matters. Even when
x_2 really does affect y, the tree picks it
first only 41% of the time; the rest of the time a useless predictor
with more split points wins. This is the bias described in Section 8.1.
Conditional inference trees (ctree/cforest)
fix it by using a statistical test, adjusted for the number of possible
splits, to choose the predictor.
Figure 8.24 shows variable importance for boosting on the solubility data. On the left, the bagging fraction and learning rate are both 0.1; on the right, both are 0.9. The right model puts most of the importance on a few predictors; the left spreads it out.
Both settings push the right model toward a few predictors:
In short, the right model learns fast from the same few predictors, and the left model learns slowly from many.
Most likely the left model (0.1 / 0.1). A small learning rate is the main thing that keeps boosting from overfitting (Friedman 2002), and using a random sample for each tree helps too. Taking 90% steps makes the model fit noise in the training data quickly.
One catch: a bagging fraction of 0.1 means each tree sees only about 95 of the 951 compounds, so each tree is noisy and the model needs many trees. The real answer should come from cross-validation or a test set (see the demo below). In practice, middle values usually work better than either extreme.
Increasing interaction depth should make the importance curve flatter: importance spreads over more predictors.
Deeper trees have more splits, so each tree uses more predictors, and lower-ranked ones get some credit. With a high learning rate the change may be small: the first few deep trees already explain almost everything, so the top predictors keep most of the credit. With a low learning rate the signal is spread over many trees, so deeper trees give more predictors a chance, and the curve flattens more. The demo below shows this.
A quick check of (a)–(c). The book doesn’t list all the settings for Figure 8.24, so this uses 500 trees and compares depth 1 with depth 10.
data(solubility)
sol_train <- data.frame(solTrainXtrans, Solubility = solTrainY)
fit_gbm <- function(rate, bag, depth, seed = 83) {
set.seed(seed)
gbm(Solubility ~ ., data = sol_train, distribution = "gaussian",
n.trees = 500, interaction.depth = depth,
shrinkage = rate, bag.fraction = bag)
}
settings <- expand.grid(rate_bag = c(0.1, 0.9), depth = c(1, 10))
demo <- lapply(seq_len(nrow(settings)), function(i) {
s <- settings[i, ]
m <- fit_gbm(s$rate_bag, s$rate_bag, s$depth)
ri <- summary(m, plotit = FALSE)
pred <- predict(m, newdata = data.frame(solTestXtrans), n.trees = 500)
list(settings = s, rel_inf = ri,
test_rmse = RMSE(pred, solTestY),
top5_share = sum(sort(ri$rel.inf, decreasing = TRUE)[1:5]))
})
demo_summary <- bind_rows(lapply(demo, function(d) data.frame(
`Learning rate & bag fraction` = d$settings$rate_bag,
`Interaction depth` = d$settings$depth,
`% importance in top 5 predictors` = round(d$top5_share, 1),
`Test RMSE` = round(d$test_rmse, 3), check.names = FALSE)))
knitr::kable(demo_summary)
| Learning rate & bag fraction | Interaction depth | % importance in top 5 predictors | Test RMSE |
|---|---|---|---|
| 0.1 | 1 | 50.2 | 0.717 |
| 0.9 | 1 | 77.8 | 0.703 |
| 0.1 | 10 | 43.8 | 0.680 |
| 0.9 | 10 | 76.1 | 0.812 |
plot_df <- bind_rows(lapply(demo, function(d) {
d$rel_inf %>% arrange(desc(rel.inf)) %>% slice(1:25) %>%
mutate(Rank = row_number(),
Model = paste0("rate = bag = ", d$settings$rate_bag,
", depth = ", d$settings$depth))
}))
ggplot(plot_df, aes(Rank, rel.inf)) +
geom_col(fill = "steelblue") +
facet_wrap(~ Model, ncol = 2) +
labs(title = "Relative influence of the top 25 predictors",
x = "Predictor rank", y = "Relative influence (%)") +
theme_minimal()
(a): the top 5 predictors get 77.8% of the importance in the 0.9/0.9 model and 50.2% in the 0.1/0.1 model (depth 1), which matches (a).
(b): test RMSE at depth 1 is 0.717 (0.1/0.1) vs 0.703 (0.9/0.9), and at depth 10 it is 0.68 vs 0.812. With depth-1 trees the two models are about the same, because the trees are too simple to overfit much. With deeper trees the 0.9/0.9 model overfits and the 0.1/0.1 model is clearly better. So the answer to (b) holds, but the gap depends on tree depth.
(c): going from depth 1 to depth 10, the top-5 share goes from 77.8% to 76.1% for the 0.9/0.9 model and from 50.2% to 43.8% for the 0.1/0.1 model. Both curves get flatter, and the 0.1/0.1 model changes more, as expected in (c).
Use the chemical manufacturing data with the same imputation, data split and preprocessing as in Exercises 6.3 and 7.5, and train several tree-based models.
Note: If your 6.3/7.5 used a different seed, split ratio or imputation method, change the next chunk to match so the models are comparable.
data(ChemicalManufacturingProcess)
chem_x <- ChemicalManufacturingProcess[, -1]
chem_y <- ChemicalManufacturingProcess$Yield
# 80/20 split, stratified on yield
set.seed(100)
train_idx <- createDataPartition(chem_y, p = 0.8, list = FALSE)
x_train <- chem_x[train_idx, ]; y_train <- chem_y[train_idx]
x_test <- chem_x[-train_idx, ]; y_test <- chem_y[-train_idx]
# Remove near-zero-variance predictors (decided on training data only)
nzv <- nearZeroVar(x_train)
if (length(nzv) > 0) {
x_train <- x_train[, -nzv]
x_test <- x_test[, -nzv]
}
# KNN imputation (also centers/scales); fit on training data, apply to both
pp <- preProcess(x_train, method = "knnImpute")
x_train_p <- predict(pp, x_train)
x_test_p <- predict(pp, x_test)
c(train_rows = nrow(x_train_p), test_rows = nrow(x_test_p),
predictors = ncol(x_train_p), NAs_left = sum(is.na(x_train_p)) + sum(is.na(x_test_p)))
## train_rows test_rows predictors NAs_left
## 144 32 56 0
Tree models don’t need centering or scaling, because scaling doesn’t
change where a split falls. knnImpute does it anyway, and
it doesn’t hurt.
All models use the same 10 cross-validation folds, so their results can be compared fairly.
set.seed(100)
cv_folds <- createFolds(y_train, k = 10, returnTrain = TRUE)
ctrl <- trainControl(method = "cv", index = cv_folds)
# Single CART tree
set.seed(100)
rpart_fit <- train(x_train_p, y_train, method = "rpart",
tuneLength = 10, trControl = ctrl)
# Bagged trees
set.seed(100)
bag_fit <- train(x_train_p, y_train, method = "treebag",
nbagg = 50, trControl = ctrl)
# Random forest
set.seed(100)
rf_fit <- train(x_train_p, y_train, method = "rf",
tuneLength = 8, ntree = 1000,
importance = TRUE, trControl = ctrl)
# Stochastic gradient boosting
gbm_grid <- expand.grid(interaction.depth = c(1, 3, 5, 7),
n.trees = c(100, 250, 500, 1000),
shrinkage = c(0.01, 0.1),
n.minobsinnode = 10)
set.seed(100)
gbm_fit <- train(x_train_p, y_train, method = "gbm",
tuneGrid = gbm_grid, verbose = FALSE, trControl = ctrl)
# Cubist
cubist_grid <- expand.grid(committees = c(1, 10, 50, 100),
neighbors = c(0, 1, 5, 9))
set.seed(100)
cubist_fit <- train(x_train_p, y_train, method = "cubist",
tuneGrid = cubist_grid, trControl = ctrl)
plot(rpart_fit, main = "CART: tuning cp")
plot(rf_fit, main = "Random forest: tuning mtry")
plot(gbm_fit)
if (params$run_cubist) plot(cubist_fit)
tree_models <- list(CART = rpart_fit, Bagged = bag_fit,
`Random Forest` = rf_fit, GBM = gbm_fit)
if (params$run_cubist) tree_models$Cubist <- cubist_fit
# Resampling performance at each model's best tuning values
rs <- resamples(tree_models)
summary(rs)
##
## Call:
## summary.resamples(object = rs)
##
## Models: CART, Bagged, Random Forest, GBM, Cubist
## Number of resamples: 10
##
## MAE
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## CART 0.8943367 0.9925658 1.0975338 1.1278035 1.2576226 1.430910 0
## Bagged 0.7361728 0.8012410 0.8526954 0.8995226 0.9015115 1.289562 0
## Random Forest 0.6954760 0.7345514 0.8189474 0.8424424 0.8594832 1.191555 0
## GBM 0.5940599 0.6880221 0.8811558 0.8563156 0.9961782 1.145695 0
## Cubist 0.2698428 0.5778509 0.6777920 0.6699962 0.7546113 1.024639 0
##
## RMSE
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## CART 1.2469986 1.2601838 1.3760790 1.4637255 1.586585 1.947016 0
## Bagged 0.8980600 1.0258664 1.1153486 1.1815472 1.273183 1.608692 0
## Random Forest 0.8864568 0.9762451 1.0405690 1.1133677 1.202877 1.501394 0
## GBM 0.7039101 0.8791812 1.0606918 1.0827102 1.343355 1.402479 0
## Cubist 0.4475008 0.8847583 0.9698917 0.9578212 1.102217 1.381739 0
##
## Rsquared
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## CART 0.1916246 0.4120140 0.4299761 0.4398475 0.5159737 0.5951562 0
## Bagged 0.4385069 0.6168211 0.6438715 0.6363519 0.6946406 0.7481019 0
## Random Forest 0.5428585 0.6462617 0.6872540 0.6876251 0.7248463 0.8401560 0
## GBM 0.4472657 0.5804498 0.6559306 0.6742443 0.7950921 0.8582508 0
## Cubist 0.6207494 0.6827360 0.7344240 0.7574520 0.8129004 0.9317312 0
cv_perf <- bind_rows(lapply(names(tree_models), function(nm) {
f <- tree_models[[nm]]
best <- merge(f$results, f$bestTune)
data.frame(Model = nm, CV_RMSE = best$RMSE, CV_Rsquared = best$Rsquared, CV_MAE = best$MAE)
}))
# Test-set performance
test_perf <- bind_rows(lapply(names(tree_models), function(nm) {
pr <- postResample(predict(tree_models[[nm]], x_test_p), y_test)
data.frame(Model = nm, Test_RMSE = pr["RMSE"], Test_Rsquared = pr["Rsquared"],
Test_MAE = pr["MAE"])
}))
perf <- left_join(cv_perf, test_perf, by = "Model") %>% arrange(CV_RMSE)
rownames(perf) <- NULL
perf %>% mutate(across(where(is.numeric), ~ round(.x, 3))) %>% knitr::kable()
| Model | CV_RMSE | CV_Rsquared | CV_MAE | Test_RMSE | Test_Rsquared | Test_MAE |
|---|---|---|---|---|---|---|
| Cubist | 0.958 | 0.757 | 0.670 | 0.815 | 0.777 | 0.591 |
| GBM | 1.083 | 0.674 | 0.856 | 0.798 | 0.780 | 0.647 |
| Random Forest | 1.113 | 0.688 | 0.842 | 0.995 | 0.658 | 0.839 |
| Bagged | 1.182 | 0.636 | 0.900 | 1.079 | 0.574 | 0.874 |
| CART | 1.464 | 0.440 | 1.128 | 1.282 | 0.411 | 0.996 |
bwplot(rs, metric = "RMSE", main = "10-fold CV RMSE (same folds for every model)")
Answer. By cross-validation, the best tree-based model is Cubist (CV RMSE = 0.958, CV R² = 0.757). On the test set, the lowest RMSE comes from GBM (test RMSE = 0.798). These disagree, but the test set has only 32 samples, so its RMSE can change a lot by chance. I pick the model by cross-validation, which averages over 10 folds. The two test RMSEs are also close (0.815 vs 0.798), so the test set doesn’t really contradict that choice. The single tree (CART) does worst. Models that combine many trees are more stable than one tree, so they predict better.
The best model, used for the rest of this exercise, is Cubist, with these tuning values:
best_fit$bestTune
## committees neighbors
## 10 50 1
best_imp <- varImp(best_fit)
plot(best_imp, top = 20, main = paste("Top 20 predictors:", best_name))
top_n_vars <- function(fit, n = 10) {
vi <- varImp(fit)$importance
vi <- vi[order(-vi[, 1]), , drop = FALSE]
head(rownames(vi), n)
}
top10_tree <- top_n_vars(best_fit)
n_bio_tree <- sum(grepl("^Biological", top10_tree))
n_proc_tree <- sum(grepl("^Manufacturing", top10_tree))
n_bio_all <- sum(grepl("^Biological", names(x_train_p)))
n_proc_all <- sum(grepl("^Manufacturing", names(x_train_p)))
Do biological or process variables dominate? Process variables do: 7 of the top 10 are process variables and 3 are biological. Keep in mind there are many more process variables to choose from (45 process vs 11 biological). The top predictor is ManufacturingProcess32.
To compare, I refit the model types that usually win in 6.3 and 7.5 (PLS for linear, SVM for nonlinear) on the same data and folds.
If a different model was optimal in your 6.3 or 7.5, replace
method = "pls"/"svmRadial"with that model.
set.seed(100)
pls_fit <- train(x_train_p, y_train, method = "pls",
tuneLength = 20, trControl = ctrl)
set.seed(100)
svm_fit <- train(x_train_p, y_train, method = "svmRadial",
tuneLength = 10, trControl = ctrl)
top10_pls <- top_n_vars(pls_fit)
top10_svm <- top_n_vars(svm_fit)
data.frame(Rank = 1:10,
Tree = top10_tree,
`Linear (PLS)` = top10_pls,
`Nonlinear (SVM)` = top10_svm,
check.names = FALSE) %>% knitr::kable()
| Rank | Tree | Linear (PLS) | Nonlinear (SVM) |
|---|---|---|---|
| 1 | ManufacturingProcess32 | ManufacturingProcess32 | ManufacturingProcess32 |
| 2 | ManufacturingProcess13 | ManufacturingProcess13 | ManufacturingProcess13 |
| 3 | BiologicalMaterial03 | ManufacturingProcess36 | BiologicalMaterial06 |
| 4 | ManufacturingProcess04 | ManufacturingProcess09 | ManufacturingProcess17 |
| 5 | ManufacturingProcess33 | ManufacturingProcess17 | BiologicalMaterial03 |
| 6 | ManufacturingProcess15 | ManufacturingProcess33 | ManufacturingProcess36 |
| 7 | ManufacturingProcess09 | BiologicalMaterial02 | BiologicalMaterial02 |
| 8 | BiologicalMaterial06 | BiologicalMaterial06 | ManufacturingProcess09 |
| 9 | BiologicalMaterial02 | ManufacturingProcess06 | BiologicalMaterial12 |
| 10 | ManufacturingProcess17 | BiologicalMaterial03 | ManufacturingProcess06 |
How do the top 10 compare?
To make the split values readable, I refit the tuned tree on the imputed data in its original units (not scaled). Scaling doesn’t change a tree’s structure, only the numbers shown at the splits.
vars <- names(x_train_p)
x_train_orig <- as.data.frame(
sweep(sweep(as.matrix(x_train_p), 2, pp$std[vars], "*"), 2, pp$mean[vars], "+")
)
single_tree <- rpart(Yield ~ ., data = data.frame(x_train_orig, Yield = y_train),
control = rpart.control(cp = rpart_fit$bestTune$cp))
plot(partykit::as.party(single_tree),
main = "Optimal CART tree: Yield distribution in each terminal node",
gp = gpar(fontsize = 9))
if (has_split) {
cat("Path to highest-yield node (mean yield =", round(max(leaves$yval), 2), ", n =",
leaves$n[which.max(leaves$yval)], "):\n ", paste(path_best, collapse = " AND "), "\n\n")
cat("Path to lowest-yield node (mean yield =", round(min(leaves$yval), 2), ", n =",
leaves$n[which.min(leaves$yval)], "):\n ", paste(path_worst, collapse = " AND "), "\n")
}
## Path to highest-yield node (mean yield = 43.49 , n = 10 ):
## ManufacturingProcess32>=159.5 AND ManufacturingProcess06>=208.4 AND ManufacturingProcess17< 33.45
##
## Path to lowest-yield node (mean yield = 37 , n = 8 ):
## ManufacturingProcess32< 159.5 AND BiologicalMaterial12< 19.73 AND BiologicalMaterial05>=19.7
Does this view add knowledge about the predictors and yield?
Yes. It shows things the importance rankings can’t:
Note: a single tree can change a lot with small changes in the data, and it predicts worse than the combined models (see part a). Use it to understand the relationships, not to make the final predictions.