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.0001)
#Gini
G=2*p*(1-p)
#Classification Error
E=1-pmax(p,1-p)
#Entropy
D=-(p*log(p) + (1-p)*log(1-p))

plot(p,D, col="red",ylab="")
lines(p,E,col='green')
lines(p,G,col='blue')
legend(0.3,0.15,c("Entropy", "Missclassification","Gini"),lty=c(1,1,1),
       lwd=c(2.5,2.5,2.5),col=c('red','green','blue'))

#install.packages("tree")
#install.packages("BART")

library("ISLR2")
## Warning: package 'ISLR2' was built under R version 4.5.3
library("tree")
## Warning: package 'tree' was built under R version 4.5.3
library("rpart.plot")
## Warning: package 'rpart.plot' was built under R version 4.5.3
## Loading required package: rpart
library("rattle")
## Warning: package 'rattle' was built under R version 4.5.3
## Loading required package: tibble
## Warning: package 'tibble' was built under R version 4.5.3
## Loading required package: bitops
## Warning: package 'bitops' was built under R version 4.5.2
## Rattle: A free graphical interface for data science with R.
## Version 5.6.2 Copyright (c) 2006-2023 Togaware Pty Ltd.
## Type 'rattle()' to shake, rattle, and roll your data.
library("randomForest")
## Warning: package 'randomForest' was built under R version 4.5.3
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:rattle':
## 
##     importance
library("BART")
## Warning: package 'BART' was built under R version 4.5.3
## Loading required package: nlme
## Loading required package: survival
library("caret")
## Warning: package 'caret' was built under R version 4.5.3
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 4.5.3
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
## 
##     margin
## Loading required package: lattice
## 
## Attaching package: 'caret'
## The following object is masked from 'package:survival':
## 
##     cluster
data("Carseats")

8. In the lab, a classification tree was applied to the Carseats data set after converting Sales into a qualitative response variable. Now we will seek to predict Sales using regression trees and related approaches,treating the response as a quantitative variable.

(a) Split the data set into a training set and a test set.

set.seed(70)

trainCars=sample(1:nrow(Carseats), nrow(Carseats)/2)

TrCars = Carseats[trainCars,]
TstCars = Carseats[-trainCars,]

(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?

tree.carseatsR=rpart(Sales~., data = TrCars, method="anova", 
                    control=rpart.control(minsplit=15, cp=0.1)) 

fancyRpartPlot(tree.carseatsR)

If the ShelveLoc value is good, the sales value is high.

If the ShelveLoc value is bad/medium and the price is above 106 (in thousands), then the value of “Sales” is low.

pred.treeR = predict(tree.carseatsR, newdata = TstCars)

mean((TstCars$Sales - pred.treeR)^2)
## [1] 5.387279

The Test MSE is 5.387 .

(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?

set.seed(70)

tree.carseatsR$cptable[which.min(tree.carseatsR$cptable[, "xerror"]), "CP"]
## [1] 0.1
# Taking the cptable and asking which value has lowest cv error
# Lowest CP values is 1

carseats.prune=prune(tree.carseatsR, cp= tree.carseatsR$cptable
                    [which.min(tree.carseatsR$cptable[, "xerror"]), "CP"])

The optimal level of tree complexity is 0.1 .

pred.treeR2 = predict(carseats.prune, newdata = TstCars)

mean((TstCars$Sales - pred.treeR2)^2)
## [1] 5.387279

The Test MSE did not change at all from 5.387 .

The lack of change suggests that the original fitted tree was close to the optimal level of complexity in the beginning. It could also mean that the initial tree was too small for pruning to have any effect.

(d) Use the bagging approach in order to analyze this data. What test MSE do you obtain? Use the importance() function to determine which variables are most important.

set.seed(70)

carseats.bag = randomForest(Sales ~ .,data = TrCars,mtry = 10,importance = TRUE)

pred.bag = predict(carseats.bag, newdata = TstCars)

mean((TstCars$Sales - pred.bag)^2)
## [1] 2.854362

I got 2.854 as the Test MSE.

importance(carseats.bag)
##                %IncMSE IncNodePurity
## CompPrice   24.7789221    159.790483
## Income       0.8593279     69.826501
## Advertising 16.2301682     86.682169
## Population   5.6905834     88.777363
## Price       58.8884723    520.466567
## ShelveLoc   59.1990735    579.876501
## Age         16.5266474    124.399759
## Education    3.7028321     44.966902
## Urban       -1.7660146      7.686481
## US           2.9544192     10.367423

The ‘Price’ and ‘ShelveLoc’ predictors are the most important.

(e) Use random forests to analyze this data. What test MSE do you obtain? Use the importance() function to determine which variables are most important. Describe the effect of m, the number of variables considered at each split, on the error rate obtained.

set.seed(70)

carseats.rf <- randomForest(Sales ~ .,data = TrCars,mtry = 3,importance = TRUE)

preds.carseatrf = predict(carseats.rf, newdata = TstCars)

mean((TstCars$Sales - preds.carseatrf)^2)
## [1] 2.866964

I got 2.867 as the Test MSE. Setting the m value (mtry) to 3, yielded a slightly larger then the bagging Test MSE.

Due to only 3 predictors being used to fit the model, the chances of one or both of the most significant predictors being selected is not guaranteed at each split.

In turn, this is why the value for the test MSE with a lower m value appears to be slightly higher.

importance(carseats.rf)
##                %IncMSE IncNodePurity
## CompPrice   11.9947795     146.95653
## Income      -2.0001225      99.97846
## Advertising 11.9311032     140.44725
## Population   4.1105093     122.14045
## Price       36.2710863     416.71891
## ShelveLoc   41.9820462     428.40872
## Age         11.4250685     160.42221
## Education    1.8370320      70.18331
## Urban       -0.3153778      14.34518
## US           2.7746808      35.61221

The ‘Price’ and ‘ShelveLoc’ predictors are also the most important.

(f) Now analyze the data using BART, and report your results.

train_control_2 = trainControl(method="cv",number=10)

gbm.Carseats=train(Sales~., data = TrCars, distribution = 'gaussian', 
                 method = 'gbm', trControl=train_control_2, verbose =F,
                 metric = "RMSE", bag.fraction=0.75)

print(gbm.Carseats)
## Stochastic Gradient Boosting 
## 
## 200 samples
##  10 predictor
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 180, 180, 180, 180, 180, 180, ... 
## Resampling results across tuning parameters:
## 
##   interaction.depth  n.trees  RMSE      Rsquared   MAE     
##   1                   50      1.881345  0.6686399  1.528630
##   1                  100      1.557719  0.7736024  1.266937
##   1                  150      1.371990  0.8123796  1.126254
##   2                   50      1.595215  0.7664999  1.288087
##   2                  100      1.376440  0.8124965  1.112762
##   2                  150      1.339979  0.8173340  1.063490
##   3                   50      1.475899  0.7918400  1.181378
##   3                  100      1.343987  0.8109825  1.066691
##   3                  150      1.347775  0.8081428  1.054331
## 
## Tuning parameter 'shrinkage' was held constant at a value of 0.1
## 
## Tuning parameter 'n.minobsinnode' was held constant at a value of 10
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were n.trees = 150, interaction.depth =
##  2, shrinkage = 0.1 and n.minobsinnode = 10.

The optimal amount of trees is 150 at 2 splits with a cv value at 0.1.

summary(gbm.Carseats)

##                             var    rel.inf
## Price                     Price 33.7929348
## ShelveLocGood     ShelveLocGood 27.2952517
## CompPrice             CompPrice 12.0918878
## Age                         Age  7.8395477
## Advertising         Advertising  6.6434572
## ShelveLocMedium ShelveLocMedium  5.9550195
## Income                   Income  2.6509657
## Population           Population  1.8675297
## USYes                     USYes  0.9414225
## Education             Education  0.7926277
## UrbanYes               UrbanYes  0.1293559

The most important predictors are ‘Price’ and ‘ShelveLocGood’. The only other semi-important predictor is ‘CompPrice’.

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

data("OJ")

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

set.seed(70)

trainOJ=sample(1:nrow(OJ), 800)

TrOJ = OJ[trainOJ,]
TstOJ = OJ[-trainOJ,]

(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?

set.seed(70)

tree.OJR=rpart(Purchase~., data = TrOJ, method="class", 
                    control=rpart.control(minsplit=15, cp=0.1)) 

summary(tree.OJR)
## Call:
## rpart(formula = Purchase ~ ., data = TrOJ, method = "class", 
##     control = rpart.control(minsplit = 15, cp = 0.1))
##   n= 800 
## 
##          CP nsplit rel error xerror       xstd
## 1 0.5210843      0 1.0000000    1.0 0.04197676
## 2 0.1000000      1 0.4789157    0.5 0.03454742
## 
## Variable importance
##        LoyalCH        StoreID WeekofPurchase      SpecialMM        PriceMM 
##             66             13              7              5              5 
##        PriceCH 
##              4 
## 
## Node number 1: 800 observations,    complexity param=0.5210843
##   predicted class=CH  expected loss=0.415  P(node) =1
##     class counts:   468   332
##    probabilities: 0.585 0.415 
##   left son=2 (435 obs) right son=3 (365 obs)
##   Primary splits:
##       LoyalCH   < 0.5039495 to the right, improve=139.18690, (0 missing)
##       StoreID   < 3.5       to the right, improve= 41.13141, (0 missing)
##       PriceDiff < 0.31      to the right, improve= 20.39110, (0 missing)
##       Store7    splits as  RL, improve= 20.24063, (0 missing)
##       STORE     < 0.5       to the left,  improve= 20.24063, (0 missing)
##   Surrogate splits:
##       StoreID        < 3.5       to the right, agree=0.635, adj=0.200, (0 split)
##       WeekofPurchase < 248.5     to the right, agree=0.589, adj=0.099, (0 split)
##       SpecialMM      < 0.5       to the left,  agree=0.578, adj=0.074, (0 split)
##       PriceMM        < 1.89      to the right, agree=0.575, adj=0.068, (0 split)
##       PriceCH        < 1.825     to the right, agree=0.574, adj=0.066, (0 split)
## 
## Node number 2: 435 observations
##   predicted class=CH  expected loss=0.1448276  P(node) =0.54375
##     class counts:   372    63
##    probabilities: 0.855 0.145 
## 
## Node number 3: 365 observations
##   predicted class=MM  expected loss=0.2630137  P(node) =0.45625
##     class counts:    96   269
##    probabilities: 0.263 0.737

The tree was fit with the model and determined that the ‘LoyalCH’ predictor is the most influential in determining ‘Purchase’. The optimal cp value was 0.1 and only 1 split was determined to be necessary.

pred.TrOJ<- predict(tree.OJR, TrOJ, type = "class")

train.errorOJ <- mean(pred.TrOJ != TrOJ$Purchase)
train.errorOJ
## [1] 0.19875

The training error is 0.19875.

The tree has 2 terminal nodes

(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.OJR
## n= 800 
## 
## node), split, n, loss, yval, (yprob)
##       * denotes terminal node
## 
## 1) root 800 332 CH (0.5850000 0.4150000)  
##   2) LoyalCH>=0.5039495 435  63 CH (0.8551724 0.1448276) *
##   3) LoyalCH< 0.5039495 365  96 MM (0.2630137 0.7369863) *
  1. If Customer brand loyalty is greater then .5039, there’s a 85.5% chance the customer will purchase Citrus Hill. There’s a 14.5% the customer will choose to purchase Minute Maid instead. Out of 435 observations, only 63 observations were misclassified.

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

fancyRpartPlot(tree.OJR)

If the value for Customer loyalty is greater then 50%, there’s 86% chance that the customer will buy Citrus Hill. If Customer loyalty is less then 50%, there’s a 74% chance the customer will buy Minute Maid instead.

Customer Loyalty is the only predictor used in the final 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?

OJ.pred = predict(tree.OJR, newdata = TstOJ, type = "class")

table(OJ.pred, TstOJ$Purchase)
##        
## OJ.pred  CH  MM
##      CH 148  18
##      MM  37  67
mean(OJ.pred != TstOJ$Purchase)
## [1] 0.2037037

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

printcp(tree.OJR)
## 
## Classification tree:
## rpart(formula = Purchase ~ ., data = TrOJ, method = "class", 
##     control = rpart.control(minsplit = 15, cp = 0.1))
## 
## Variables actually used in tree construction:
## [1] LoyalCH
## 
## Root node error: 332/800 = 0.415
## 
## n= 800 
## 
##        CP nsplit rel error xerror     xstd
## 1 0.52108      0   1.00000    1.0 0.041977
## 2 0.10000      1   0.47892    0.5 0.034547

The optimal tree size is 1 split because it has the lowest CV error and the best predictor is LoyalCH.

(g) Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.

plotcp(tree.OJR)

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

The lowest cross-validated classification tree size is 2.

(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.OJR = prune(tree.OJR, cp = 0.10)

pruned.OJR
## n= 800 
## 
## node), split, n, loss, yval, (yprob)
##       * denotes terminal node
## 
## 1) root 800 332 CH (0.5850000 0.4150000)  
##   2) LoyalCH>=0.5039495 435  63 CH (0.8551724 0.1448276) *
##   3) LoyalCH< 0.5039495 365  96 MM (0.2630137 0.7369863) *

Cross-validation selected a tree with two terminal nodes, which is the same size as the original tree.

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

OJ.predPrunedTr = predict(pruned.OJR, newdata = TrOJ, type = "class")

#table(OJ.predPrunedTr, TrOJ$Purchase)

mean(OJ.predPrunedTr != TrOJ$Purchase)
## [1] 0.19875

The pruned training error rate for a pruned tree is 0.19875 The unpruned training error rate for a unpruned tree is 0.19875

The training error rates are the same.

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

OJ.predPrunedTst = predict(pruned.OJR, newdata = TstOJ, type = "class")

#table(OJ.predPrunedTst, TstOJ$Purchase) 

mean(OJ.predPrunedTst != TstOJ$Purchase)
## [1] 0.2037037

The pruned test error rate for a pruned tree is 0.2037037 The unpruned test error rate for a unpruned tree is 0.2037037

The test error rates are the same.