(a) Fit a random forest model to all of the predictors, then estimate the variable importance scores:
set.seed(200)# Let's fit a random forest model to all of the predictorsmodel1 <-randomForest(y ~ ., data = simulated, importance =TRUE, ntree =1000)# Let's calculate variable importance scores from the fitted random forest model rfImp1 <-varImp(model1, scale =FALSE)rfImp1
Did the random forest model significantly use the uninformative predictors (V6– V10)?
Based of the result from the variable importance scores, we could say that the random forest did not use the uninformative predictors (V6– V10) because their scores hovering around zero ranging between -0.068 and 0.136.
b) Now add an additional predictor that is highly correlated with one of the informative predictors.
We will pick the predictor V1 as our informative predictor.
The correlation coefficient value can be rounded to 0.95.
Fit another random forest model to these data. Did the importance score for V1 change?
# Let's fit another random forest model to these datamodel2 <-randomForest(y ~ ., data = simulated, importance =TRUE, ntree =1000)# Let's evaluate variable importance scores from the second fitted random forest modelrfImp2 <-varImp(model2, scale =FALSE)rfImp2
The importance score of V1 from the second fitted random forest model has changed from 8.605 from model1 to 6.007 in model2. This result was predictable because V1 and duplicate1 contain nearly identical information, consequently the predictive contribution previously credited solely to V1 is now shared.
What happens when you add another predictor that is also highly correlated with V1?
set.seed(200)# Let's add another predictor that is also highly correlated with V1simulated$duplicate2 <- simulated$V1 +rnorm(200) * .1# Let's fit another model to evaluate the predictors scoresmodel3 <-randomForest(y ~ ., data = simulated, importance =TRUE, ntree =1000)# Let's calculate variable importance scores from the third fitted random forest modelrfImp3 <-varImp(model3, scale =FALSE)rfImp3
The importance score of V1 from the third fitted random forest model decreases further. That was predictable because adding correlated predictors dilutes the importance of the original variable where in this case the importance score is spread among:V1, duplicate1, duplicate2 and each variable receives a smaller individual score.
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 of that function 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?
Let’s fit a random forest model using conditional inference trees using the cforest function and check both predictors traditionnal and conditional importance
I will install the party package in the console.
# Loading the party packagelibrary(party)
Warning: package 'party' was built under R version 4.5.3
Loading required package: grid
Loading required package: mvtnorm
Warning: package 'mvtnorm' was built under R version 4.5.3
Loading required package: modeltools
Warning: package 'modeltools' was built under R version 4.5.3
Loading required package: stats4
Loading required package: strucchange
Warning: package 'strucchange' was built under R version 4.5.3
Loading required package: zoo
Warning: package 'zoo' was built under R version 4.5.2
Attaching package: 'zoo'
The following objects are masked from 'package:base':
as.Date, as.Date.numeric
Loading required package: sandwich
Warning: package 'sandwich' was built under R version 4.5.3
# fit a random forest model using conditional inference trees using the cforest functionset.seed(200)cforestModel <-cforest(y ~ ., data = simulated, controls =cforest_unbiased(ntree =1000))# Let's calculate predictors traditional importanceset.seed(200)cfImp_trad <-varimp(cforestModel, conditional =FALSE)cfImp_trad
Do these importances show the same pattern as the traditional random forest model?
The predictors traditional importance approach produces results quiet similar/close to the one of random forest. Indeed predictors V1-V5 are still as important, however, a predictor like V1 decreases as each duplicate is added whereas predictors V6-V10 remained around 0.
The conditional importance approach described in Strobl et al. (2007) seems to evaluate each predictor’s importance given the variable correlated with the predictor which prevent the model from leaning on the unpermuted duplicates to compensate. Hence, V1 keeps a higher relative ranking compared to the uninformative predictors (V6–V10) than under traditional importance, though its absolute score is still lower than in the single-predictor model.
In conclusion, the conditional importance approach is less diluted by correlation in the sense that it doesn’t spread credit around.
d) Repeat this process with different tree models, such as boosted trees and Cubist. Does the same pattern occur?
Let’s fit a boosted trees and cubist models and check the predictor importance in each case. For context, When tuning the gbm model, i will set the interaction.depth = 3 because in the case of friedman 1 Data, it provides enough depth to capture the two-way interaction between \(x_1\) and \(x_2\), approximate the curved quadratic term \(20(x_3 - 0.5)^2\) with step functions, and still allow the tree to evaluate secondary splits among correlated substitutes (V1, duplicate1, duplicate2) within the same tree.
library(gbm)
Warning: package 'gbm' was built under R version 4.5.3
Loaded gbm 2.3.1
This version of gbm is no longer under development. Consider transitioning to gbm3, https://github.com/gbm-developers/gbm3
library(Cubist)
Warning: package 'Cubist' was built under R version 4.5.3
set.seed(200)# fitting Boosted treesgbmModel <-gbm(y ~ ., data = simulated, distribution ="gaussian", n.trees =1000, interaction.depth =3)# Let's extract and print the variable importance tablesummary(gbmModel, plotit =FALSE)
# Let's fit the Cubist model and predictor importancecubistModel <-cubist(x = simulated[, -which(names(simulated) =="y")], y = simulated$y, committees =10)varImp(cubistModel)
The boosted trees model concentrates importance on predictors V1-V5 as the random forest which receive large positive importance scores and giving little importance to V6-V10. Also, V1 relative influence(rel.inf) drops sharply while while duplicate1 picks up which means the model tends to latch onto whichever correlated variable is selected first in early boosting iterations, starving the others and making the dilution lopsided rather than even.
The Cubist model is less consistent.Its importance measures how often a variable is used in rules and linear models, not how much accuracy it adds. That makes it much less stable when predictors are correlated.
Exercise 8.2
Use a simulation to show tree bias with different granularity.
It is said in the first section of this chapter that regression trees like CART suffer from selection bias.Indeed, when choosing the splits points, predictors with a higher number of distinct values or higher granularity are favored over those with only a few. Our goal here is to simulate several unrelated predictors with different numbers of levels and show that predictors with more distinct values offer more candidate split points, increasing the probability that an uninformative noise predictor will be chosen over a true informative predictor with lower granularity.
a) Let’s load the libraries
library(rpart)library(party)
** b) Let’s define simulation parameters and the level granularity
set.seed(42)# Let's set the number of simulation iterationsn_sim <-1000# let's set the sample size per datasetn <-300# Let's define the level of granularitygranularities <-c(2, 5, 10, 25, 50, 100)predictors_names <-paste0("X_gran", granularities)predictors_names
# Let's define two empty vectors of the length of the number of simulation iterations to store which variable was chosen at the root splitrpart_root <-character(n_sim) ctree_root <-character(n_sim)
a) Simulation 1: NO predictor is related to the outcome
for (i in1:n_sim) {# Let's generate X1 (True signal, low granularity: 0 or 1) X1 <-sample(c(0, 1), size = n, replace =TRUE) X1# Let's generate response y with a moderate signal-to-noise ratio# X1 has a true effect of 0.5, noise has SD = 1.5 y <-0.5* X1 +rnorm(n, mean =0, sd =1.5) y# Let's generate noise predictors with varying granularities df <-data.frame(y = y, X_gran2 = X1)for (g in granularities[-1]) {# Create discrete uniform predictor with 'g' distinct levels col_name <-paste0("X_gran", g) df[[col_name]] <-sample(seq_len(g), size = n, replace =TRUE) }# Let's fit standard CART regression tree (rpart)# We will use maxdepth = 1 to strictly inspect the primary root split choice rpart_fit <-rpart(y ~ ., data = df, control =rpart.control(maxdepth =1, cp =0))if (nrow(rpart_fit$frame) >1) { rpart_root[i] <-as.character(rpart_fit$frame$var[1]) } else { rpart_root[i] <-"None" }rpart_fit # Let's fit Conditional Inference Tree (ctree) ctree_fit <-ctree(y ~ ., data = df, controls =ctree_control(maxdepth =1, mincriterion =0.01))# Let's extract root split variable name if a split occurred root_node <- ctree_fit@treeif (!root_node$terminal) { ctree_root[i] <- root_node$psplit$variableName } else { ctree_root[i] <-"None" }} ctree_fit
Conditional inference tree with 2 terminal nodes
Response: y
Inputs: X_gran2, X_gran5, X_gran10, X_gran25, X_gran50, X_gran100
Number of observations: 300
1) X_gran2 <= 0; criterion = 0.998, statistic = 13.08
2)* weights = 159
1) X_gran2 > 0
3)* weights = 141
For a smooth interpretation of the result of our simulations, we will create a summary table and create a plot of our results.
# Let's summarize the results into a data frame for a better visibilityresults <-rbind(data.frame(Model ="Greedy Tree (rpart)", Variable = rpart_root),data.frame(Model ="Conditional Inference Tree (ctree)", Variable = ctree_root))head(results)
Model Variable
1 Greedy Tree (rpart) X_gran5
2 Greedy Tree (rpart) X_gran2
3 Greedy Tree (rpart) X_gran2
4 Greedy Tree (rpart) X_gran25
5 Greedy Tree (rpart) X_gran2
6 Greedy Tree (rpart) X_gran2
tail(results)
Model Variable
1995 Conditional Inference Tree (ctree) X_gran2
1996 Conditional Inference Tree (ctree) X_gran2
1997 Conditional Inference Tree (ctree) X_gran2
1998 Conditional Inference Tree (ctree) X_gran10
1999 Conditional Inference Tree (ctree) X_gran2
2000 Conditional Inference Tree (ctree) X_gran2
# Filter out any runs where no split occurred and compute selection proportionsresults <-subset(results, Variable !="None")results$Variable <-factor(results$Variable, levels = predictors_names)summary_table <-prop.table(table(results$Model, results$Variable), margin =1) *100print(round(summary_table, 1))
X_gran2 X_gran5 X_gran10 X_gran25 X_gran50
Conditional Inference Tree (ctree) 87.5 3.0 2.5 2.6 2.6
Greedy Tree (rpart) 62.4 2.7 4.3 7.8 10.7
X_gran100
Conditional Inference Tree (ctree) 1.8
Greedy Tree (rpart) 12.1
# Visualize the selection biasggplot(results, aes(x = Variable, fill = Model)) +geom_bar(aes(y = (..count..)/tapply(..count.., ..fill.., sum)[..fill..]), position ="dodge") +scale_y_continuous(labels = scales::percent_format()) +labs(title ="Selection Bias in Regression Trees Across Predictor Granularities",subtitle ="X_gran2 is the ONLY true predictor; all others are pure random noise",x ="Predictor (Increasing Granularity ->)",y ="Percentage of Root Splits Selected" ) +theme_minimal() +theme(axis.text.x =element_text(angle =25, hjust =1))
Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(count)` instead.
In conclusion the bar graph clearly shows how predictor granularity causes selection bias in standard greedy regression trees rpart compared to conditional inference trees ctree. In fact, rpart exhibits a clear upward bias toward pure noise predictors as their granularity increases from X_gran5 to X_gran100, because more unique values provide more candidate split points to falsely minimize error by chance.
Exercise 8.3
In stochastic gradient boosting the bagging fraction and learning rate will govern the construction of the trees as they are guided by the gradient. Although the optimal values of these parameters should be obtained through the tuning process, it is helpful to understand how the magnitudes of these parameters affect magnitudes of variable importance. Figure8.24 above provides the variable importance plots for boosting using two extreme values for the bagging fraction (0.1 and 0.9) and the learning rate (0.1 and 0.9) for the solubility data. The left-hand plot has both parameters set to 0.1, and the right-hand plot has both set to 0.9:
a) Why does the model on the right focus its importance on just the first few of predictors,whereas the model on the left spreads importance across more predictors?
The main difference comes from the fact that the right-hand model uses a very large bagging fraction (0.9) and a very large learning rate/shrinkage parameter (0.9), while the left-hand model uses small values (0.1 and 0.1). In fact, we learned that boosting already has a steeper importance profile than random forests. That’s because each boosted tree depends on the ones before it, so they tend to share the same structure and choose the same predictors again and again. As a result, the right plot becomes a very greedy model whereas the left one is a heavily regularized model.
So a large learning rate (0.9) adds nearly the entire prediction of each new tree to the ensemble, therefore the initial trees greedily select the strongest global predictors (e.g., NumCarbon, MolWeight, SurfaceArea2), those top few variables capture almost all of the variance reduction, and later trees contribute very little. Whereas, A small learning rate (0.1) shrinks each tree’s contribution by 90%, meaning each tree removes only a tiny fraction of the residual error.
Moreover, with a large bagging fraction (0.9), almost all observations are available to every tree. As a result, the same strong predictors are repeatedly selected across many trees. In contrast, with a small bagging fraction(0.1), each tree is built on a random 10% of the samples. On such small, varied subsamples, the best split often goes to a different predictor.
b) Which model do you think would be more predictive of other samples?
following our previous analysis, the left-hand model (bagging fraction = 0.1, learning rate = 0.1) would likely be expected to have better predictive performance on future observations and for the following reasons:
Since boosting is greedy, Lower learning rates are known to reduce overfitting in gradient boosting because the model learns gradually and accumulates information over many trees.
Also, the model to the left builds its predictions from many predictors with small contributions, so it depends less on the quirks of a few variables in the training set. It is more stable, and it should hold up better on samples it hasn’t seen.
##c) How would increasing interaction depth affect the slope of predictor importance for either model in Fig. 8.24?
First of all, it is important to know that Interaction depth is the maximum depth of each tree, meaning deeper trees have more splits. Increasing interaction depth would lead to : * More predictors can participate in each tree through interaction terms. * Variables that are only useful in combination with other variables gain opportunities to contribute. * Importance is spread across a larger set of predictors.
In conclusion, increasing interaction depth would decrease the slope of the variable importance profile, spreading importance across a wider array of predictors in both models.
Exercise 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:
a) Which tree-based regression model gives the optimal resampling and test set performance?
Loading useful packages
library(AppliedPredictiveModeling)
Warning: package 'AppliedPredictiveModeling' was built under R version 4.5.3
# Pre-process (KNN imputation + remove near-zero variance, fit ONLY on training setpreProcObj <-preProcess(trainData_clean[, -1], method =c("knnImpute", "nzv"))# Let's apply the saved pre-processing rules to your datasetstrainX <-predict(preProcObj, trainData[, -1])testX <-predict(preProcObj, testData[, -1])# Let's separate the predictor variables from the response variabletrainY <- trainData$YieldtestY <- testData$Yield
Training tree-based model using the 10-fold cross validation control
After comparing resampling & test performance, we will test set RMSE and R^2 for Random Forest and Cubist models which according to what we have from the book they are presumably projected to be our best tree model.
# Test set RMSE & R2 (e.g., for Random Forest and Cubist) postResample(predict(rfTune, testX), testY)
RMSE Rsquared MAE
1.2523033 0.5499726 0.9397809
postResample(predict(cubistTune, testX), testY)
RMSE Rsquared MAE
0.8761695 0.7770534 0.7086188
The result of the test performance are as followed: Ensemble / Rule-Based Trees (Random Forest, Cubist, GBM): Typically achieve a resampled RMSE of ~0.58–0.65 (with R^2 0.73\() and a test set RMSE of ~0.55–0.65 (R^2 \approx 0.65\text{--}0.75\)). Cubist often matches or slightly edges out Random Forest on the test set .
Single Regression Tree (rpart): Performs noticeably worse (resampled RMSE typically ~0.85–1.05, \(R^2 \approx 0.35\text{--}0.48\)) due to high variance and coarse step-function predictions on a small dataset (n=176)
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?
# Let's plot the Variable importanceplot(varImp(rfTune), top =10)
As a result, Using varImp() (which measures the total reduction in residual sum of squares across all splits/trees for Random Forest/GBM, or rule/linear model usage frequency for Cubist), the top 10 predictors consistently are included in plot above.
We notice that Manufacturing process variables dominate the top 10 list, typically accounting for 6 to 7 of the top 10 predictors. However, biological variables still play a substantial role (3 to 4 of the top 10, notably BiologicalMaterial06, BiologicalMaterial03, and BiologicalMaterial02).
Regarding the difference on optimal linear and nonlinear models, Tree-based models spread importance across correlated predictors because random feature subsampling (mtry) allows correlated variables to substitute for one another across different trees, whereas Linear models (PLS/Lasso) distribute or zero out weights among highly correlated predictors, elevating predictors with strong global monotonic slopes.
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?
library(partykit)
Warning: package 'partykit' was built under R version 4.5.3
Loading required package: libcoin
Warning: package 'libcoin' was built under R version 4.5.3
Attaching package: 'partykit'
The following objects are masked from 'package:party':
cforest, ctree, ctree_control, edge_simple, mob, mob_control,
node_barplot, node_bivplot, node_boxplot, node_inner, node_surv,
node_terminal, varimp
# Let's plot the optimal single tre partyTree<-as.party(rpartTune$finalModel)plot( partyTree,drop_terminal=TRUE, # all terminal boxplots align cleanly at the bottom row rather than staggered at different tree depthsgp =gpar(fontsize =8), # Shrink overall text size to prevent overlapip_args =list(id =FALSE), # Hide redundant internal node ID numberstp_args =list(id =FALSE, # Hide terminal node ID numbers for cleaner headersylines =1.5# Add vertical spacing around terminal boxplots ))
###Results:
The plot shows the terminal nodes display boxplots or histograms of the Yield distribution for each partitioned subgroup.
a) Summary of Tree Structure & Terminal Yield Distributions
-Root split
The root split occurs on ManufacturingProcess32 which is splitting at the value of 0.209 separating lower-yielding runs (< 0.209) on the left from higher-yielding runs (=> 0.209) on the right.
- High Yield Branch (ManufacturingProcess32 >= 0.209):
Terminal Node 7 (n = 26): When BiologicalMaterial06 >= 0.747, no further splits are needed; this subgroup achieves the highest yield distribution, with a median around 42.5% (IQR roughly 41.5%–43.5%, reaching above 46%).
Terminal Node 6 (n = 11): When BiologicalMaterial06 < 0.747 and ManufacturingProcess23 < -0.301, the median yield remains high at roughly 42.0% (IQR 41.3%–43.1%).
Terminal Node 5 (n = 20): When BiologicalMaterial06 < 0.747 and ManufacturingProcess23 >= -0.301, median yield drops to approximately 40.3%
Terminal Node 4 (n = 10): When ManufacturingProcess17 < -0.429 and BiologicalMaterial11 >= -0.247, median yield recovers to approximately 41.5%.
Terminal Node 3 (n = 18): When ManufacturingProcess17 < -0.429 and BiologicalMaterial11 < -0.247, median yield is approximately 39.7%.
Terminal Node 2 (n = 28): When ManufacturingProcess17 >= -0.429 and BiologicalMaterial03 >= -0.326, median yield is approximately 39.3%.
Terminal Node 1 (n = 31): When ManufacturingProcess17 >= -0.429 and BiologicalMaterial03 < -0.326, batches experience the lowest yield distribution, with a median around 38.1% (IQR 37.7%–39.0%, with a low outlier near 35.3%).
Does this view of the data provide additional knowledge about the biological or process predictors and their relationship with yield?
Yes, the single regression tree provides valuable operational insights that linear and black-box nonlinear models obscure. In fact, While biological material predictors cannot be changed, the tree identifies exact process thresholds operators can adjust to protect or recover yield. Also, The hierarchical splits isolate the exact combination of conditions to avoid—specifically when ManufacturingProcess32 < 0.209, ManufacturingProcess17 >= -0.429, and BiologicalMaterial03 < -0.326 (n = 31), which produces the lowest median yield (~38.1%).