# Loading required packages
library(AppliedPredictiveModeling)
library(caret)
library(mlbench)
library(randomForest)
library(party)
library(gbm)
library(rpart)
library(kernlab)
library(pls)
library(RANN)DATA 624 Homework 9
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"
sim_base <- simulatedSame 200 points as Homework 8. V1 to V5 are in the equation and V6 to V10 are noise. A copy is kept as sim_base for later parts.
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)?
set.seed(624)
model1 <- randomForest(y ~ ., data = simulated,
importance = TRUE,
ntree = 1000)
rfImp1 <- varImp(model1, scale = FALSE)
rfImp1 Overall
V1 8.77564705
V2 6.63042098
V3 0.72355008
V4 7.82113637
V5 2.21853200
V6 0.07488538
V7 0.07351364
V8 -0.09603397
V9 0.05997620
V10 -0.08334506
No. V6 to V10 are between -0.10 and 0.07, close to zero, while V1 to V5 range from 0.72 to 8.78.
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?
set.seed(624)
cf_base <- cforest(y ~ ., data = sim_base,
controls = cforest_unbiased(ntree = 1000))
round(data.frame(Traditional = varimp(cf_base),
Conditional = varimp(cf_base, conditional = TRUE)), 3) Traditional Conditional
V1 8.702 5.531
V2 6.413 5.271
V3 0.021 0.015
V4 8.357 6.611
V5 1.800 1.145
V6 -0.022 -0.003
V7 0.084 -0.011
V8 -0.027 -0.010
V9 -0.025 -0.008
V10 -0.014 -0.003
set.seed(624)
cf_dup <- cforest(y ~ ., data = simulated,
controls = cforest_unbiased(ntree = 1000))
round(data.frame(Traditional = varimp(cf_dup),
Conditional = varimp(cf_dup, conditional = TRUE)), 3) Traditional Conditional
V1 5.306 2.126
V2 5.522 4.393
V3 0.027 0.018
V4 7.343 5.808
V5 1.605 0.973
V6 -0.001 0.020
V7 0.015 0.028
V8 -0.017 0.002
V9 -0.007 -0.012
V10 -0.023 -0.018
duplicate1 2.262 0.612
duplicate2 2.042 0.492
Without the copies, both measures rank V1, V4 and V2 at the top and V6 to V10 near zero, like the random forest. With the copies, the traditional measure drops V1 from 8.70 to 5.31, and the conditional measure drops it to 2.13 with the copies at only 0.61 and 0.49. The pattern is the same, but the conditional measure penalizes correlated predictors more.
d. Repeat this process with different tree models, such as boosted trees and Cubist. Does the same pattern occur?
set.seed(624)
gbm_base <- gbm(y ~ ., data = sim_base,
distribution = "gaussian",
n.trees = 1000, interaction.depth = 3,
shrinkage = 0.05)
set.seed(624)
gbm_dup <- gbm(y ~ ., data = simulated,
distribution = "gaussian",
n.trees = 1000, interaction.depth = 3,
shrinkage = 0.05)
summary(gbm_base, plotit = FALSE) var rel.inf
V4 V4 27.093158
V1 V1 25.318953
V2 V2 20.898190
V5 V5 11.517693
V3 V3 7.773681
V6 V6 2.025433
V7 V7 1.768332
V8 V8 1.288430
V9 V9 1.242317
V10 V10 1.073812
summary(gbm_dup, plotit = FALSE) var rel.inf
V4 V4 26.916353
V2 V2 20.554810
V1 V1 17.960869
V5 V5 10.876448
V3 V3 7.586618
duplicate1 duplicate1 5.528381
duplicate2 duplicate2 4.008762
V7 V7 1.783407
V6 V6 1.697435
V9 V9 1.092718
V8 V8 1.089187
V10 V10 0.905012
Same pattern. V1 drops from 25.3 to 18.0 and the copies take 5.5 and 4.0, moving V1 from second to third.
rp_base <- rpart(y ~ ., data = sim_base)
rp_dup <- rpart(y ~ ., data = simulated)
imp_rp <- varImp(rp_dup)
imp_rp$Base <- varImp(rp_base)[rownames(imp_rp), "Overall"]
round(imp_rp[order(-imp_rp$Overall), ], 2) Overall Base
V4 2.91 3.02
V5 2.34 2.45
V2 1.95 2.15
V1 1.38 1.62
duplicate2 1.29 NA
duplicate1 0.92 NA
V10 0.53 0.53
V7 0.51 0.51
V3 0.45 0.79
V6 0.41 0.55
V9 0.12 0.21
V8 0.00 0.09
The single tree shows it too, with V1 dropping from 1.62 to 1.38, almost tied with duplicate2 (1.29). V6 to V10 still get small scores (up to 0.55) because rpart counts surrogate splits.
8.2
Use a simulation to show tree bias with different granularities.
root_split <- function(effect = 0) {
n <- 200
sim <- data.frame(x1 = sample(1:2, n, replace = TRUE),
x2 = sample(1:10, n, replace = TRUE),
x3 = sample(1:100, n, replace = TRUE),
x4 = rnorm(n))
sim$y <- effect * sim$x1 + rnorm(n)
fit <- rpart(y ~ ., data = sim,
control = rpart.control(maxdepth = 1, cp = 0))
as.character(fit$frame$var[1])
}x1 has 2 values, x2 has 10, x3 has 100 and x4 is continuous. Each run fits a one split tree and returns the predictor used at the root.
set.seed(624)
splits <- replicate(500, root_split())
table(splits)splits
x1 x2 x3 x4
15 83 172 230
With no relationship to y, each predictor should be picked about 125 of 500 times. Instead x4 is picked 230 times and x1 only 15, since predictors with more values have more split points to choose from.
set.seed(624)
splits_x1 <- replicate(500, root_split(effect = 0.2))
table(splits_x1)splits_x1
x1 x2 x3 x4
91 63 159 187
Even when x1 is the only predictor related to y, it is picked only 91 times, behind x4 (187) and x3 (159).
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. Figure 8.24 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?
With a learning rate of 0.9, the first few trees fit most of the signal with the strongest predictors, leaving little for later trees. A bagging fraction of 0.9 also gives each tree almost the same data, so they keep picking the same splits. At 0.1, each tree adds a small step and sees a different 10% of the data, so more predictors get used.
b. Which model do you think would be more predictive of other samples?
The model on the left. The small learning rate and bagging fraction act as regularization, while the model on the right is greedy and more likely to overfit.
c. How would increasing interaction depth affect the slope of predictor importance for either model in Fig. 8.24?
Deeper trees use more predictors in each tree, so importance spreads out and the slope flattens for both models, more so for the one on the right.
8.7
Refer to Exercises 6.3 and 7.5 which describe a chemical manufacturing process. Use the same data imputation, data splitting, and preprocessing steps as before and train several tree based models:
data(ChemicalManufacturingProcess)
cmp <- ChemicalManufacturingProcess
x <- cmp[, -1]
yield <- cmp$Yield
set.seed(624)
idx <- createDataPartition(yield, p = 0.8, list = FALSE)
x_train <- x[idx, ]
x_test <- x[-idx, ]
y_train <- yield[idx]
y_test <- yield[-idx]
pp <- c("knnImpute", "nzv", "center", "scale")
ctrl <- trainControl(method = "cv", number = 10)Same split as Homework 7 and 8, 144 batches for training and 32 for testing.
set.seed(624)
pls_cmp <- train(x_train, y_train,
method = "pls",
tuneLength = 15,
preProc = pp,
trControl = ctrl)
set.seed(624)
svm_cmp <- train(x_train, y_train,
method = "svmRadial",
tuneLength = 14,
preProc = pp,
trControl = ctrl)PLS and SVM from 6.3 and 7.5 are refit for comparison.
set.seed(624)
rpart_cmp <- train(x_train, y_train,
method = "rpart2",
tuneGrid = data.frame(maxdepth = 1:10),
preProc = pp,
trControl = ctrl)
set.seed(624)
bag_cmp <- train(x_train, y_train,
method = "treebag",
preProc = pp,
trControl = ctrl)
set.seed(624)
rf_cmp <- train(x_train, y_train,
method = "rf",
tuneGrid = data.frame(mtry = c(5, 10, 15, 20, 30, 40, 50)),
importance = TRUE,
preProc = pp,
trControl = ctrl)
set.seed(624)
gbm_cmp <- train(x_train, y_train,
method = "gbm",
tuneGrid = expand.grid(interaction.depth = c(1, 3, 5),
n.trees = seq(100, 1000, by = 100),
shrinkage = c(0.01, 0.1),
n.minobsinnode = 10),
verbose = FALSE,
preProc = pp,
trControl = ctrl)rpart_cmp$bestTune maxdepth
2 2
rf_cmp$bestTune mtry
2 10
gbm_cmp$bestTune n.trees interaction.depth shrinkage n.minobsinnode
29 900 5 0.01 10
The optimal single tree has a depth of 2, the random forest uses mtry = 10, and the boosted model uses 900 trees, an interaction depth of 5 and a learning rate of 0.01.
a. Which tree based regression model gives the optimal resampling and test set performance?
perf <- function(fit, name, x_new, y_new) {
cv <- getTrainPerf(fit)
te <- postResample(predict(fit, x_new), y_new)
data.frame(Model = name,
CV_RMSE = cv$TrainRMSE, CV_R2 = cv$TrainRsquared,
Test_RMSE = te["RMSE"], Test_R2 = te["Rsquared"])
}
comp_tree <- rbind(perf(rpart_cmp, "Single tree", x_test, y_test),
perf(bag_cmp, "Bagged trees", x_test, y_test),
perf(rf_cmp, "Random forest", x_test, y_test),
perf(gbm_cmp, "Boosted trees", x_test, y_test),
perf(pls_cmp, "PLS", x_test, y_test),
perf(svm_cmp, "SVM", x_test, y_test))
rownames(comp_tree) <- NULL
comp_tree Model CV_RMSE CV_R2 Test_RMSE Test_R2
1 Single tree 1.497042 0.3382419 1.429456 0.5690628
2 Bagged trees 1.212511 0.5931417 1.312538 0.6867475
3 Random forest 1.133732 0.6846684 1.272885 0.7370429
4 Boosted trees 1.122059 0.6598676 1.188956 0.7242978
5 PLS 1.368345 0.5231989 1.201579 0.6756127
6 SVM 1.167241 0.5916503 1.146870 0.7474025
Boosted trees have the lowest RMSE among the tree models, both resampled (1.122) and on the test set (1.189), so they are the optimal tree model. The random forest has a higher R squared (0.685 and 0.737), and the single tree is the weakest. The SVM is still best on the test set overall (1.147).
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?
imp_gbm <- varImp(gbm_cmp)
top_gbm <- rownames(imp_gbm$importance)[order(-imp_gbm$importance$Overall)][1:10]
imp_gbmgbm variable importance
only 20 most important variables shown (out of 56)
Overall
ManufacturingProcess32 100.000
BiologicalMaterial12 23.476
ManufacturingProcess09 17.925
ManufacturingProcess31 17.741
BiologicalMaterial03 17.190
ManufacturingProcess13 16.845
BiologicalMaterial09 13.561
ManufacturingProcess06 13.066
ManufacturingProcess17 12.694
BiologicalMaterial05 7.857
ManufacturingProcess36 7.815
ManufacturingProcess37 7.087
BiologicalMaterial06 7.067
ManufacturingProcess43 7.035
ManufacturingProcess25 6.831
BiologicalMaterial11 6.260
ManufacturingProcess27 5.515
ManufacturingProcess24 5.512
ManufacturingProcess01 5.445
BiologicalMaterial10 5.020
table(substr(top_gbm, 1, 10))
Biological Manufactur
4 6
ManufacturingProcess32 dominates, with every other predictor under 24. Process predictors lead the top 10, 6 to 4.
imp_pls <- varImp(pls_cmp)
top_pls <- rownames(imp_pls$importance)[order(-imp_pls$importance$Overall)][1:10]
imp_svm <- varImp(svm_cmp)
top_svm <- rownames(imp_svm$importance)[order(-imp_svm$importance$Overall)][1:10]
intersect(top_gbm, top_pls)[1] "ManufacturingProcess32" "ManufacturingProcess09" "BiologicalMaterial03"
[4] "ManufacturingProcess13" "ManufacturingProcess06" "ManufacturingProcess17"
intersect(top_gbm, top_svm)[1] "ManufacturingProcess32" "BiologicalMaterial12" "ManufacturingProcess09"
[4] "ManufacturingProcess31" "BiologicalMaterial03" "ManufacturingProcess13"
unique_gbm <- setdiff(top_gbm, union(top_pls, top_svm))
unique_gbm[1] "BiologicalMaterial09" "BiologicalMaterial05"
round(cor(cmp[, unique_gbm], cmp$Yield, use = "complete.obs"), 3) [,1]
BiologicalMaterial09 0.092
BiologicalMaterial05 0.146
The boosted model shares 6 of its top 10 with PLS and 6 with the SVM. Like the SVM, it includes ManufacturingProcess31 and BiologicalMaterial12, which PLS misses. BiologicalMaterial09 and 05 are unique to it, but their correlations with yield are weak (0.09 and 0.15).
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?
tree_fit <- rpart_cmp$finalModel
tree_data <- predict(rpart_cmp$preProcess, x_train)
tree_data$.outcome <- y_train
tree_fit$model <- model.frame(tree_fit$terms, tree_data)
plot(partykit::as.party(tree_fit))The final tree from train does not keep its training data, so it is added back before plotting.
The splits are on standardized values because of the preprocessing, so they are converted back to the original units.
pr <- rpart_cmp$preProcess
vars <- c("ManufacturingProcess32", "BiologicalMaterial12", "BiologicalMaterial03")
cuts <- c(0.173, -0.615, 1.091)
round(pr$mean[vars] + cuts * pr$std[vars], 1)ManufacturingProcess32 BiologicalMaterial12 BiologicalMaterial03
159.5 19.7 72.0
The tree splits first on ManufacturingProcess32 at 159.5, then on BiologicalMaterial12 at 19.7 for lower values and BiologicalMaterial03 at 72 for higher ones. Yield rises from the left node to the right node, with the highest yields in batches that have high values of both ManufacturingProcess32 and BiologicalMaterial03. The process setting matters most, but raw material quality still shifts yield within each group.