9. This problem involves the OJ data set which is part of the ISLR package.

(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.

train_index <- sample(1:nrow(OJ), 800)
train_set <- OJ[train_index, ]
test_set <- 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?

tree.oj <- tree(Purchase ~ ., train_set)
summary(tree.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = train_set)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "ListPriceDiff" "SalePriceMM"  
## Number of terminal nodes:  9 
## Residual mean deviance:  0.7425 = 587.3 / 791 
## Misclassification error rate: 0.1588 = 127 / 800

This model has 9 nodes and about at 16% error rate.
(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.48285 317  358.20 MM ( 0.25237 0.74763 )  
##      4) LoyalCH < 0.280875 173  127.90 MM ( 0.12139 0.87861 )  
##        8) LoyalCH < 0.0356415 56   10.03 MM ( 0.01786 0.98214 ) *
##        9) LoyalCH > 0.0356415 117  107.00 MM ( 0.17094 0.82906 ) *
##      5) LoyalCH > 0.280875 144  194.90 MM ( 0.40972 0.59028 )  
##       10) PriceDiff < 0.05 62   66.24 MM ( 0.22581 0.77419 ) *
##       11) PriceDiff > 0.05 82  112.90 CH ( 0.54878 0.45122 ) *
##    3) LoyalCH > 0.48285 483  427.10 CH ( 0.83851 0.16149 )  
##      6) LoyalCH < 0.753545 228  276.10 CH ( 0.70614 0.29386 )  
##       12) PriceDiff < -0.165 32   30.88 MM ( 0.18750 0.81250 ) *
##       13) PriceDiff > -0.165 196  201.00 CH ( 0.79082 0.20918 )  
##         26) ListPriceDiff < 0.16 29   39.89 MM ( 0.44828 0.55172 ) *
##         27) ListPriceDiff > 0.16 167  141.00 CH ( 0.85030 0.14970 )  
##           54) SalePriceMM < 2.125 91   98.32 CH ( 0.76923 0.23077 ) *
##           55) SalePriceMM > 2.125 76   31.34 CH ( 0.94737 0.05263 ) *
##      7) LoyalCH > 0.753545 255   90.67 CH ( 0.95686 0.04314 ) *

I’ll choose terminal node 10. From the root node, the first split is based on Loyalty > 0.48, followed by a split for Loyalty >0.28. The last one is based on PriceDiff < 0.05. 64 observations fell into this node.
(d) Create a plot of the tree, and interpret the results

plot(tree.oj)
text(tree.oj, pretty = 0)

The most important variable is LoyaltyCH because most of the splits are based on that variable. After that, PriceDiff has the most impact in the tree.
(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, test_set, type = "class")
table(pred.oj, test_set$Purchase)
##        
## pred.oj  CH  MM
##      CH 145  29
##      MM  23  73
(145+73)/270
## [1] 0.8074074

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

cv.oj <- cv.tree(tree.oj, K = 10, FUN = prune.misclass)
cv.oj
## $size
## [1] 9 7 6 4 2 1
## 
## $dev
## [1] 155 155 161 161 158 315
## 
## $k
## [1] -Inf    0    3    4   10  157
## 
## $method
## [1] "misclass"
## 
## attr(,"class")
## [1] "prune"         "tree.sequence"

(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/nrow(train_set),type="b")

(h) Which tree size corresponds to the lowest cross-validated classification error rate?
9 and 7 have 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.

pruned.oj <- prune.tree(tree.oj, best = 5)

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

table(predict(pruned.oj, train_set, type = "class"), train_set$Purchase)
##     
##       CH  MM
##   CH 399  52
##   MM  86 263
(399+263)/270
## [1] 2.451852

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

table(predict(pruned.oj, test_set, type = "class"), test_set$Purchase)
##     
##       CH  MM
##   CH 148  24
##   MM  20  78
(148+78)/270
## [1] 0.837037

The pruned is higher buy a bit.