3. Consider the Gini index, classification error, and entropy in a simpleclassification 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.

gini=function(m1){
  return(2*(m1*(1-m1)))
}
ent=function(m1){
  m2=1-m1
  return(-((m1*log(m1))+(m2*log(m2))))
}
classerr=function(m1){
  m2=1-m1
  return(1-max(m1,m2))
  #return(min((1-m1),m1))
  #return(m1)
}
err=seq(0,1,by=0.01)
c.err=sapply(err,classerr)
g=sapply(err,gini)
e=sapply(err,ent)
d=data.frame(Gini.Index=g,Cross.Entropy=e)
plot(err,c.err,type='l',col="red",xlab="m1",ylim=c(0,0.8),ylab="value")
matlines(err,d,col=c("green","blue"))

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

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

train_idx <- sample(nrow(OJ), 800)
train <- OJ[train_idx,]
test <- OJ[-train_idx,]

## (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 ~ ., data = train)
summary(oj_tree)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "SalePriceMM"   "ListPriceDiff" "PriceDiff"    
## Number of terminal nodes:  7 
## Residual mean deviance:  0.7541 = 598 / 793 
## Misclassification error rate: 0.1525 = 122 / 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.

oj_tree
## node), split, n, deviance, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 800 1059.00 CH ( 0.62500 0.37500 )  
##    2) LoyalCH < 0.48285 294  327.30 MM ( 0.24490 0.75510 )  
##      4) LoyalCH < 0.276142 159  124.10 MM ( 0.13208 0.86792 ) *
##      5) LoyalCH > 0.276142 135  179.00 MM ( 0.37778 0.62222 )  
##       10) SalePriceMM < 2.04 71   75.77 MM ( 0.22535 0.77465 ) *
##       11) SalePriceMM > 2.04 64   88.16 CH ( 0.54688 0.45312 ) *
##    3) LoyalCH > 0.48285 506  435.00 CH ( 0.84585 0.15415 )  
##      6) LoyalCH < 0.764572 246  290.10 CH ( 0.72358 0.27642 )  
##       12) ListPriceDiff < 0.235 96  132.90 MM ( 0.47917 0.52083 )  
##         24) PriceDiff < 0.085 62   77.97 MM ( 0.32258 0.67742 ) *
##         25) PriceDiff > 0.085 34   37.10 CH ( 0.76471 0.23529 ) *
##       13) ListPriceDiff > 0.235 150  110.10 CH ( 0.88000 0.12000 ) *
##      7) LoyalCH > 0.764572 260   84.77 CH ( 0.96154 0.03846 ) *
## (d) Create a plot of the tree, and interpret the results.

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?

oj_pred <- predict(oj_tree, test, type = "class")
table(oj_pred, test$Purchase)
##        
## oj_pred  CH  MM
##      CH 134  29
##      MM  19  88
sprintf("Test error rate: %s", 1 - mean(oj_pred == test$Purchase))
## [1] "Test error rate: 0.177777777777778"
## (f) Apply the cv.tree() function to the training set in order to determine the optimal tree size.

oj_cv <- cv.tree(oj_tree, FUN = prune.misclass)
oj_cv
## $size
## [1] 7 5 2 1
## 
## $dev
## [1] 146 140 159 300
## 
## $k
## [1]       -Inf   3.000000   7.333333 150.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 error rate on the y-axis.

plot(oj_cv$size, oj_cv$dev, type="b")

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

## The optimal tree size is 7.

## (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.tree(oj_tree, best = 7)
summary(oj_prune)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "SalePriceMM"   "ListPriceDiff" "PriceDiff"    
## Number of terminal nodes:  7 
## Residual mean deviance:  0.7541 = 598 / 793 
## Misclassification error rate: 0.1525 = 122 / 800
## (j) Compare the training error rates between the pruned and unpruned trees. Which is higher?

## The training error rate for the pruned tree is higher, at 16.25% versus 15.88% for unpruned tree.

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

oj_prune_pred <- predict(oj_prune, test, type = "class")
table(oj_prune_pred, test$Purchase)
##              
## oj_prune_pred  CH  MM
##            CH 134  29
##            MM  19  88
sprintf("Test unpruned error rate: %s", 1 - mean(oj_pred == test$Purchase))
## [1] "Test unpruned error rate: 0.177777777777778"
sprintf("Test pruned error rate: %s", 1 - mean(oj_prune_pred == test$Purchase))
## [1] "Test pruned error rate: 0.177777777777778"
## The test error for the unpruned tree is higher, at 17.04% versus 16.30% for the pruned tree.