DATA_624_Homework_9

Author

Long Lin

8.1

Recreate the simulated data from Exercise 7.2:

library(mlbench)
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"

a.

Fit a random forest model to all of the predictors, then estimate the variable importance scores:

library(randomForest)
randomForest 4.7-1.2
Type rfNews() to see new features/changes/bug fixes.
library(caret)
Loading required package: ggplot2

Attaching package: 'ggplot2'
The following object is masked from 'package:randomForest':

    margin
Loading required package: lattice
model1 <- randomForest(y ~ ., data = simulated,
  importance = TRUE,
  ntree = 1000)
rfImp1 <- varImp(model1, scale = FALSE)

Did the random forest model significantly use the uninformative predictors (V6 – V10)?

print(rfImp1)
         Overall
V1   8.732235404
V2   6.415369387
V3   0.763591825
V4   7.615118809
V5   2.023524577
V6   0.165111172
V7  -0.005961659
V8  -0.166362581
V9  -0.095292651
V10 -0.074944788

The random forest model did not significantly use the uninformative predictors (V6 – V10). The value for V6 was only 0.165, and the values for V7-V10 were all negative.

b.

Now add an additional predictor that is highly correlated with one of the informative predictors. For example:

set.seed(200)
simulated_original <- simulated
simulated$duplicate1 <- simulated$V1 + rnorm(200) * .1
cor(simulated$duplicate1, simulated$V1)
[1] 0.9497025

Fit another random forest model to these data. Did the importance score for V1 change? What happens when you add another predictor that is also highly correlated with V1?

model2 <- randomForest(y ~ ., data = simulated,
  importance = TRUE,
  ntree = 1000)
rfImp2 <- varImp(model2, scale = FALSE)
print(rfImp2)
               Overall
V1          6.00709780
V2          6.05937899
V3          0.58465293
V4          6.86363294
V5          2.19939891
V6          0.10898039
V7          0.06104207
V8         -0.04059204
V9          0.06123662
V10         0.09999339
duplicate1  4.43323167

The importance score for V1 did change after adding an additional predictor that is highly correlated with V1, it went from about 8.73 to about 6.00. After the change, the importance score for V4 took the the top spot with an overall value of about 6.86.

set.seed(200)
simulated$duplicate2 <- simulated$V1 + rnorm(200) * .1
cor(simulated$duplicate2, simulated$V1)
[1] 0.9497025
model3 <- randomForest(y ~ ., data = simulated,
  importance = TRUE,
  ntree = 1000)
rfImp3 <- varImp(model3, scale = FALSE)
print(rfImp3)
               Overall
V1          4.84857115
V2          6.50242654
V3          0.51808831
V4          7.21616819
V5          2.11631632
V6          0.22066363
V7         -0.02066815
V8         -0.06964769
V9         -0.02908959
V10        -0.03105942
duplicate1  2.84168163
duplicate2  2.94318033

When you add another predictor that is also highly correlated with V1, it dilutes the importance of V1 even further to 4.84. The importance for V4 went even further up and the importance score for V2 also passed that of V1. The V6-V10 predictors are still insignificant though, so those did not change.

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?

library(partykit)
Loading required package: grid
Loading required package: libcoin
Loading required package: mvtnorm
set.seed(200)
cf_simulated <- cforest(y ~ ., data = simulated_original)

cf_cond_false <- varimp(cf_simulated, conditional = FALSE)
cf_cond_true   <- varimp(cf_simulated, conditional = TRUE)


data.frame(
  Conditional_False = cf_cond_false,
  Conditional_True   = cf_cond_true
)
    Conditional_False Conditional_True
V1         8.04166864        5.8454101
V2         6.21307352        5.0272517
V3         0.23458171        0.2313670
V4         7.55930190        6.2533209
V5         2.13338717        1.4521394
V6         0.07895189       -0.2014898
V7         0.21504772       -0.2234096
V8        -0.30008835       -0.2420770
V9        -0.04506062       -0.2634202
V10       -0.24685120       -0.1054899
set.seed(200)
simulated <- simulated_original
simulated$duplicate1 <- simulated$V1 + rnorm(200) * 0.1

set.seed(200)
cf_simulated2 <- cforest(y ~ ., data = simulated)

cf_cond_false2 <- varimp(cf_simulated2, conditional = FALSE)
cf_cond_true2  <- varimp(cf_simulated2, conditional = TRUE)

data.frame(
  Conditional_False = cf_cond_false2,
  Conditional_True  = cf_cond_true2
)
           Conditional_False Conditional_True
V1                6.89372200        3.7794916
V2                5.42681890        4.7508529
V3                0.29078586        0.1893469
V4                6.73970307        6.0649958
V5                2.20524074        1.5127378
V6               -0.21894079       -0.3014418
V7                0.10827801       -0.1260085
V8               -0.04952383       -0.2312845
V9                0.06521191       -0.2109473
V10              -0.16405103       -0.2032378
duplicate1        4.54149915        2.4449479

These importances show the same pattern as the traditional random forest model. The V1 importance value goes down when you add another predictor that is highly correlated with it. The V6-V10 predictors are sitll the lowest importance values as well.

d.

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

Boosted trees

library(gbm)
Loaded gbm 2.3.1
This version of gbm is no longer under development. Consider transitioning to gbm3, https://github.com/gbm-developers/gbm3
set.seed(200)
gbm_original <- gbm(y ~ ., data = simulated_original, distribution = "gaussian", n.trees = 1000)

gbmImp1 <- varImp(gbm_original, numTrees = 1000, scale = FALSE)

print(gbmImp1)
      Overall
V1  4703.5564
V2  3908.9573
V3  1793.4126
V4  4996.0711
V5  2355.8812
V6   485.5785
V7   577.6274
V8   379.8224
V9   347.4833
V10  324.0831
set.seed(200)
gbm_additional <- gbm(y ~ ., data = simulated, distribution = "gaussian", n.trees = 1000)

gbmImp2 <- varImp(gbm_additional, numTrees = 1000, scale = FALSE)

print(gbmImp2)
             Overall
V1         4058.8385
V2         3872.7462
V3         1785.5112
V4         4957.8414
V5         2367.2412
V6          481.2560
V7          576.7949
V8          324.4181
V9          324.5805
V10         351.1916
duplicate1  964.2617

Boosted trees also follows the same trend. With the additional duplicate predictor, the importance value of V1 goes down. Meanwhile the V6-V10 predictors are still the lowest values.

Cubist

library(Cubist)
set.seed(200)
cubist_original <- cubist(x = simulated_original[, names(simulated_original) != "y"], y = simulated_original$y, committees = 100)

cubistImp1 <- varImp(cubist_original)

print(cubistImp1)
    Overall
V1     71.5
V3     47.0
V2     58.5
V4     48.0
V5     33.0
V6      0.0
V7      0.0
V8      0.0
V9      0.0
V10     0.0
set.seed(200)
cubist_additional <- cubist(x = simulated[, names(simulated) != "y"], y = simulated$y, committees = 100)

cubistImp2 <- varImp(cubist_additional)

print(cubistImp2)
           Overall
V1            71.0
V3            46.5
V2            59.0
V4            48.0
V5            32.5
V6            12.0
V7             0.0
V8             0.0
V9             0.0
V10            0.0
duplicate1     0.0

The cubist tree model follows the same trend although it seems like the drop is not as steep as the drop for the other models with only a small decline from 71.5 to 71.

8.2

Use a simulation to show tree bias with different granularities.

library(rpart)

set.seed(200)

root_splits <- replicate(500, {
  df <- data.frame(
    y      = rnorm(200),
    x_2    = sample(1:2, 200, replace = TRUE),
    x_10   = sample(1:10, 200, replace = TRUE),
    x_50   = sample(1:50, 200, replace = TRUE),
    x_cont = rnorm(200)
  )
  
  fit <- rpart(
    y ~ ., 
    data = df, 
    control = rpart.control(maxdepth = 1, cp = 0)
  )
  
  as.character(fit$frame$var[1])
})

prop.table(table(root_splits))
root_splits
  x_10    x_2   x_50 x_cont 
 0.200  0.022  0.350  0.428 

The simulation results show that there was not an equal split between the predictors and that there is indeed selection bias. The continuous predictor was chosen 42.8% of the time while the predictor with the lowest percentage was the predictor with 2 unique values. This shows that rpart strongly favors predictors with more unique values.

8.3

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?

The model on the right focuses its importance on just the first few of the predictors because it has a higher learning rate and a higher bagging fraction. The higher learning rate and higher bagging fraction puts more emphasis on the first few predictors and leads to a higher importance value for those predictors. The model on the left with the lower learning rate and lower bagging fraction will go through more iterations therefore giving more predictors a share of the importance score leading to a less steep curve in the importance scores compared to the model on the right.

b.

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

I think the model on the left will be more predictive of other samples because with the lower bagging fraction and learning rate, there is less risk of overfitting. The model on the left also has more variance in the predictors’ importance scores.

c.

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

Increasing the interaction depth will decrease the slope of the predictor importance for both of them models. This is because as the interaction depth increases, each model makes more splits which leads to deeper nodes using more predictors. Thus spreading out the importance scores.

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:

library(AppliedPredictiveModeling)
library(caret)
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.0     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ lubridate 1.9.5     ✔ tibble    3.3.1
✔ purrr     1.2.1     ✔ tidyr     1.3.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::combine()  masks randomForest::combine()
✖ dplyr::filter()   masks stats::filter()
✖ dplyr::lag()      masks stats::lag()
✖ purrr::lift()     masks caret::lift()
✖ ggplot2::margin() masks randomForest::margin()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(RANN)
library(earth)
Loading required package: Formula
Loading required package: plotmo
Loading required package: plotrix
library(kernlab)

Attaching package: 'kernlab'

The following object is masked from 'package:purrr':

    cross

The following object is masked from 'package:ggplot2':

    alpha
library(nnet)
data(ChemicalManufacturingProcess)

impute_model <- preProcess(ChemicalManufacturingProcess[, -1], method = "knnImpute")

predictors_imputed <- predict(impute_model, ChemicalManufacturingProcess[, -1])

chem_imputed <- bind_cols(Yield = ChemicalManufacturingProcess$Yield, predictors_imputed)

nzv_predictors <- nearZeroVar(chem_imputed)
if(length(nzv_predictors) > 0){
  chem_imputed <- chem_imputed[, -nzv_predictors]
}

set.seed(8585)
index <- createDataPartition(chem_imputed$Yield, p = 0.8, list = FALSE)

training_data <- chem_imputed[index, ]
test_data  <- chem_imputed[-index, ]

training_x <- training_data[, -1]
training_y <- training_data$Yield
test_x <- test_data[, -1]
test_y <- test_data$Yield

ctrl <- trainControl(method = "cv", number = 10)

Single Regression Tree (CART)

set.seed(8585)
rpart_fit <- train(
  x = training_x,
  y = training_y,
  method = "rpart",
  tuneLength = 10,
  trControl = ctrl
)
Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,
: There were missing values in resampled performance measures.
rpart_resamp <- getTrainPerf(rpart_fit) |>
  select(RMSE = TrainRMSE, Rsquared = TrainRsquared, MAE = TrainMAE) |>
  mutate(Set = "Resampling", .before = 1)

rpart_preds <- predict(rpart_fit, newdata = test_x)
rpart_test  <- postResample(pred = rpart_preds, obs = test_y) |>
  as_tibble_row() |>
  mutate(Set = "Test", .before = 1)

rpart_metrics <- bind_rows(rpart_resamp, rpart_test) |>
  mutate(Model = "CART", .before = 1)

rpart_metrics
  Model        Set     RMSE  Rsquared      MAE
1  CART Resampling 1.404164 0.4866513 1.108052
2  CART       Test 1.442207 0.3818624 1.062822

Bagged Trees

set.seed(8585)
bag_fit <- train(
  x = training_x,
  y = training_y,
  method = "treebag",
  trControl = ctrl
)

bag_resamp <- getTrainPerf(bag_fit) |>
  select(RMSE = TrainRMSE, Rsquared = TrainRsquared, MAE = TrainMAE) |>
  mutate(Set = "Resampling", .before = 1)

bag_preds <- predict(bag_fit, newdata = test_x)
bag_test  <- postResample(pred = bag_preds, obs = test_y) |>
  as_tibble_row() |>
  mutate(Set = "Test", .before = 1)

bag_metrics <- bind_rows(bag_resamp, bag_test) |>
  mutate(Model = "Bagged Trees", .before = 1)

bag_metrics
         Model        Set     RMSE  Rsquared       MAE
1 Bagged Trees Resampling 1.290493 0.5733760 0.9869980
2 Bagged Trees       Test 1.113716 0.5952913 0.7919775

Random Forest

set.seed(8585)
rf_fit <- train(
  x = training_x,
  y = training_y,
  method = "rf",
  tuneLength = 10,
  importance = TRUE,
  trControl = ctrl
)

rf_resamp <- getTrainPerf(rf_fit) |>
  select(RMSE = TrainRMSE, Rsquared = TrainRsquared, MAE = TrainMAE) |>
  mutate(Set = "Resampling", .before = 1)

rf_preds <- predict(rf_fit, newdata = test_x)
rf_test  <- postResample(pred = rf_preds, obs = test_y) |>
  as_tibble_row() |>
  mutate(Set = "Test", .before = 1)

rf_metrics <- bind_rows(rf_resamp, rf_test) |>
  mutate(Model = "Random Forest", .before = 1)

rf_metrics
          Model        Set      RMSE  Rsquared       MAE
1 Random Forest Resampling 1.1661654 0.6623216 0.9001449
2 Random Forest       Test 0.9608506 0.7083806 0.7194099

Stochastic Gradient Boosting (GBM)

set.seed(8585)
gbm_grid <- expand.grid(
  interaction.depth = c(1, 3, 5),
  n.trees = seq(50, 500, by = 50),
  shrinkage = c(0.01, 0.05, 0.1),
  n.minobsinnode = 10
)

gbm_fit <- train(
  x = training_x,
  y = training_y,
  method = "gbm",
  tuneGrid = gbm_grid,
  trControl = ctrl,
  verbose = FALSE
)

gbm_resamp <- getTrainPerf(gbm_fit) |>
  select(RMSE = TrainRMSE, Rsquared = TrainRsquared, MAE = TrainMAE) |>
  mutate(Set = "Resampling", .before = 1)

gbm_preds <- predict(gbm_fit, newdata = test_x)
gbm_test  <- postResample(pred = gbm_preds, obs = test_y) |>
  as_tibble_row() |>
  mutate(Set = "Test", .before = 1)

gbm_metrics <- bind_rows(gbm_resamp, gbm_test) |>
  mutate(Model = "GBM", .before = 1)

gbm_metrics
  Model        Set      RMSE  Rsquared       MAE
1   GBM Resampling 1.1412230 0.6605708 0.8653036
2   GBM       Test 0.8821569 0.7449699 0.6850148

Cubist

set.seed(8585)
cubist_fit <- train(
  x = training_x,
  y = training_y,
  method = "cubist",
  tuneGrid = expand.grid(committees = c(1, 5, 10, 20), neighbors = c(0, 3, 5, 9)),
  trControl = ctrl
)

cubist_resamp <- getTrainPerf(cubist_fit) |>
  select(RMSE = TrainRMSE, Rsquared = TrainRsquared, MAE = TrainMAE) |>
  mutate(Set = "Resampling", .before = 1)

cubist_preds <- predict(cubist_fit, newdata = test_x)
cubist_test  <- postResample(pred = cubist_preds, obs = test_y) |>
  as_tibble_row() |>
  mutate(Set = "Test", .before = 1)

cubist_metrics <- bind_rows(cubist_resamp, cubist_test) |>
  mutate(Model = "Cubist", .before = 1)

cubist_metrics
   Model        Set      RMSE  Rsquared       MAE
1 Cubist Resampling 0.9450973 0.7668565 0.7417569
2 Cubist       Test 0.7801177 0.7975513 0.6537008
all_metrics <- bind_rows(
  rpart_metrics,
  bag_metrics,
  rf_metrics,
  gbm_metrics,
  cubist_metrics
) |>
  arrange(Set, RMSE)

all_metrics
           Model        Set      RMSE  Rsquared       MAE
1         Cubist Resampling 0.9450973 0.7668565 0.7417569
2            GBM Resampling 1.1412230 0.6605708 0.8653036
3  Random Forest Resampling 1.1661654 0.6623216 0.9001449
4   Bagged Trees Resampling 1.2904928 0.5733760 0.9869980
5           CART Resampling 1.4041637 0.4866513 1.1080523
6         Cubist       Test 0.7801177 0.7975513 0.6537008
7            GBM       Test 0.8821569 0.7449699 0.6850148
8  Random Forest       Test 0.9608506 0.7083806 0.7194099
9   Bagged Trees       Test 1.1137160 0.5952913 0.7919775
10          CART       Test 1.4422073 0.3818624 1.0628220

a.

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

The Cubist model gives the optimal resampling and test set performance due having the lowest RMSE scores for both sets as well as the highest Rsqaured scores for both sets.

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?

top_10_tree <- varImp(cubist_fit)$importance |>
  rownames_to_column("Predictor") |>
  arrange(desc(Overall)) |>
  slice_head(n = 10) |>
  mutate(Type = if_else(str_starts(Predictor, "Manufacturing"), "Process", "Biological"))

print(top_10_tree)
                Predictor   Overall       Type
1  ManufacturingProcess32 100.00000    Process
2  ManufacturingProcess17  60.97561    Process
3    BiologicalMaterial02  59.75610 Biological
4  ManufacturingProcess13  48.78049    Process
5    BiologicalMaterial03  46.34146 Biological
6  ManufacturingProcess29  42.68293    Process
7    BiologicalMaterial06  32.92683 Biological
8  ManufacturingProcess04  32.92683    Process
9  ManufacturingProcess27  30.48780    Process
10 ManufacturingProcess09  28.04878    Process
top_10_tree |> count(Type)
        Type n
1 Biological 3
2    Process 7
plot(varImp(cubist_fit), top = 10, main = "Top 10 Important Variables (Cubist)")

set.seed(200)
svm_model <- train(x = training_x, y = training_y, 
                 method = "svmRadial", 
                 tuneLength = 10, 
                 trControl = ctrl)
svm_model
Support Vector Machines with Radial Basis Function Kernel 

144 samples
 56 predictor

No pre-processing
Resampling: Cross-Validated (10 fold) 
Summary of sample sizes: 130, 129, 129, 130, 131, 131, ... 
Resampling results across tuning parameters:

  C       RMSE      Rsquared   MAE      
    0.25  1.444211  0.4895204  1.1806061
    0.50  1.346477  0.5207197  1.0976668
    1.00  1.281661  0.5580941  1.0434639
    2.00  1.228883  0.5825904  1.0021677
    4.00  1.209414  0.5876187  0.9711280
    8.00  1.191013  0.6021931  0.9575093
   16.00  1.190248  0.6026218  0.9566994
   32.00  1.190248  0.6026218  0.9566994
   64.00  1.190248  0.6026218  0.9566994
  128.00  1.190248  0.6026218  0.9566994

Tuning parameter 'sigma' was held constant at a value of 0.01473484
RMSE was used to select the optimal model using the smallest value.
The final values used for the model were sigma = 0.01473484 and C = 16.
svm_imp <- varImp(svm_model)
plot(svm_imp, top = 10, main = "Top 10 Important Variables (SVM)")

set.seed(8585)
pls_mod <- train(x = training_x, y = training_y, method = "pls", tuneLength = 10, trControl = ctrl)
plot(varImp(pls_mod), top = 10, main = "Top 10 Important Variables (PLS)")

Attaching package: 'pls'
The following object is masked from 'package:caret':

    R2
The following object is masked from 'package:stats':

    loadings

In the Cubist model, which was the optimal tree-based regression model, Manufacturing Processes dominated the list with only one Biological variable in the top 10. The three most important predictors were ManufacturingProcess32, ManufacturingProcess13, and ManufacturingProcess17. This was also very similar to the optimal linear model being the PLS, which shares the same top three predictors just with the top second and third predictors reversed. The optimal nonlinear model though had a those three predictors in the top four of its predictors with the added predictor BiologicalMaterial06 at number three.

When you zoom out and look at the top ten predictors though, it paints a slightly different story. The Cubist tree model only has one biological variable whereas the nonlinear SVM model has 4 biological variables and the linear PLS model has 3 biological variables.

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?

optimal_single_tree <- rpart_fit$finalModel

rpart.plot::rpart.plot(optimal_single_tree)

This view of the data does provide additional knowledge about the predictors and their relationship with yield. At each of the splits in the tree, you are able to see how each predictor affects the yield. At the top of the tree, if you have ManufacturingProcess32 less than 0.19, then you would have a yield of 39 as opposed to a yield of 42. Then if you have ManufacturingProcess32 less than 0.19, you would check to see if you have BiologicalMaterial12 less than -0.6. If the BiologicalMaterial12 predictor is less than -0.6 then you you will have a yield of 38 and then you’d check whether your BiologicalMaterial05 predictor is greater than or equal to 0.52. If it is greater than or equal to 0.52 then your yield will be 37. Otherwise the yield will be 39.