library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.4.2
library(caret)
## Warning: package 'caret' was built under R version 4.4.2
## Loading required package: ggplot2
## Loading required package: lattice
library(rattle)
## Warning: package 'rattle' was built under R version 4.4.3
## Loading required package: tibble
## Loading required package: bitops
## Rattle: A free graphical interface for data science with R.
## Version 5.5.1 Copyright (c) 2006-2021 Togaware Pty Ltd.
## Type 'rattle()' to shake, rattle, and roll your data.
library(rpart)
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.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:rattle':
## 
##     importance
## The following object is masked from 'package:ggplot2':
## 
##     margin
library(BART)
## Warning: package 'BART' was built under R version 4.4.3
## Loading required package: nlme
## Loading required package: survival
## 
## Attaching package: 'survival'
## The following object is masked from 'package:caret':
## 
##     cluster
attach(Carseats)
attach(OJ)

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. The x-axis should display ˆ pm1, 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, ˆ pm1 =1− ˆ pm2. You could make this plot by hand, but it will be much easier to make in R.

p <- seq(0, 1, 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.na(entropy)] <- 0  

plot(p, gini, type = "l", col = "blue", ylim = c(0,1),
     ylab = "Value", xlab = "pm1")
lines(p, entropy, col = "red")
lines(p, classification_error, col = "green")
legend("top", legend = c("Gini", "Entropy", "Classification Error"),
       col = c("blue", "red", "green"), lty = 1)

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(62)

n <- nrow(OJ)
oj_train_index <- sample(1:n, 800)
oj_train <- OJ[oj_train_index, ]
oj_test <- OJ[-oj_train_index, ]

(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?

oj_tree <- tree(Purchase ~ ., data = oj_train)
summary(oj_tree)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = oj_train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "ListPriceDiff" "PctDiscCH"    
## Number of terminal nodes:  9 
## Residual mean deviance:  0.7594 = 600.6 / 791 
## Misclassification error rate: 0.1612 = 129 / 800

Training error rate is 0.1612 and the Terminal nodes is 9

(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 1070.00 CH ( 0.61000 0.39000 )  
##    2) LoyalCH < 0.48285 297  326.70 MM ( 0.23906 0.76094 )  
##      4) LoyalCH < 0.0616725 66   17.92 MM ( 0.03030 0.96970 ) *
##      5) LoyalCH > 0.0616725 231  281.70 MM ( 0.29870 0.70130 )  
##       10) PriceDiff < 0.31 179  195.00 MM ( 0.23464 0.76536 )  
##         20) PriceDiff < -0.34 19    0.00 MM ( 0.00000 1.00000 ) *
##         21) PriceDiff > -0.34 160  184.20 MM ( 0.26250 0.73750 ) *
##       11) PriceDiff > 0.31 52   72.01 CH ( 0.51923 0.48077 ) *
##    3) LoyalCH > 0.48285 503  460.20 CH ( 0.82903 0.17097 )  
##      6) LoyalCH < 0.705699 204  258.30 CH ( 0.67157 0.32843 )  
##       12) ListPriceDiff < 0.235 79  106.70 MM ( 0.40506 0.59494 )  
##         24) PctDiscCH < 0.052007 66   82.56 MM ( 0.31818 0.68182 ) *
##         25) PctDiscCH > 0.052007 13   11.16 CH ( 0.84615 0.15385 ) *
##       13) ListPriceDiff > 0.235 125  109.90 CH ( 0.84000 0.16000 ) *
##      7) LoyalCH > 0.705699 299  141.50 CH ( 0.93645 0.06355 )  
##       14) PriceDiff < -0.39 8   10.59 MM ( 0.37500 0.62500 ) *
##       15) PriceDiff > -0.39 291  112.30 CH ( 0.95189 0.04811 ) *

In Node 15, there are 291 observations where PriceDiff > -0.39. The predicted class is CH, with 95% of customers choosing CH, so the model is confident in this prediction.

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

plot(oj_tree)
text(oj_tree)

It look like most of the data is split on the LoyalCH variable.

(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, newdata = oj_test, type = "class")
confusionMatrix(data = oj_pred, reference = oj_test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 130  19
##         MM  35  86
##                                          
##                Accuracy : 0.8            
##                  95% CI : (0.7472, 0.846)
##     No Information Rate : 0.6111         
##     P-Value [Acc > NIR] : 2.106e-11      
##                                          
##                   Kappa : 0.5906         
##                                          
##  Mcnemar's Test P-Value : 0.04123        
##                                          
##             Sensitivity : 0.7879         
##             Specificity : 0.8190         
##          Pos Pred Value : 0.8725         
##          Neg Pred Value : 0.7107         
##              Prevalence : 0.6111         
##          Detection Rate : 0.4815         
##    Detection Prevalence : 0.5519         
##       Balanced Accuracy : 0.8035         
##                                          
##        'Positive' Class : CH             
## 
oj_error <- mean(oj_pred != oj_test$Purchase)
oj_error
## [1] 0.2

The Test result error rate is 0.2

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

set.seed(62)
oj_cv <- cv.tree(oj_tree, FUN = prune.misclass)
oj_cv
## $size
## [1] 9 8 6 5 2 1
## 
## $dev
## [1] 152 151 150 149 160 312
## 
## $k
## [1] -Inf    0    1    2    8  155
## 
## $method
## [1] "misclass"
## 
## attr(,"class")
## [1] "prune"         "tree.sequence"

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

plot(oj_cv$size, oj_cv$dev, type = "b")

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

oj_cv$size[which.min(oj_cv$dev)]
## [1] 5

The optimal tree size is 5, as it gives the lowest cross-validated classification error.

(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.

oj_pruned <- prune.misclass(oj_tree, best = 5)
plot(oj_pruned)
text(oj_pruned, pretty = 0)

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

pred_unpruned <- predict(oj_tree, newdata = oj_train, type = "class")
pred_pruned <- predict(oj_pruned, newdata = oj_train, type = "class")
error_unpruned <- mean(pred_unpruned != oj_train$Purchase)
error_unpruned
## [1] 0.16125

Unpruned is 0.16125

error_pruned <- mean(pred_pruned != oj_train$Purchase)
error_pruned
## [1] 0.16625

Pruned is 0.16625

The training error rate for the unpruned tree was 0.16125, while the pruned tree had a slightly higher error rate of 0.16625.

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

test_unpruned <- predict(oj_tree, newdata = oj_test, type = "class")
test_pruned <- predict(oj_pruned, newdata = oj_test, type = "class")
error_unpruned2 <- mean(test_unpruned != oj_test$Purchase)
error_unpruned2
## [1] 0.2

Test error rate for unpruned is 0.2

error_pruned <- mean(test_pruned != oj_test$Purchase)
error_pruned
## [1] 0.1851852

Test error rate for unpruned is 0.1851852

The test error rate for the unpruned tree was 0.2, while the pruned tree had a slightly lower error rate of 0.1852.