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. Thexaxis 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.index <- 2 * p * (1 - p)
class.error <- 1 - pmax(p, 1 - p)
cross.entropy <- - (p * log(p) + (1 - p) * log(1 - p))
par(bg = "papayawhip")
matplot(p, cbind(gini.index, class.error, cross.entropy), pch=c(15,17,19) ,ylab = "gini.index, class.error, cross.entropy",col = c("darkolivegreen4" , "wheat", "tomato2"), type = 'b')
legend('bottom', inset=.01, legend = c('gini.index', 'class.error', 'cross.entropy'), col = c("darkolivegreen4" , "wheat", "tomato2"), pch=c(15,17,19))

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.

set.seed(10)
library(ISLR)
library(tree)
samp<-sample(1:nrow(OJ), 800)

oj.tr<-OJ[samp,]
oj.te<-OJ[-samp,]

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 = oj.tr)
summary(tree.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.tr)
## Variables actually used in tree construction:
## [1] "LoyalCH"   "SpecialCH" "PriceDiff"
## Number of terminal nodes:  7 
## Residual mean deviance:  0.7936 = 629.3 / 793 
## Misclassification error rate: 0.1625 = 130 / 800

Misclassification error rate: 16.25%

Number of terminal nodes: 7

Uses only 3 of the 18 variables: “LoyalCH” “SpecialCH” “PriceDiff”

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 1080.000 CH ( 0.59500 0.40500 )  
##    2) LoyalCH < 0.450956 290  295.700 MM ( 0.20690 0.79310 )  
##      4) LoyalCH < 0.276142 172  119.500 MM ( 0.11047 0.88953 ) *
##      5) LoyalCH > 0.276142 118  152.400 MM ( 0.34746 0.65254 )  
##       10) SpecialCH < 0.5 104  125.000 MM ( 0.28846 0.71154 ) *
##       11) SpecialCH > 0.5 14   14.550 CH ( 0.78571 0.21429 ) *
##    3) LoyalCH > 0.450956 510  487.400 CH ( 0.81569 0.18431 )  
##      6) LoyalCH < 0.764572 258  321.100 CH ( 0.68605 0.31395 )  
##       12) PriceDiff < 0.05 87  119.200 MM ( 0.43678 0.56322 )  
##         24) PriceDiff < -0.34 18    7.724 MM ( 0.05556 0.94444 ) *
##         25) PriceDiff > -0.34 69   95.290 CH ( 0.53623 0.46377 ) *
##       13) PriceDiff > 0.05 171  164.900 CH ( 0.81287 0.18713 ) *
##      7) LoyalCH > 0.764572 252  102.400 CH ( 0.94841 0.05159 ) *

4) LoyalCH < 0.276142 172 119.500 MM ( 0.11047 0.88953 ) *

If LoyalCH is less than 0.450956 AND less than 0.276142, the Purchase is MM

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

par(bg = "darkorange")
plot(tree.oj)
text(tree.oj, 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?

tree.predz<-predict(tree.oj, oj.te, type = 'class')
obs.purch<-oj.te$Purchase
caret::confusionMatrix(tree.predz, obs.purch)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 155  27
##         MM  22  66
##                                           
##                Accuracy : 0.8185          
##                  95% CI : (0.7673, 0.8626)
##     No Information Rate : 0.6556          
##     P-Value [Acc > NIR] : 2.277e-09       
##                                           
##                   Kappa : 0.5929          
##  Mcnemar's Test P-Value : 0.5677          
##                                           
##             Sensitivity : 0.8757          
##             Specificity : 0.7097          
##          Pos Pred Value : 0.8516          
##          Neg Pred Value : 0.7500          
##              Prevalence : 0.6556          
##          Detection Rate : 0.5741          
##    Detection Prevalence : 0.6741          
##       Balanced Accuracy : 0.7927          
##                                           
##        'Positive' Class : CH              
## 

We get an error rate of 18.15%

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.misclass)

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/800, type ="b", xlab = "tree size", ylab = 'CV Error Rate', main = 'What size tree has\n the lowest CV Error Rate?')

H. Which tree size corresponds to the lowest cross-validated classification error rate?

best.trees<-data.frame(tree_size = cv.oj$size, CvErrors = cv.oj$dev, Rate = paste0(cv.oj$dev/8,"%"))
best.trees[order(best.trees$Rate),]
##   tree_size CvErrors    Rate
## 2         5      149 18.625%
## 1         7      151 18.875%
## 3         4      159 19.875%
## 4         2      159 19.875%
## 5         1      324   40.5%

It looks like a tree size of 5 gives us the lowest CV error rate of 18.625%

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.oj<-prune.misclass(tree.oj, best = 5)

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

prune.predz<-predict(prune.oj, oj.te, type = "class")
caret::confusionMatrix(prune.predz, obs.purch)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 151  25
##         MM  26  68
##                                          
##                Accuracy : 0.8111         
##                  95% CI : (0.7592, 0.856)
##     No Information Rate : 0.6556         
##     P-Value [Acc > NIR] : 1.242e-08      
##                                          
##                   Kappa : 0.5828         
##  Mcnemar's Test P-Value : 1              
##                                          
##             Sensitivity : 0.8531         
##             Specificity : 0.7312         
##          Pos Pred Value : 0.8580         
##          Neg Pred Value : 0.7234         
##              Prevalence : 0.6556         
##          Detection Rate : 0.5593         
##    Detection Prevalence : 0.6519         
##       Balanced Accuracy : 0.7921         
##                                          
##        'Positive' Class : CH             
## 

best = 5 18.89%

best = 7 18.15%

The tree with 7 terminal nodes has the lower error rate