library(ISLR)
library(tree)
library(rpart)
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice

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

pm1 = seq(0.0, 1.0, .01)
pm2 = 1 - pm1
classe = 1- pmax(pm1, 1 - pm1)
entropy = - pm1 * log(pm1) - pm2* log(pm2)
gini = pm1 * (1 - pm1) + pm2 *(1- pm2)

plot(pm1, entropy, typ = "l", xlab = "pm1", ylab = "Value")
lines(pm1, gini,  col = "green")
lines(pm1, classe, col = "blue")

## Problem 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.

attach(Carseats)
set.seed(1)
sample = sample(1:nrow(Carseats), nrow(Carseats)/2)
train = Carseats[sample,]
test = Carseats[-sample,]

(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain? The test MSE is 4.922039. Only 6 variables were used in constructing the tree with a total of 18 nodes.

set.seed(1)
tree.c = tree(Sales ~ ., data = train)
plot(tree.c)
text(tree.c, pretty = 0)

pred = predict(tree.c, test)
mean((test$Sales - pred) ^ 2)
## [1] 4.922039
summary(tree.c)
## 
## Regression tree:
## tree(formula = Sales ~ ., data = train)
## Variables actually used in tree construction:
## [1] "ShelveLoc"   "Price"       "Age"         "Advertising" "CompPrice"  
## [6] "US"         
## Number of terminal nodes:  18 
## Residual mean deviance:  2.167 = 394.3 / 182 
## Distribution of residuals:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -3.88200 -0.88200 -0.08712  0.00000  0.89590  4.09900

(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE? The optimal level of tree complexity is 17. It improved the MSE a little bit, bringing it down to 4.827162.

set.seed(1)
cv.tree = cv.tree(tree.c)
plot(cv.tree$size, cv.tree$dev, type = "b")

summary(cv.tree)
##        Length Class  Mode     
## size   17     -none- numeric  
## dev    17     -none- numeric  
## k      17     -none- numeric  
## method  1     -none- character
prune.c = prune.tree(tree.c, best = 17)
plot(prune.c)
text(prune.c, pretty = 0)

prune.pred = predict(prune.c, test)
mean((test$Sales - prune.pred) ^ 2)
## [1] 4.827162
summary(prune.c)
## 
## Regression tree:
## snip.tree(tree = tree.c, nodes = 21L)
## Variables actually used in tree construction:
## [1] "ShelveLoc"   "Price"       "Age"         "Advertising" "CompPrice"  
## [6] "US"         
## Number of terminal nodes:  17 
## Residual mean deviance:  2.248 = 411.3 / 183 
## Distribution of residuals:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -4.29900 -0.88200 -0.06379  0.00000  0.89590  4.09900

(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. The test MSE is 2.605253. The most important variables are Price and Shelveloc, the have the highest %IncMSE and IncNodePurity

library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
## 
##     margin
set.seed(1)
bag.c = randomForest(Sales ~., data = train , mtry = 10, importance = TRUE )
bag.c
## 
## Call:
##  randomForest(formula = Sales ~ ., data = train, mtry = 10, importance = TRUE) 
##                Type of random forest: regression
##                      Number of trees: 500
## No. of variables tried at each split: 10
## 
##           Mean of squared residuals: 2.889221
##                     % Var explained: 63.26
importance(bag.c)
##                %IncMSE IncNodePurity
## CompPrice   24.8888481    170.182937
## Income       4.7121131     91.264880
## Advertising 12.7692401     97.164338
## Population  -1.8074075     58.244596
## Price       56.3326252    502.903407
## ShelveLoc   48.8886689    380.032715
## Age         17.7275460    157.846774
## Education    0.5962186     44.598731
## Urban        0.1728373      9.822082
## US           4.2172102     18.073863
bag.cp = predict(bag.c, newdata = test)
bag.mse = mean((bag.cp - test$Sales)^2)
bag.mse
## [1] 2.605253
varImpPlot(bag.c)

(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. The test MSE is 2.90282. The most important variables are again Price and Shelveloc.

set.seed(1)
random.c = randomForest(Sales ~., data = train , mtry = 5, ntree = 30, importance = TRUE )
random.c
## 
## Call:
##  randomForest(formula = Sales ~ ., data = train, mtry = 5, ntree = 30,      importance = TRUE) 
##                Type of random forest: regression
##                      Number of trees: 30
## No. of variables tried at each split: 5
## 
##           Mean of squared residuals: 3.550771
##                     % Var explained: 54.84
random.f = predict(random.c, newdata = test)
random.mse = mean((random.f - test$Sales)^2)
random.mse
## [1] 2.90282
importance(random.c)
##                %IncMSE IncNodePurity
## CompPrice    4.2908277     143.26934
## Income       1.2067338     106.71853
## Advertising  2.8235763      85.25177
## Population  -1.7883987      90.00200
## Price       11.0694587     446.45794
## ShelveLoc    9.5648921     326.38912
## Age          4.5656248     196.56374
## Education    0.3828607      54.48205
## Urban       -1.0498078      13.97890
## US           1.6095756      28.77391

(f) Now analyze the data using BART, and report your results. The MSE using BART is 0.1603478. The lowest MSE obtained

library(BART)
## Loading required package: nlme
## Loading required package: nnet
## Loading required package: survival
## 
## Attaching package: 'survival'
## The following object is masked from 'package:caret':
## 
##     cluster
set.seed(1)
bart.c = gbart(train, train$Sales, x.test = test)
## *****Calling gbart: type=1
## *****Data:
## data:n,p,np: 200, 15, 200
## y1,yn: 2.781850, 1.091850
## x1,x[n*p]: 10.360000, 1.000000
## xp1,xp[np*p]: 11.220000, 1.000000
## *****Number of Trees: 200
## *****Number of Cut Points: 100 ... 1
## *****burn,nd,thin: 100,1000,1
## *****Prior:beta,alpha,tau,nu,lambda,offset: 2,0.95,0.273474,3,4.01382e-30,7.57815
## *****sigma: 0.000000
## *****w (weights): 1.000000 ... 1.000000
## *****Dirichlet:sparse,theta,omega,a,b,rho,augment: 0,0,1,0.5,1,15,0
## *****printevery: 100
## 
## MCMC
## done 0 (out of 1100)
## done 100 (out of 1100)
## done 200 (out of 1100)
## done 300 (out of 1100)
## done 400 (out of 1100)
## done 500 (out of 1100)
## done 600 (out of 1100)
## done 700 (out of 1100)
## done 800 (out of 1100)
## done 900 (out of 1100)
## done 1000 (out of 1100)
## time: 4s
## trcnt,tecnt: 1000,1000
bart.cp = bart.c$yhat.test.mean
mean((test$Sales - bart.cp)^2)
## [1] 0.1603478

Problem 9

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

library(ISLR2)
## 
## Attaching package: 'ISLR2'
## The following objects are masked from 'package:ISLR':
## 
##     Auto, Credit
attach(OJ)

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

set.seed(1)
train.ojs=sample(nrow(OJ), 800)
train.oj=OJ[train.ojs,]
test.oj=OJ[-train.ojs, ]

(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? The error rate is 0.1588 and there are 9 nodes in the tree.

set.seed(1)
tree.oj = tree(Purchase ~ ., data = train.oj)
plot(tree.oj)
text(tree.oj, pretty = 0)

summary(tree.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = train.oj)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "SpecialCH"     "ListPriceDiff"
## [5] "PctDiscMM"    
## Number of terminal nodes:  9 
## Residual mean deviance:  0.7432 = 587.8 / 791 
## Misclassification error rate: 0.1588 = 127 / 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. Number 8 customer brand loyalty for Citrus hill is split at less than .035 with 140.5 observations and a yprob of ( 0.01695 0.98305 )

tree.oj
## node), split, n, deviance, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 800 1073.00 CH ( 0.60625 0.39375 )  
##    2) LoyalCH < 0.5036 365  441.60 MM ( 0.29315 0.70685 )  
##      4) LoyalCH < 0.280875 177  140.50 MM ( 0.13559 0.86441 )  
##        8) LoyalCH < 0.0356415 59   10.14 MM ( 0.01695 0.98305 ) *
##        9) LoyalCH > 0.0356415 118  116.40 MM ( 0.19492 0.80508 ) *
##      5) LoyalCH > 0.280875 188  258.00 MM ( 0.44149 0.55851 )  
##       10) PriceDiff < 0.05 79   84.79 MM ( 0.22785 0.77215 )  
##         20) SpecialCH < 0.5 64   51.98 MM ( 0.14062 0.85938 ) *
##         21) SpecialCH > 0.5 15   20.19 CH ( 0.60000 0.40000 ) *
##       11) PriceDiff > 0.05 109  147.00 CH ( 0.59633 0.40367 ) *
##    3) LoyalCH > 0.5036 435  337.90 CH ( 0.86897 0.13103 )  
##      6) LoyalCH < 0.764572 174  201.00 CH ( 0.73563 0.26437 )  
##       12) ListPriceDiff < 0.235 72   99.81 MM ( 0.50000 0.50000 )  
##         24) PctDiscMM < 0.196196 55   73.14 CH ( 0.61818 0.38182 ) *
##         25) PctDiscMM > 0.196196 17   12.32 MM ( 0.11765 0.88235 ) *
##       13) ListPriceDiff > 0.235 102   65.43 CH ( 0.90196 0.09804 ) *
##      7) LoyalCH > 0.764572 261   91.20 CH ( 0.95785 0.04215 ) *

(d) Create a plot of the tree, and interpret the results. There are 16 terminal nodes

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? The test error rate is 0.1703704.

set.seed(1)
oj.pred = predict(tree.oj, test.oj, type = "class")
table(test.oj$Purchase, oj.pred)
##     oj.pred
##       CH  MM
##   CH 160   8
##   MM  38  64
mean(oj.pred!=test.oj$Purchase)
## [1] 0.1703704
confusionMatrix(test.oj$Purchase, oj.pred)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 160   8
##         MM  38  64
##                                           
##                Accuracy : 0.8296          
##                  95% CI : (0.7794, 0.8725)
##     No Information Rate : 0.7333          
##     P-Value [Acc > NIR] : 0.0001259       
##                                           
##                   Kappa : 0.6154          
##                                           
##  Mcnemar's Test P-Value : 1.904e-05       
##                                           
##             Sensitivity : 0.8081          
##             Specificity : 0.8889          
##          Pos Pred Value : 0.9524          
##          Neg Pred Value : 0.6275          
##              Prevalence : 0.7333          
##          Detection Rate : 0.5926          
##    Detection Prevalence : 0.6222          
##       Balanced Accuracy : 0.8485          
##                                           
##        'Positive' Class : CH              
## 

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

set.seed(1)
cv.oj = cv.tree(tree.oj, FUN = prune.misclass)
summary(cv.oj)
##        Length Class  Mode     
## size   6      -none- numeric  
## dev    6      -none- numeric  
## k      6      -none- numeric  
## method 1      -none- character
names(cv.oj)
## [1] "size"   "dev"    "k"      "method"

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

(h) Which tree size corresponds to the lowest cross-validated classification error rate? It looks like tree size four has the lowest but 8 is very close (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.

set.seed(1)
p.oj=prune.tree(tree.oj, best=4)
summary(p.oj)
## 
## Classification tree:
## snip.tree(tree = tree.oj, nodes = 4:6)
## Variables actually used in tree construction:
## [1] "LoyalCH"
## Number of terminal nodes:  4 
## Residual mean deviance:  0.8678 = 690.7 / 796 
## Misclassification error rate: 0.205 = 164 / 800
set.seed(1)
p.oj=prune.tree(tree.oj, best=5)
summary(p.oj)
## 
## Classification tree:
## snip.tree(tree = tree.oj, nodes = c(4L, 12L, 5L))
## Variables actually used in tree construction:
## [1] "LoyalCH"       "ListPriceDiff"
## Number of terminal nodes:  5 
## Residual mean deviance:  0.8239 = 655 / 795 
## Misclassification error rate: 0.205 = 164 / 800

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

set.seed(1)
unpruned.p = predict(tree.oj, newdata = train.oj, type="class")
table(train.oj$Purchase, unpruned.p)
##     unpruned.p
##       CH  MM
##   CH 450  35
##   MM  92 223
mean(train.oj$Purchase!=unpruned.p)
## [1] 0.15875
pruned.p = predict(p.oj, newdata = train.oj, type="class")
table(train.oj$Purchase, pruned.p)
##     pruned.p
##       CH  MM
##   CH 356 129
##   MM  40 275
mean(train.oj$Purchase!=pruned.p)
## [1] 0.21125

(k) Compare the test error rates between the pruned and unpruned trees. Which is higher? The test error rate for the pruned tree is 0.1925926 wich is higher than the unpruned tree at 0.1703704.

te.pred.prune = predict(p.oj, test.oj, type='class')
table(test.oj$Purchase, te.pred.prune)
##     te.pred.prune
##       CH  MM
##   CH 135  33
##   MM  19  83
mean(test.oj$Purchase!=te.pred.prune)
## [1] 0.1925926