3. Consider the Gini index, classification error, and cross-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 xaxis 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, \(pˆm1 = 1 − pˆm2\). You could make this plot by hand, but it will be much easier to make in R.
p = seq(0, 1, 0.01)
gini.index = 2 * p * (1 - p)
class.err = 1 - pmax(p, 1 - p)
cross.entr = - (p * log(p) + (1 - p) * log(1 - p))
matplot(p, cbind(gini.index, class.err, cross.entr), col = c("red", "green", "blue"))
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.
library(ISLR)
library(rpart)
library(caret)
library(tree)
library(randomForest)
(a) Split the data set into a training set and a test set.
attach(Carseats)
set.seed(2)
sample.car=sample(nrow(Carseats),nrow(Carseats)*0.7)
train.car=Carseats[sample.car,]
test.car=Carseats[-sample.car,]
(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test error rate do you obtain?
model.car = tree(Sales~.,train.car)
summary(model.car)
##
## Regression tree:
## tree(formula = Sales ~ ., data = train.car)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "CompPrice" "Age" "Advertising"
## Number of terminal nodes: 15
## Residual mean deviance: 2.318 = 614.3 / 265
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -4.00300 -1.13400 -0.04134 0.00000 1.01500 4.16000
plot(model.car)
text(model.car,pretty = 0)
prediction.tree = predict(model.car,newdata=test.car)
mean((test.car$Sales-prediction.tree)^2)
## [1] 4.805327
Based on our model above our test MSE was at 4.805327
(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test error rate?
set.seed(3)
cv.car=cv.tree(model.car)
plot(cv.car$size,cv.car$dev,xlab = "Tree size" , ylab= "Deviance" , type = "b")
prune.car<-prune.tree(model.car,best=7)
plot(prune.car)
text(prune.car,pretty=0)
prune.predict=predict(prune.car,test.car)
mean((prune.predict-test.car$Sales)^2)
## [1] 5.777114
The size to which the tree should be pruned at optimal decision was 7. The pruned tree theres a 5.777114 MSE
(d) Use the bagging approach in order to analyze this data. What test error rate do you obtain? Use the importance() function to determine which variables are most important. 334 8. Tree-Based Methods
bagging.car = randomForest(Sales~.,train.car,importance=TRUE,mtry=13)
importance(bagging.car)
## %IncMSE IncNodePurity
## CompPrice 32.3498251 263.736121
## Income 7.7743280 103.459581
## Advertising 21.5763581 161.543966
## Population 0.7121014 73.398908
## Price 72.0070548 701.045999
## ShelveLoc 66.0513075 488.387286
## Age 17.2059118 180.595960
## Education 1.9229589 56.330583
## Urban -1.2457543 8.682964
## US 4.7597999 8.799835
predict.bagCar= predict(bagging.car,test.car)
mean((predict.bagCar-test.car$Sales)^2)
## [1] 2.642365
Implementing the bagging model we see that the test MSE dropped to 2.643583. WIth Price and ShelvLoc being the most important variables
(e) Use random forests to analyze this data. What test error rate 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.
rf.car=randomForest(Sales~.,train.car,importance=TRUE,mtry=sqrt(13))
importance(rf.car)
## %IncMSE IncNodePurity
## CompPrice 20.941069 224.54313
## Income 6.929272 153.00102
## Advertising 14.520835 171.39674
## Population -0.559691 103.56503
## Price 53.248598 611.25806
## ShelveLoc 46.605378 416.30556
## Age 12.711304 210.83567
## Education 2.247890 81.30471
## Urban 1.083535 15.18158
## US 3.475638 20.07580
predict.RfCar = predict(rf.car,test.car)
mean((predict.RfCar-test.car$Sales)^2)
## [1] 2.739237
Implementing the Random Forest model the test MSE was at 2.766911. In conclusion our best performing model was bagging with a test MSE at 2.643583
This problem involves the OJ data set which is part of the ISLR package.
library(ISLR)
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
attach(OJ)
sample.oj=sample(1:nrow(OJ),800)
train.oj = OJ[sample.oj,]
test.oj= OJ[-sample.oj,]
(b) Fit a tree to the training data, with Purchase as the response and the other variables except for Buy 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?
tree.oj=tree(Purchase~.,train.oj)
summary(tree.oj)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train.oj)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 9
## Residual mean deviance: 0.7456 = 589.7 / 791
## Misclassification error rate: 0.155 = 124 / 800
The variables used to for the tree construction were LoyalCH, SalePriceMM, and PriceDiff. With 7 terminal nodes and a error rate of 15%
(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.oj
## node), split, n, deviance, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 1068.000 CH ( 0.61250 0.38750 )
## 2) LoyalCH < 0.5036 351 415.700 MM ( 0.27920 0.72080 )
## 4) LoyalCH < 0.0616725 69 10.450 MM ( 0.01449 0.98551 ) *
## 5) LoyalCH > 0.0616725 282 363.000 MM ( 0.34397 0.65603 )
## 10) PriceDiff < 0.195 125 125.100 MM ( 0.20000 0.80000 ) *
## 11) PriceDiff > 0.195 157 216.600 MM ( 0.45860 0.54140 )
## 22) LoyalCH < 0.277977 59 64.660 MM ( 0.23729 0.76271 ) *
## 23) LoyalCH > 0.277977 98 132.500 CH ( 0.59184 0.40816 ) *
## 3) LoyalCH > 0.5036 449 341.700 CH ( 0.87305 0.12695 )
## 6) PriceDiff < -0.39 21 26.730 MM ( 0.33333 0.66667 ) *
## 7) PriceDiff > -0.39 428 279.100 CH ( 0.89953 0.10047 )
## 14) LoyalCH < 0.705326 139 142.400 CH ( 0.79137 0.20863 )
## 28) PriceDiff < -0.165 15 20.190 MM ( 0.40000 0.60000 ) *
## 29) PriceDiff > -0.165 124 109.600 CH ( 0.83871 0.16129 )
## 58) LoyalCH < 0.684038 117 89.610 CH ( 0.87179 0.12821 ) *
## 59) LoyalCH > 0.684038 7 8.376 MM ( 0.28571 0.71429 ) *
## 15) LoyalCH > 0.705326 289 112.100 CH ( 0.95156 0.04844 ) *
(d) Create a plot of the tree, and interpret the results
plot(tree.oj)
text(tree.oj,pretty = 0)
for question (c) and (d) we can conclude that the most important variable is LoyalCH as it appears in the Top 3 nodes
(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?
predict.oj= predict(tree.oj,newdata = test.oj,type = "class")
table(test.oj$Purchase,predict.oj,dnn = c("Actual", "Predicted"))
## Predicted
## Actual CH MM
## CH 143 20
## MM 32 75
(21+37)/nrow(test.oj)
## [1] 0.2148148
Test Error Rate : 21.48%
(f) Apply the cv.tree() function to the training set in order to determine the optimal tree size.
cv.oj=cv.tree(tree.oj, FUN = prune.misclass)
cv.oj
## $size
## [1] 9 6 3 2 1
##
## $dev
## [1] 160 164 168 164 305
##
## $k
## [1] -Inf 2 6 7 155
##
## $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(cv.oj$size,cv.oj$dev,xlab="Tree Size",ylab="CV Deviance",type = "b")
points(4,min(cv.oj$dev),col="red")
(h) Which tree size corresponds to the lowest cross-validated classification error rate?
Tree Size 4
(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.
prune.oj<-prune.misclass(tree.oj,best=4)
plot(prune.oj)
text(prune.oj,pretty=0)
(j) Compare the training error rates between the pruned and unpruned trees. Which is higher?
summary(prune.oj)
##
## Classification tree:
## snip.tree(tree = tree.oj, nodes = 7L)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 6
## Residual mean deviance: 0.8043 = 638.6 / 794
## Misclassification error rate: 0.1625 = 130 / 800
With the training data set Pruned Tree error rate was at 16% while the full tree eroor rate was at 15%. Therefore pruning did not help reduce the error rate
(k) Compare the test error rates between the pruned and unpruned trees. Which is higher?
prune.predict=predict(prune.oj,newdata = test.oj,type="class")
table(test.oj$Purchase,prune.predict,dnn = c("Actual","Predicted"))
## Predicted
## Actual CH MM
## CH 144 19
## MM 34 73
oj.testerror.prune=(40+15)/nrow(test.oj)
round(oj.testerror.prune,3)
## [1] 0.204
With the testing data set Pruned Tree error rate was at 20.4% while the full tree error rate was at 21.5%. Therefore pruning did in fact help reduce the error rate. Though they might be signs over overfitting the data