Predictive Modeling Homework 7

Author

Cheryl Chiu (wky301)

Published

April 6, 2025

Load libraries

library(ISLR)
library(tree)
library(randomForest)
library(BART)
library(caret)
library(dplyr)

Exercise 3

Consider the Gini index, classification error, and entropy in a simple classification setting with two classes. Create a single plot that dis- plays each of these quantities as a function of pˆm1. The x-axis should display pˆm1, ranging from 0 to 1, and the y-axis should display the value of the Gini index, classification error, and entropy. Hint: In a setting with two classes, pˆm1 = 1 − pˆm2. You could make this plot by hand, but it will be much easier to make in R.

p <- seq(0, 1, length.out = 200)

gini <- 2 * p * (1 - p)
class_error <- 1 - pmax(p, 1 - p)
entropy <- -p * log2(p) - (1 - p) * log2(1 - p)
entropy[is.nan(entropy)] <- 0  

plot(p, gini, type = "l", col = "lightblue", lwd = 2,
     ylab = "Impurity Measure", xlab = expression(hat(p)[m1]),
     main = "Gini index, classification error, and entropy",
     ylim = c(0, 1))
lines(p, class_error, col = "lightgreen", lwd = 2)
lines(p, entropy, col = "darkred", lwd = 2)
legend("bottom", legend = c("Gini index", "Classification error", "Entropy"),
       col = c("lightblue", "lightgreen", "darkred"), lwd = 2, bty = "n")

Exercise 8

In the lab, a classification tree was applied to the Carseats data set af- ter converting Sales into a qualitative response variable. Now we will seek to predict Sales using regression trees and related approaches, treating the response as a quantitative variable.

(a) Split the data set into a training set and a test set.

data(Carseats)
set.seed(123)
train_idx <- sample(1:nrow(Carseats), nrow(Carseats) / 2)
train <- Carseats[train_idx, ]
test <- Carseats[-train_idx, ]

(b) Fit a regression tree to the training set. Plot the tree, and inter- pret the results. What test MSE do you obtain?

tree_carseats <- tree(Sales ~ ., data = train)

dev.new(width=5, height=24, unit="in")
plot(tree_carseats)
text(tree_carseats, pretty = 0, cex=.55)

pred_tree <- predict(tree_carseats, newdata = test)
mse_tree <- mean((pred_tree - test$Sales)^2)
mse_tree
[1] 4.395357

🔴 Answer: MSE = 4.395357.

(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?

cv = cv.tree(tree_carseats, FUN = prune.tree)
par(mfrow = c(1,2))
plot(cv$size, cv$dev, type = "b")
plot(cv$k, cv$dev, type = "b")

cv_car = cv.tree(tree_carseats, FUN = prune.tree)
dev.new(width=5, height=4, unit="in")
par(mfrow = c(1, 2))
plot(cv_car$size, cv_car$dev, type = "b")
plot(cv_car$k, cv_car$dev, type = "b")

car_prune = prune.tree(tree_carseats, best = 15)
dev.new(width=5, height=24, unit="in")
par(mfrow = c(1, 1))
plot(car_prune)
text(car_prune, pretty = 0, cex=.55)

prune_pred = predict(car_prune, test)
(prune_mse=mean((test$Sales - prune_pred)^2))
[1] 4.591618

🔴 Answer: The pruning MSE is increased to 4.591618.

(d) Use the bagging approach in order to analyze this data. What test MSE do you obtain? Use the importance() function to de- termine which variables are most important.

set.seed(123)
bagging_model <- randomForest(Sales ~ ., data = train, mtry = ncol(train) - 1, importance = TRUE)
pred_bag <- predict(bagging_model, newdata = test)
mse_bag <- mean((pred_bag - test$Sales)^2)
mse_bag
[1] 2.76144
importance <- importance(bagging_model) |>
  as.data.frame() |>
  arrange(desc(`%IncMSE`))
print(importance)
               %IncMSE IncNodePurity
ShelveLoc   48.3345635    387.886972
Price       44.3578602    380.255094
CompPrice   20.3414969    158.911610
Age         18.6296851    187.107660
Income       6.6237140     90.369331
Advertising  5.7777253     72.793558
Education    2.6619834     55.987493
Urban        0.9276070      8.152320
US           0.4202302      5.900097
Population  -2.2001506     55.786278

🔴 Answer: The MSE is improved to 2.76144. ShelveLoc, Price, CompPrice, and Age are the most important variables.

(e) Use random forests to analyze this data. What test MSE do you obtain? Use the importance() function to determine which vari- ables are most important. Describe the effect of m, the number of variables considered at each split, on the error rate obtained.

car_rf = randomForest(Sales ~ ., data = train, mtry = 7, ntree = 500, 
    importance = T)
pred_rf = predict(car_rf, test)

rf_mse=mean((test$Sales - pred_rf)^2)
rf_mse
[1] 2.859611
importance(car_rf)
               %IncMSE IncNodePurity
CompPrice   18.8205307    153.440176
Income       4.5999565     97.306475
Advertising  9.0450046     81.235935
Population  -0.4811541     69.773327
Price       43.8479680    360.824655
ShelveLoc   48.0255731    358.680198
Age         17.9070293    197.465653
Education    2.6665378     60.464745
Urban       -1.0008403      9.474273
US           2.2103786      7.563025
varImpPlot(car_rf)

🔴 Answer: The MSE is 2.859611. ShelveLoc, Price, CompPrice, and Age are still the most important variables.

**(f) Now analyze the data using BART, and report your results.

set.seed(123)
x_train <- train[, -which(names(train) == "Sales")]
x_test <- test[, -which(names(test) == "Sales")]
y_train <- train$Sales

bart_model <- gbart(x.train = x_train, y.train = y_train, x.test = x_test)
*****Calling gbart: type=1
*****Data:
data:n,p,np: 200, 14, 200
y1,yn: 3.230000, 3.070000
x1,x[n*p]: 104.000000, 1.000000
xp1,xp[np*p]: 138.000000, 1.000000
*****Number of Trees: 200
*****Number of Cut Points: 63 ... 1
*****burn,nd,thin: 100,1000,1
*****Prior:beta,alpha,tau,nu,lambda,offset: 2,0.95,0.260569,3,0.191523,7.43
*****sigma: 0.991574
*****w (weights): 1.000000 ... 1.000000
*****Dirichlet:sparse,theta,omega,a,b,rho,augment: 0,0,1,0.5,1,14,0
*****printevery: 100

MCMC
done 0 (out of 1100)
done 100 (out of 1100)
done 200 (out of 1100)
done 300 (out of 1100)
done 400 (out of 1100)
done 500 (out of 1100)
done 600 (out of 1100)
done 700 (out of 1100)
done 800 (out of 1100)
done 900 (out of 1100)
done 1000 (out of 1100)
time: 2s
trcnt,tecnt: 1000,1000
pred_bart <- bart_model$yhat.test.mean
mse_bart <- mean((pred_bart - test$Sales)^2)
mse_bart
[1] 1.622453

🔴 Answer:The BART model was run with 200 trees using a burn-in of 100 iterations and 1100 total MCMC iterations. The final MSE is 1.622453.

Exercise 9

This problem involves the OJ data set which is part of the ISLR2 package. (a) Create a training set containing a random sample of 800 obser- vations, and a test set containing the remaining observations.

set.seed(1)
train_idx <- sample(1:nrow(OJ), 800)
train <- OJ[train_idx, ]
test <- OJ[-train_idx, ]

(b) Fit a tree to the training data, with Purchase as the response and the other variables as predictors. Use the summary() function to produce summary statistics about the tree, and describe the results obtained. What is the training error rate? How many terminal nodes does the tree have?

tree_oj <- tree(Purchase ~ ., data = train)
summary(tree_oj)

Classification tree:
tree(formula = Purchase ~ ., data = train)
Variables actually used in tree construction:
[1] "LoyalCH"       "PriceDiff"     "SpecialCH"     "ListPriceDiff"
[5] "PctDiscMM"    
Number of terminal nodes:  9 
Residual mean deviance:  0.7432 = 587.8 / 791 
Misclassification error rate: 0.1588 = 127 / 800 

🔴 Answer: The tree uses LoyalCH, PriceDiff,SpecialCH, ListPriceDiff, and PctDiscMM variables. training error rate is 0.1588. The tree has 9 terminal nodes.

(c) Type in the name of the tree object in order to get a detailed text output. Pick one of the terminal nodes, and interpret the information displayed.

tree_oj
node), split, n, deviance, yval, (yprob)
      * denotes terminal node

 1) root 800 1073.00 CH ( 0.60625 0.39375 )  
   2) LoyalCH < 0.5036 365  441.60 MM ( 0.29315 0.70685 )  
     4) LoyalCH < 0.280875 177  140.50 MM ( 0.13559 0.86441 )  
       8) LoyalCH < 0.0356415 59   10.14 MM ( 0.01695 0.98305 ) *
       9) LoyalCH > 0.0356415 118  116.40 MM ( 0.19492 0.80508 ) *
     5) LoyalCH > 0.280875 188  258.00 MM ( 0.44149 0.55851 )  
      10) PriceDiff < 0.05 79   84.79 MM ( 0.22785 0.77215 )  
        20) SpecialCH < 0.5 64   51.98 MM ( 0.14062 0.85938 ) *
        21) SpecialCH > 0.5 15   20.19 CH ( 0.60000 0.40000 ) *
      11) PriceDiff > 0.05 109  147.00 CH ( 0.59633 0.40367 ) *
   3) LoyalCH > 0.5036 435  337.90 CH ( 0.86897 0.13103 )  
     6) LoyalCH < 0.764572 174  201.00 CH ( 0.73563 0.26437 )  
      12) ListPriceDiff < 0.235 72   99.81 MM ( 0.50000 0.50000 )  
        24) PctDiscMM < 0.196196 55   73.14 CH ( 0.61818 0.38182 ) *
        25) PctDiscMM > 0.196196 17   12.32 MM ( 0.11765 0.88235 ) *
      13) ListPriceDiff > 0.235 102   65.43 CH ( 0.90196 0.09804 ) *
     7) LoyalCH > 0.764572 261   91.20 CH ( 0.95785 0.04215 ) *

🔴 Answer: Terminal node 4 represents a subset of customers with low loyalty scores (LoyalCH < 0.280875) after initially having LoyalCH < 0.5036. In this group of 177 customers, about 86.4% are predicted to purchase MM.

(d) Create a plot of the tree, and interpret the results.

dev.new(width=5, height=24, unit="in")
plot(tree_oj)
text(tree_oj, pretty = 0,cex=0.55)

🔴 Answer: Customer loyalty (LoyalCH) is the primary driver of purchase behavior. Customers with a LoyalCH value below 0.5036 are more likely to choose MM. In contrast, those with a LoyalCH above 0.5036 tend to purchase CH more.

**(e) Predict the response on the test data, and produce a confusion matrix comparing the test labels to the predicted test labels. What is the test error rate?

pred_oj <- predict(tree_oj, newdata = test, type = "class")
confusionMatrix(test$Purchase, pred_oj)
Confusion Matrix and Statistics

          Reference
Prediction  CH  MM
        CH 160   8
        MM  38  64
                                          
               Accuracy : 0.8296          
                 95% CI : (0.7794, 0.8725)
    No Information Rate : 0.7333          
    P-Value [Acc > NIR] : 0.0001259       
                                          
                  Kappa : 0.6154          
                                          
 Mcnemar's Test P-Value : 1.904e-05       
                                          
            Sensitivity : 0.8081          
            Specificity : 0.8889          
         Pos Pred Value : 0.9524          
         Neg Pred Value : 0.6275          
             Prevalence : 0.7333          
         Detection Rate : 0.5926          
   Detection Prevalence : 0.6222          
      Balanced Accuracy : 0.8485          
                                          
       'Positive' Class : CH              
                                          
cm <- table(Actual = test$Purchase, Predicted = pred_oj)
test_error_rate <- 1 - sum(diag(cm)) / sum(cm)
test_error_rate
[1] 0.1703704

🔴 Answer: The test error rate is 17.03%.

(f) Apply the cv.tree() function to the training set in order to determine the optimal tree size.

cv_oj = cv.tree(tree_oj, FUN = prune.tree)

(g) Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.

plot(cv_oj$size, cv_oj$dev, type = "b",
     xlab = "Tree Size", ylab = "CV Classification Error",
     main = "CV for OJ Tree")

(h) Which tree size corresponds to the lowest cross-validated classi- fication error rate?

optimal_size <- cv_oj$size[which.min(cv_oj$dev)]
optimal_size
[1] 9

🔴 Answer: Size of 9 has the lowest error rate.

(i) Produce a pruned tree corresponding to the optimal tree size obtained using cross-validation. If cross-validation does not lead to selection of a pruned tree, then create a pruned tree with five terminal nodes.

🔴 Answer: The cross-validation process suggests the best-performing tree is the full tree (=9) so pruning is needed.

prune_oj = prune.tree(tree_oj, best = 5)

(j) Compare the training error rates between the pruned and un- pruned trees. Which is higher?

pred_train_unpruned <- predict(tree_oj, newdata = train, type = "class")
error_unpruned <- mean(pred_train_unpruned != train$Purchase)

pred_train_pruned <- predict(prune_oj, newdata = train, type = "class")
error_pruned <- mean(pred_train_pruned != train$Purchase)

error_unpruned
[1] 0.15875
error_pruned
[1] 0.20375

🔴 Answer: Training error for the unpruned trees (0.1588) is lower than the pruned tree (0.205).

(k) Compare the test error rates between the pruned and unpruned trees. Which is higher?

pred_test_unpruned <- predict(tree_oj, newdata = test, type = "class")
test_error_unpruned <- mean(pred_test_unpruned != test$Purchase)

pred_test_pruned <- predict(prune_oj, newdata = test, type = "class")
test_error_pruned <- mean(pred_test_pruned != test$Purchase)

test_error_unpruned
[1] 0.1703704
test_error_pruned
[1] 0.2

🔴 Answer: Unpruned tree has a lower test error rate of ~17.0% compared to pruned tree (20%).