library(ISLR)
library(tree)
library(randomForest)
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
library(rattle)
## Loading required package: tibble
## Loading required package: bitops
## Rattle: A free graphical interface for data science with R.
## Version 5.4.0 Copyright (c) 2006-2020 Togaware Pty Ltd.
## Type 'rattle()' to shake, rattle, and roll your data.
## 
## Attaching package: 'rattle'
## The following object is masked from 'package:randomForest':
## 
##     importance
library(rpart)

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

  1. Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(2)
train=sample(1:nrow(OJ),800)

OJ.train=OJ[train,]
OJ.test=OJ[-train,]
  1. 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"
## Number of terminal nodes:  9 
## Residual mean deviance:  0.7009 = 554.4 / 791 
## Misclassification error rate: 0.1588 = 127 / 800

The tree has 9 nodes. The misclassification error rate is 0.1588 = 127 / 800.

  1. 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 1068.00 CH ( 0.61250 0.38750 )  
##    2) LoyalCH < 0.5036 359  422.80 MM ( 0.27577 0.72423 )  
##      4) LoyalCH < 0.280875 172  127.60 MM ( 0.12209 0.87791 )  
##        8) LoyalCH < 0.035047 56   10.03 MM ( 0.01786 0.98214 ) *
##        9) LoyalCH > 0.035047 116  106.60 MM ( 0.17241 0.82759 ) *
##      5) LoyalCH > 0.280875 187  254.10 MM ( 0.41711 0.58289 )  
##       10) PriceDiff < 0.05 73   71.36 MM ( 0.19178 0.80822 ) *
##       11) PriceDiff > 0.05 114  156.30 CH ( 0.56140 0.43860 ) *
##    3) LoyalCH > 0.5036 441  311.80 CH ( 0.88662 0.11338 )  
##      6) LoyalCH < 0.737888 168  191.10 CH ( 0.74405 0.25595 )  
##       12) PriceDiff < 0.265 93  125.00 CH ( 0.60215 0.39785 )  
##         24) PriceDiff < -0.35 12   10.81 MM ( 0.16667 0.83333 ) *
##         25) PriceDiff > -0.35 81  103.10 CH ( 0.66667 0.33333 ) *
##       13) PriceDiff > 0.265 75   41.82 CH ( 0.92000 0.08000 ) *
##      7) LoyalCH > 0.737888 273   65.11 CH ( 0.97436 0.02564 )  
##       14) PriceDiff < -0.39 11   12.89 CH ( 0.72727 0.27273 ) *
##       15) PriceDiff > -0.39 262   41.40 CH ( 0.98473 0.01527 ) *

Each node of the tree is a region in which most of observartions is loayal to Citrus Hill or Minute Maid. The very first split is the obius loyast to Citrus Hill: above 0.5036 they will be indeed loyal to CH, below they will be loyal to MinuteMaid.

  1. Create a plot of the tree, and interpret the results.
plot(OJ.tree)
text(OJ.tree)

The plot show the same splits of above, just in a visual fashion.

  1. 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.test=predict(OJ.tree,OJ.test,type = 'class')
table(OJ.test[,'Purchase'],OJ.pred.test)
##     OJ.pred.test
##       CH  MM
##   CH 148  15
##   MM  37  70
test.error=(37+15)/(37+148+15+70)
test.error
## [1] 0.1925926
  1. Apply the cv.tree() function to the training set in order to determine the optimal tree size.
set.seed(2)
OJ.tree.cv=cv.tree(OJ.tree,K = 10,FUN = prune.misclass)
  1. Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.
plot(OJ.tree.cv)

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

4

  1. 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.tree=prune.misclass(OJ.tree,best = 4)
plot(OJ.prune.tree)
text(OJ.prune.tree)

  1. Compare the training error rates between the pruned and unpruned trees. Which is higher?
OJ.pred.train=predict(OJ.tree,OJ.train,type = 'class')
table(OJ.train[,'Purchase'],OJ.pred.train)
##     OJ.pred.train
##       CH  MM
##   CH 453  37
##   MM  90 220
OJ.prune.pred.train=predict(OJ.prune.tree,OJ.train,type = 'class')
table(OJ.train[,'Purchase'],OJ.prune.pred.train)
##     OJ.prune.pred.train
##       CH  MM
##   CH 455  35
##   MM 100 210

The pruned model has a slightly higher train error rate.

  1. Compare the test error rates between the pruned and unpruned trees. Which is higher?
OJ.pred.test=predict(OJ.tree,OJ.test,type = 'class')
table(OJ.test[,'Purchase'],OJ.pred.test)
##     OJ.pred.test
##       CH  MM
##   CH 148  15
##   MM  37  70
OJ.prune.pred.test=predict(OJ.prune.tree,OJ.test,type = 'class')
table(OJ.test[,'Purchase'],OJ.prune.pred.test)
##     OJ.prune.pred.test
##       CH  MM
##   CH 149  14
##   MM  42  65

The pruned model has a slightly higher test error rate.