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)

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.
- Split the data set into a training set and a test set.
set.seed(1)
train<-sample(1:nrow(Carseats),nrow(Carseats)/2)
- Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
tree.carseats <- tree(formula=Sales~.,data=Carseats,subset = train)
plot(tree.carseats)
text(tree.carseats)

tree.carseat2 <- rpart(Sales~.,data=Carseats,subset = train)
fancyRpartPlot(tree.carseat2)

tree.pred2 <- predict(tree.carseat2,Carseats[-train,])
mean((tree.pred2-Carseats[-train,'Sales'])^2)
## [1] 5.165182
tree.pred <- predict(tree.carseats,Carseats[-train,])
mean((tree.pred-Carseats[-train,'Sales'])^2)
## [1] 4.922039
The decision tree had MSE around 5.0
- Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
tree.carseats.cv=cv.tree(tree.carseats)
plot(tree.carseats.cv)

printcp(tree.carseat2)
##
## Regression tree:
## rpart(formula = Sales ~ ., data = Carseats, subset = train)
##
## Variables actually used in tree construction:
## [1] Advertising Age CompPrice Price ShelveLoc Urban
## [7] US
##
## Root node error: 1572.7/200 = 7.8634
##
## n= 200
##
## CP nsplit rel error xerror xstd
## 1 0.214665 0 1.00000 1.01810 0.092661
## 2 0.101606 1 0.78533 0.85580 0.076755
## 3 0.074204 2 0.68373 0.86999 0.081939
## 4 0.063328 3 0.60952 0.81915 0.076191
## 5 0.048464 4 0.54620 0.76465 0.068430
## 6 0.033428 5 0.49773 0.71550 0.065359
## 7 0.025914 6 0.46431 0.73310 0.064712
## 8 0.025127 8 0.41248 0.74708 0.065786
## 9 0.020072 9 0.38735 0.73815 0.065887
## 10 0.018437 10 0.36728 0.72888 0.064208
## 11 0.013075 11 0.34884 0.69277 0.063229
## 12 0.010807 12 0.33577 0.68953 0.062993
## 13 0.010272 13 0.32496 0.68010 0.062602
## 14 0.010000 14 0.31469 0.68010 0.062602
prune.carseats=prune.tree(tree.carseats,best=6)
plot(prune.carseats)
text(prune.carseats)

tree.car.pred=predict(prune.carseats,Carseats[-train,])
mean((tree.car.pred-Carseats[-train,'Sales'])^2)
## [1] 5.318073
min.car.seat<-tree.carseat2$cptable[which.min(tree.carseat2$cptable[,"xerror"]),"CP"]
prune.carseat2 <-prune(tree.carseat2, cp =min.car.seat)
tree.car.pred2 <-predict(prune.carseat2,Carseats[-train,])
mean((tree.car.pred2-Carseats[-train,'Sales'])^2)
## [1] 5.249431
fancyRpartPlot(prune.carseat2)

Prunning does not reduce the mean residual error of the predictions.
- 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.
d=ncol(Carseats)-1
set.seed(1)
carseats.bag <- randomForest(Sales~.,data=Carseats,subset=train,mtry=d,importance=F,ntree=100)
tree.pred.bag <- predict(carseats.bag,Carseats[-train,])
mean((tree.pred.bag-Carseats[-train,'Sales'])^2)
## [1] 2.696891
- 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(1)
carseats.rf=randomForest(Sales~.,data=Carseats,subset=train,mtry=6,importance=T,ntree=100)
tree.pred.rf <- predict(carseats.rf,Carseats[-train,])
mean((tree.pred.rf-Carseats[-train,'Sales'])^2)
## [1] 2.73953
carseats.rf$importance
## %IncMSE IncNodePurity
## CompPrice 1.07273134 165.11421
## Income 0.07051408 100.19254
## Advertising 0.56119643 98.35028
## Population 0.00804708 70.24815
## Price 4.18669399 453.55455
## ShelveLoc 3.10288571 363.84767
## Age 0.94816980 180.08672
## Education 0.06594809 49.83424
## Urban 0.01719917 12.92851
## US 0.13273520 32.19317
The M parameter in the model select how many variables will be used in each tree within the forest. That limit the correlation between each tree as they will not be based on the same variables. In this particular case, bagging had a smaller error rate. But that is due the small size of the dataset.
9. This problem involves the OJ data set which is part of the ISLR package.
- 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,]
- 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.
- 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.
- 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.
- 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
- 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)
- Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.
plot(OJ.tree.cv)

- Which tree size corresponds to the lowest cross-validated classification error rate?
4
- 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)

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