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)
classerror = 1 - pmax(p,1-p)
crossentropy = -(p*log(p)+(1-p)*log(1-p))
plot(NA,NA,xlim = c(0,1),ylim = c(0,1), xlab = 'p', ylab ='error')
lines(p,gini,type = 'l')
lines(p,classerror,col = 'blue')
lines(p,crossentropy,col = 'red')
legend(x ='top',legend = c('gini','class error','cross entropy'),
       col = c('black','blue','red'),lty = 1,text.width = 0.22)

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.

attach(OJ)
set.seed(111)
library(ISLR)

train = sample(1:nrow(OJ),800)
oj.train = OJ[train,]
oj.test = 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?

oj.tree = tree(Purchase~.,oj.train)
fulltree.summary = summary(oj.tree)
fulltree.summary
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "ListPriceDiff"
## Number of terminal nodes:  8 
## Residual mean deviance:  0.7598 = 601.7 / 792 
## Misclassification error rate: 0.1675 = 134 / 800

The summary results show that The fitted tree has 8 terminal nodes and a training error rate of 0.1675.

(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 1069.00 CH ( 0.61125 0.38875 )  
##    2) LoyalCH < 0.48285 304  335.10 MM ( 0.24013 0.75987 )  
##      4) LoyalCH < 0.0356415 53    0.00 MM ( 0.00000 1.00000 ) *
##      5) LoyalCH > 0.0356415 251  302.70 MM ( 0.29084 0.70916 )  
##       10) LoyalCH < 0.276142 108  100.50 MM ( 0.17593 0.82407 ) *
##       11) LoyalCH > 0.276142 143  189.60 MM ( 0.37762 0.62238 )  
##         22) PriceDiff < 0.05 62   63.68 MM ( 0.20968 0.79032 ) *
##         23) PriceDiff > 0.05 81  112.30 CH ( 0.50617 0.49383 ) *
##    3) LoyalCH > 0.48285 496  438.30 CH ( 0.83871 0.16129 )  
##      6) LoyalCH < 0.764572 233  284.80 CH ( 0.69957 0.30043 )  
##       12) ListPriceDiff < 0.235 91  126.10 MM ( 0.49451 0.50549 )  
##         24) PriceDiff < 0.085 58   74.73 MM ( 0.34483 0.65517 ) *
##         25) PriceDiff > 0.085 33   36.55 CH ( 0.75758 0.24242 ) *
##       13) ListPriceDiff > 0.235 142  129.00 CH ( 0.83099 0.16901 ) *
##      7) LoyalCH > 0.764572 263   85.01 CH ( 0.96198 0.03802 ) *

Looking at terminal node #4, LoyalCH < 0.0356415 (which classifies as MM), I’ve interpreted the following information. In node #4 the data suggests 0% of the observations in that branch take the value of CH, while 100% take the value of MM. There were a total of 53 observations classified in this node, with a residual deviance of 0.00. This termnal node #4, with it’s relatively low LoyalCh, is established without the need for further consideration of PriceDiff or ListPriceDiff values, and thus classifies solely based on falling within this low LoyalCh threshold.

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

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

When looking at the predictors of “Purchase” that are shown in this tree, which are LoyalCH, ListPriceDiff, and PriceDiff, the plot suggest a strong influence from LoyalCH that effects how the rest of the tree splits. Furthermore, if LoyalCh isn’t enough to predict Purchase (as in observations with LoyalCH value above 0.276142 and below 0.764572), then we may observe how varying levels of PriceDif and ListPriceDiff help classify purchases for those Loyal CH values in between.

(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.predict.test = predict(oj.tree,newdata = oj.test,type = "class")
table(oj.test$Purchase,oj.predict.test,dnn = c("Actual","Predicted"))
##       Predicted
## Actual  CH  MM
##     CH 147  17
##     MM  25  81
ojTE = 1 - (147 + 81)/270
ojTE
## [1] 0.1555556

The test error rate appears to be 0.1555556

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

oj.cv.train = cv.tree(oj.tree, FUN = prune.misclass)
oj.cv.train
## $size
## [1] 8 5 2 1
## 
## $dev
## [1] 165 168 160 311
## 
## $k
## [1]        -Inf   0.3333333   6.0000000 158.0000000
## 
## $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(oj.cv.train$size, oj.cv.train$dev, type = "b", xlab = "Tree size", ylab = "CV error rate")

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

According to the above plot, we can see a tree size of 2 corresponds to the lowest cross-walidated classification 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.

oj.prune = prune.misclass(oj.tree,best=2)
plot(oj.prune)
text(oj.prune,pretty=0)

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

summary(oj.tree)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "ListPriceDiff"
## Number of terminal nodes:  8 
## Residual mean deviance:  0.7598 = 601.7 / 792 
## Misclassification error rate: 0.1675 = 134 / 800
summary(oj.prune)
## 
## Classification tree:
## snip.tree(tree = oj.tree, nodes = 2:3)
## Variables actually used in tree construction:
## [1] "LoyalCH"
## Number of terminal nodes:  2 
## Residual mean deviance:  0.9692 = 773.4 / 798 
## Misclassification error rate: 0.1912 = 153 / 800

The unpruned tree produced a trainning error of 0.1675, while the prune tree did slightly worse with a training error of 0.1912.

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

prune.predict.test = predict(oj.prune,newdata = oj.test,type="class")
table(oj.test$Purchase,prune.predict.test,dnn = c("Actual","Predicted"))
##       Predicted
## Actual  CH  MM
##     CH 143  21
##     MM  30  76
unprunedTE = 1 - (143 + 76)/270
unprunedTE
## [1] 0.1888889

The test error rate appears to be 0.1555556 for the unpruned tree and the test error rate appears to be 0.1888889 for the pruned tree, which is slightly higher than the unpruned tree.