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

p = seq(0, 1, 0.001)
gini.index = 2 * p * (1 - p)
class.error = 1 - pmax(p, 1 - p)
entropy = - (p * log(p) + (1 - p) * log(1 - p))
matplot(p, cbind(gini.index, class.error, entropy), ylab = "gini.index, class.error, entropy", col = c("green", "blue", "purple"))
legend('bottom', inset=.01, legend = c('gini.index', 'class.error', 'entropy'), col = c("green" , "blue", "purple"), pch=c(15,17,19))

Question 9. This problem involves the OJ data set with 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.

library(ISLR2)
attach(OJ)
set.seed(3)
train <- sample(1:nrow(OJ), 800)
OJtrain <- OJ[train,]
OJtest <- OJ[-train,]

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?

The training error rate is 18%. Four variables were used, and the tree has 9 terminal nodes.

OJ.tree <- tree(Purchase~., data = OJtrain)
summary(OJ.tree)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = OJtrain)
## Variables actually used in tree construction:
## [1] "LoyalCH"     "PriceDiff"   "PriceMM"     "SalePriceMM"
## Number of terminal nodes:  9 
## Residual mean deviance:  0.7247 = 573.2 / 791 
## Misclassification error rate: 0.1812 = 145 / 800

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.

Line 10 “PriceDiff” has a split criterion of <.05, 114 observations, and a deviance of 105.9.

OJ.tree
## node), split, n, deviance, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 800 1068.00 CH ( 0.61250 0.38750 )  
##    2) LoyalCH < 0.5036 346  414.30 MM ( 0.28613 0.71387 )  
##      4) LoyalCH < 0.0356415 57    0.00 MM ( 0.00000 1.00000 ) *
##      5) LoyalCH > 0.0356415 289  371.50 MM ( 0.34256 0.65744 )  
##       10) PriceDiff < 0.05 114  105.90 MM ( 0.17544 0.82456 )  
##         20) PriceMM < 2.11 89   94.84 MM ( 0.22472 0.77528 ) *
##         21) PriceMM > 2.11 25    0.00 MM ( 0.00000 1.00000 ) *
##       11) PriceDiff > 0.05 175  240.90 MM ( 0.45143 0.54857 )  
##         22) LoyalCH < 0.277221 62   66.24 MM ( 0.22581 0.77419 ) *
##         23) LoyalCH > 0.277221 113  154.10 CH ( 0.57522 0.42478 ) *
##    3) LoyalCH > 0.5036 454  365.70 CH ( 0.86123 0.13877 )  
##      6) LoyalCH < 0.764572 187  221.10 CH ( 0.72193 0.27807 )  
##       12) PriceDiff < 0.265 113  154.70 CH ( 0.56637 0.43363 )  
##         24) SalePriceMM < 2.155 102  141.20 CH ( 0.51961 0.48039 ) *
##         25) SalePriceMM > 2.155 11    0.00 CH ( 1.00000 0.00000 ) *
##       13) PriceDiff > 0.265 74   25.11 CH ( 0.95946 0.04054 ) *
##      7) LoyalCH > 0.764572 267   91.71 CH ( 0.95880 0.04120 ) *

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

The plot is showing the most important indicator of purchase is LoyalCH.

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?

Will have a test error rate of 0.8296

tree.pred <- predict(OJ.tree, OJtest, type = "class")
table(tree.pred, OJtest$Purchase)
##          
## tree.pred  CH  MM
##        CH 148  31
##        MM  15  76
(148+76)/270
## [1] 0.8296296

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

set.seed(3)
OJ.cv <- cv.tree(OJ.tree, FUN = prune.misclass)
OJ.cv
## $size
## [1] 9 5 2 1
## 
## $dev
## [1] 175 175 169 310
## 
## $k
## [1]       -Inf   0.000000   5.666667 148.000000
## 
## $method
## [1] "misclass"
## 
## attr(,"class")
## [1] "prune"         "tree.sequence"

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

plot(OJ.cv$size, OJ.cv$dev, type = "b", xlab = "Tree Size", ylab = "CV Classification Error Rate")

### h. Which tree size corresponds to the lowest cross-validated classification error rate? ### The tree size of 5 has the lowest cross-validation error rate.

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

OJprune <- prune.misclass(OJ.tree, best = 5)
plot(OJprune)
text(OJprune, pretty = 0)

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

The pruned tree has a training error of 18%. The unpruned tree also has a training error of 18%.

summary(OJprune)
## 
## Classification tree:
## snip.tree(tree = OJ.tree, nodes = c(3L, 10L))
## Variables actually used in tree construction:
## [1] "LoyalCH"   "PriceDiff"
## Number of terminal nodes:  5 
## Residual mean deviance:  0.8703 = 691.9 / 795 
## Misclassification error rate: 0.1812 = 145 / 800
summary(OJ.tree)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = OJtrain)
## Variables actually used in tree construction:
## [1] "LoyalCH"     "PriceDiff"   "PriceMM"     "SalePriceMM"
## Number of terminal nodes:  9 
## Residual mean deviance:  0.7247 = 573.2 / 791 
## Misclassification error rate: 0.1812 = 145 / 800

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

The test error rates are also the same at 0.8296.

OJtree.pred = predict(OJprune, newdata = OJtest, type = "class")
table(OJtree.pred, OJtest$Purchase)
##            
## OJtree.pred  CH  MM
##          CH 148  31
##          MM  15  76
(148+76)/270
## [1] 0.8296296
OJtree.pred2 <- predict(OJ.tree, newdata = OJtest, type = "class")
table(OJtree.pred2, OJtest$Purchase)
##             
## OJtree.pred2  CH  MM
##           CH 148  31
##           MM  15  76
(148+76)/270
## [1] 0.8296296