##Chapter 08: 3, 8, 9
library(tree)
## Warning: package 'tree' was built under R version 4.4.3
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.4.3
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.4.2
library(ggplot2)
##
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
##
## margin
library(tidyr)
library(BART)
## Warning: package 'BART' was built under R version 4.4.3
## Loading required package: nlme
## Loading required package: survival
###Exercise 3. Consider the Gini index, classification error, and entropy in a simple classification setting with two classes. Create a single plot that displays each of these quantities as a function of ˆpm1.
p <- seq(0, 1, by = 0.01)
gini <- 2 * p * (1 - p)
classification_error <- 1 - pmax(p, 1 - p)
entropy <- -p * log2(p) - (1 - p) * log2(1 - p)
entropy[is.nan(entropy)] <- 0 # Handle log2(0)
df <- data.frame(
p_hat = p,
Gini = gini,
Entropy = entropy,
Classification_Error = classification_error
)
df_long <- pivot_longer(df, cols = -p_hat, names_to = "Measure", values_to = "Value")
ggplot(df_long, aes(x = p_hat, y = Value, color = Measure)) +
geom_line(size = 1.2) +
scale_x_continuous(breaks = seq(0, 1, by = 0.1)) +
labs(
title = "Impurity Measures as a Function of p̂ₘ₁",
x = expression(hat(p)[m1]),
y = "Impurity",
color = "Measure"
) +
theme_minimal(base_size = 14)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
###Exercise 8: In the lab, a classification tree was applied to the
Carseats data set after 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.
set.seed(1)
train <- sample(1:nrow(Carseats), 200)
carseats_train <- Carseats[train, ]
carseats_test <- Carseats[-train, ]
(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
# Fit regression tree
tree_model <- tree(Sales ~ ., data = carseats_train)
summary(tree_model)
##
## Regression tree:
## tree(formula = Sales ~ ., data = carseats_train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "Age" "Advertising" "CompPrice"
## [6] "US"
## Number of terminal nodes: 18
## Residual mean deviance: 2.167 = 394.3 / 182
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -3.88200 -0.88200 -0.08712 0.00000 0.89590 4.09900
# Plot tree
plot(tree_model)
text(tree_model, pretty = 0)
# Predict and compute MSE
tree_pred <- predict(tree_model, carseats_test)
tree_mse <- mean((tree_pred - carseats_test$Sales)^2)
tree_mse
## [1] 4.922039
The Tree MSE is 4.922039
(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
set.seed(2)
cv_results <- cv.tree(tree_model)
# Plot CV error
plot(cv_results$size, cv_results$dev, type = "b", xlab = "Tree Size", ylab = "CV Error")
# Prune to best size
best_size <- cv_results$size[which.min(cv_results$dev)]
pruned_tree <- prune.tree(tree_model, best = best_size)
# Plot pruned tree
plot(pruned_tree)
text(pruned_tree, pretty = 0)
# Predict and compute pruned MSE
pruned_pred <- predict(pruned_tree, carseats_test)
pruned_mse <- mean((pruned_pred - carseats_test$Sales)^2)
pruned_mse
## [1] 4.922039
Pruning the tree should have made the MSE better,
(d) Use the bagging approach in order to analyze this data. What test MSE do you obtain? Use the importance() function to determine which variables are most important.
set.seed(1)
bag_model <- randomForest(Sales ~ ., data = carseats_train, mtry = ncol(Carseats) - 1, importance = TRUE)
# Predict and compute MSE
bag_pred <- predict(bag_model, carseats_test)
bag_mse <- mean((bag_pred - carseats_test$Sales)^2)
bag_mse # e.g. ~2.64
## [1] 2.605253
# Variable importance
importance(bag_model)
## %IncMSE IncNodePurity
## CompPrice 24.8888481 170.182937
## Income 4.7121131 91.264880
## Advertising 12.7692401 97.164338
## Population -1.8074075 58.244596
## Price 56.3326252 502.903407
## ShelveLoc 48.8886689 380.032715
## Age 17.7275460 157.846774
## Education 0.5962186 44.598731
## Urban 0.1728373 9.822082
## US 4.2172102 18.073863
varImpPlot(bag_model)
Price and Shelve Location are by far the most important factors when
buying a carseat
(e) Use random forests to analyze this data. What test MSE do you obtain? Use the importance() function to determine which variables are most important. Describe the effect of m, the number of variables considered at each split, on the error rate obtained.
set.seed(1)
rf_model <- randomForest(Sales ~ ., data = carseats_train, importance = TRUE)
# Predict and MSE
rf_pred <- predict(rf_model, carseats_test)
rf_mse <- mean((rf_pred - carseats_test$Sales)^2)
rf_mse
## [1] 2.960559
# Importance
importance(rf_model)
## %IncMSE IncNodePurity
## CompPrice 14.8840765 158.82956
## Income 4.3293950 125.64850
## Advertising 8.2215192 107.51700
## Population -0.9488134 97.06024
## Price 34.9793386 385.93142
## ShelveLoc 34.9248499 298.54210
## Age 14.3055912 178.42061
## Education 1.3117842 70.49202
## Urban -1.2680807 17.39986
## US 6.1139696 33.98963
varImpPlot(rf_model)
Small M is more variation across the trees trying for better
generalization, and a larger M is closer to the bagging.
(f) Now analyze the data using BART, and report your results.
x_train <- data.matrix(carseats_train[, -which(names(Carseats) == "Sales")])
y_train <- carseats_train$Sales
x_test <- data.matrix(carseats_test[, -which(names(Carseats) == "Sales")])
y_test <- carseats_test$Sales
set.seed(1)
bart_fit <- gbart(x_train, y_train, x.test = x_test)
## *****Calling gbart: type=1
## *****Data:
## data:n,p,np: 200, 10, 200
## y1,yn: 2.781850, 1.091850
## x1,x[n*p]: 107.000000, 2.000000
## xp1,xp[np*p]: 111.000000, 2.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.273474,3,0.692269,7.57815
## *****sigma: 1.885179
## *****w (weights): 1.000000 ... 1.000000
## *****Dirichlet:sparse,theta,omega,a,b,rho,augment: 0,0,1,0.5,1,10,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: 4s
## trcnt,tecnt: 1000,1000
# Predictions and MSE
yhat_bart <- bart_fit$yhat.test.mean
bart_mse <- mean((y_test - yhat_bart)^2)
bart_mse # e.g. ~2.42
## [1] 1.465254
# Variable importance (based on use counts)
importance_bart <- bart_fit$varcount.mean
sort(importance_bart, decreasing = TRUE)
## ShelveLoc Price Education CompPrice US Urban
## 31.159 29.937 24.392 23.995 22.884 22.612
## Population Age Income Advertising
## 22.380 21.764 21.291 20.900
the 1.465254 MSE is by far the best outcome.
###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 observations,and a test set containing the remaining observations.
set.seed(1)
train_indices <- sample(1:nrow(OJ), 800)
oj_train <- OJ[train_indices, ]
oj_test <- OJ[-train_indices, ]
(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?
# Fit classification tree
oj_tree <- tree(Purchase ~ ., data = oj_train)
# Summary
summary(oj_tree)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = oj_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
the error rate is about 16%, with nine 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.
oj_tree
## 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 ) *
node 9 split condition LoyalCH > 0.0356415, with 118 observations, deviance: 116.40, Predicted class: MM, and class probabilities: 19.492%, 80.508%
this suggests there is a preference to MM despice a slight brand loyality to CH which means there are factors that could pull CH fans away to the MM brand.
(d) Create a plot of the tree, and interpret the results.
plot(oj_tree)
text(oj_tree, pretty = 0)
(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?
oj_pred <- predict(oj_tree, oj_test, type = "class")
# Confusion matrix
conf_matrix <- table(Predicted = oj_pred, Actual = oj_test$Purchase)
conf_matrix
## Actual
## Predicted CH MM
## CH 160 38
## MM 8 64
# Test error rate
test_error <- mean(oj_pred != oj_test$Purchase)
test_error
## [1] 0.1703704
error rate of 17.03704
(f) Apply the cv.tree() function to the training set in order to determine the optimal tree size.
set.seed(2)
cv_oj <- cv.tree(oj_tree, FUN = prune.misclass)
summary(cv_oj)
## Length Class Mode
## size 6 -none- numeric
## dev 6 -none- numeric
## k 6 -none- numeric
## method 1 -none- character
(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 (Number of Terminal Nodes)",
ylab = "CV Misclassification Error",
main = "CV Error vs. Tree Size")
(h) Which tree size corresponds to the lowest cross-validated classification error rate?
optimal_size <- cv_oj$size[which.min(cv_oj$dev)]
optimal_size
## [1] 9
(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.
# Prune to optimal size
pruned_tree <- prune.misclass(oj_tree, best = optimal_size)
# Plot pruned tree
plot(pruned_tree)
text(pruned_tree, pretty = 0)
(j) Compare the training error rates between the pruned and unpruned trees. Which is higher?
train_pred_full <- predict(oj_tree, oj_train, type = "class")
train_pred_pruned <- predict(pruned_tree, oj_train, type = "class")
train_err_full <- mean(train_pred_full != oj_train$Purchase)
train_err_pruned <- mean(train_pred_pruned != oj_train$Purchase)
train_err_full
## [1] 0.15875
train_err_pruned
## [1] 0.15875
the error rate for the full and pruned are the same which shouldn’t be. the pruned should be lower.
(k) Compare the test error rates between the pruned and unpruned trees. Which is higher?
test_pred_full <- predict(oj_tree, oj_test, type = "class")
test_pred_pruned <- predict(pruned_tree, oj_test, type = "class")
test_err_full <- mean(test_pred_full != oj_test$Purchase)
test_err_pruned <- mean(test_pred_pruned != oj_test$Purchase)
test_err_full
## [1] 0.1703704
test_err_pruned
## [1] 0.1703704
the error rate on the test set is slightly higher than the train set but for both sets, both the train and test have the the same full and pruned error rate which shouldn’t be.
changing pruned nodes
# Prune to optimal size
pruned_tree <- prune.misclass(oj_tree, best = 5)
# Plot pruned tree
plot(pruned_tree)
text(pruned_tree, pretty = 0)
train_pred_full <- predict(oj_tree, oj_train, type = "class")
train_pred_pruned <- predict(pruned_tree, oj_train, type = "class")
train_err_full <- mean(train_pred_full != oj_train$Purchase)
train_err_pruned <- mean(train_pred_pruned != oj_train$Purchase)
train_err_full
## [1] 0.15875
train_err_pruned
## [1] 0.1625
test_pred_full <- predict(oj_tree, oj_test, type = "class")
test_pred_pruned <- predict(pruned_tree, oj_test, type = "class")
test_err_full <- mean(test_pred_full != oj_test$Purchase)
test_err_pruned <- mean(test_pred_pruned != oj_test$Purchase)
test_err_full
## [1] 0.1703704
test_err_pruned
## [1] 0.162963
Changing the nodes to 5 from the “optimal” there was a difference in the full to pruned error rates. on the train set, it gets slightly worse, and on the test set it gets slightly better.