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 pˆm1. The x- axis should display pˆm1, ranging from 0 to 1, and the y-axis should display the value of the Gini index, classification error, and entropy.
p <- seq(0, 1, 0.01)
gini.index = 2 * p * (1 - p)
class.error = 1 - pmax(p, 1 - p)
cross.entropy = - (p * log(p) + (1 - p) * log(1 - p))
matplot(p, cbind(gini.index, class.error, cross.entropy), col = c("red", "green", "blue"))
## Exercise 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.
data("Carseats")
set.seed(80)
Carseats.split = initial_split(Carseats, strata = Sales, prop = .8)
Carseats.train = training(Carseats.split)
Carseats.test = testing (Carseats.split)
(B) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
Carseats.tree = tree(Sales ~., data=Carseats.train)
summary(Carseats.tree)
##
## Regression tree:
## tree(formula = Sales ~ ., data = Carseats.train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "Age" "Income" "Advertising"
## Number of terminal nodes: 16
## Residual mean deviance: 2.658 = 805.3 / 303
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -4.851 -1.137 0.035 0.000 1.137 3.906
plot(Carseats.tree)
text(Carseats.tree, pretty=0)
Carseats.tree
## node), split, n, deviance, yval
## * denotes terminal node
##
## 1) root 319 2583.00 7.501
## 2) ShelveLoc: Bad,Medium 247 1500.00 6.757
## 4) Price < 105.5 85 467.20 8.265
## 8) Age < 49.5 35 123.30 9.523
## 16) Income < 56 11 15.12 7.992 *
## 17) Income > 56 24 70.53 10.220 *
## 9) Age > 49.5 50 249.80 7.384
## 18) Income < 100.5 40 151.30 6.792
## 36) ShelveLoc: Bad 15 57.54 5.481
## 72) Income < 86 9 19.02 4.376 *
## 73) Income > 86 6 11.01 7.140 *
## 37) ShelveLoc: Medium 25 52.52 7.579 *
## 19) Income > 100.5 10 28.38 9.752 *
## 5) Price > 105.5 162 738.40 5.966
## 10) ShelveLoc: Bad 47 192.70 4.626
## 20) Age < 65.5 37 137.00 5.112
## 40) Price < 144 30 74.96 5.594 *
## 41) Price > 144 7 25.22 3.047 *
## 21) Age > 65.5 10 14.68 2.828 *
## 11) ShelveLoc: Medium 115 426.70 6.514
## 22) Age < 49.5 47 139.30 7.521 *
## 23) Age > 49.5 68 206.90 5.818
## 46) Advertising < 2.5 22 38.47 4.655 *
## 47) Advertising > 2.5 46 124.40 6.375 *
## 3) ShelveLoc: Good 72 478.50 10.050
## 6) Price < 109.5 22 68.98 12.470 *
## 7) Price > 109.5 50 223.90 8.986
## 14) Advertising < 14 42 139.50 8.463
## 28) Price < 142.5 31 74.60 8.962 *
## 29) Price > 142.5 11 35.47 7.058 *
## 15) Advertising > 14 8 12.68 11.730 *
tree.pred = predict(Carseats.tree, newdata = Carseats.test)
mean((tree.pred - Carseats.test$Sales)^2)
## [1] 4.609654
The test MSE is 4.609654.
(C) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
set.seed(40)
(Carseats.cv = cv.tree(Carseats.tree))
## $size
## [1] 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
##
## $dev
## [1] 1494.096 1501.535 1547.390 1546.254 1546.254 1512.667 1512.667 1440.412
## [9] 1476.161 1462.447 1493.145 1519.033 1576.524 1726.050 2015.207 2613.852
##
## $k
## [1] -Inf 27.51175 29.41571 36.80553 37.60295 41.06340 41.24406
## [8] 44.00570 70.08096 71.77521 80.58436 94.16759 118.95542 185.59077
## [15] 294.51876 604.77267
##
## $method
## [1] "deviance"
##
## attr(,"class")
## [1] "prune" "tree.sequence"
plot(Carseats.cv$size,Carseats.cv$dev,xlab = "Size of Tree",ylab = "Deviance",type = "b")
tree.min <- which.min(Carseats.cv$dev)
points(tree.min, Carseats.cv$dev[tree.min], col = "red", cex = 2, pch = 20)
Cross Validations identified that a tree with 8 nodes would be best.
Carseats.prune<-prune.tree(Carseats.tree,best=8)
plot(Carseats.prune)
text(Carseats.prune,pretty=0)
prune.pred = predict(Carseats.prune, newdata= Carseats.test)
(mean((prune.pred-Carseats.test$Sales)^2))
## [1] 4.746612
Pruning the tree increased the Test MSE to 4.746612.
(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(32)
(Carseat.bag = randomForest(Sales~., data = Carseats.train, mtry = 10, importance = TRUE))
##
## Call:
## randomForest(formula = Sales ~ ., data = Carseats.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.570221
## % Var explained: 68.26
bag.pred =predict(Carseat.bag, newdata = Carseats.test)
mean((bag.pred - Carseats.test$Sales)^2)
## [1] 1.992814
The Test MSE decreased to 1.992814.
importance(Carseat.bag)
## %IncMSE IncNodePurity
## CompPrice 28.0848739 251.23343
## Income 10.1463085 152.12294
## Advertising 22.8378486 203.57589
## Population -0.2927063 93.19977
## Price 69.0407143 746.46578
## ShelveLoc 78.5988228 750.13345
## Age 20.7156289 238.78085
## Education 2.3575730 71.29455
## Urban -1.8454983 11.34849
## US 2.7460705 13.95880
The two most important variables are Price and ShelveLoc.
(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(90)
Carseats.rf <- randomForest(Sales ~ ., data = Carseats.train, mtry = 3, ntree = 500, importance = TRUE)
rf.preds <- predict(Carseats.rf, newdata = Carseats.test)
mean((rf.preds - Carseats.test$Sales)^2)
## [1] 2.347761
The Test MSE increased to 2.347761. This indicates that random forest yielded an improvement over bagging in the same case.
importance(Carseats.rf)
## %IncMSE IncNodePurity
## CompPrice 13.882142 226.62309
## Income 5.756639 201.72632
## Advertising 16.133567 230.95358
## Population -1.002238 172.26872
## Price 46.864754 608.39919
## ShelveLoc 47.255009 559.64237
## Age 15.343072 283.31535
## Education 1.677001 106.86362
## Urban -1.539836 21.14679
## US 3.348941 28.16114
varImpPlot(Carseats.rf)
The results indicate that across all of the trees considered in the random forest, the price a company charges for a car seat (Price) and the quality of the shelving location (ShelveLoc.) are by far the two most important variables.
This problem involves the OJ data set which is part of the ISLR package.
(A) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
data(OJ)
set.seed(20)
OJ.split = initial_split(OJ, prop = .748)
OJ.train = training(OJ.split)
OJ.test = testing (OJ.split)
(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=OJ.train)
summary(OJ.tree)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7532 = 596.6 / 792
## Misclassification error rate: 0.1638 = 131 / 800
The tree is a classification tree that uses three variables in the tree constructions: LoyalCH, PriceDiff, and ListPriceDiff. The tree has 8 terminal nodes and a training error rate of 16.38%.
(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 1072.00 CH ( 0.6075 0.3925 )
## 2) LoyalCH < 0.5036 352 418.30 MM ( 0.2812 0.7188 )
## 4) LoyalCH < 0.264232 162 117.10 MM ( 0.1173 0.8827 )
## 8) LoyalCH < 0.0356415 52 0.00 MM ( 0.0000 1.0000 ) *
## 9) LoyalCH > 0.0356415 110 101.20 MM ( 0.1727 0.8273 ) *
## 5) LoyalCH > 0.264232 190 258.60 MM ( 0.4211 0.5789 )
## 10) PriceDiff < 0.05 77 81.30 MM ( 0.2208 0.7792 ) *
## 11) PriceDiff > 0.05 113 155.20 CH ( 0.5575 0.4425 ) *
## 3) LoyalCH > 0.5036 448 356.50 CH ( 0.8638 0.1362 )
## 6) LoyalCH < 0.764572 198 221.60 CH ( 0.7525 0.2475 )
## 12) PriceDiff < -0.165 26 28.09 MM ( 0.2308 0.7692 ) *
## 13) PriceDiff > -0.165 172 156.10 CH ( 0.8314 0.1686 )
## 26) ListPriceDiff < 0.135 24 33.10 MM ( 0.4583 0.5417 ) *
## 27) ListPriceDiff > 0.135 148 101.40 CH ( 0.8919 0.1081 ) *
## 7) LoyalCH > 0.764572 250 96.29 CH ( 0.9520 0.0480 ) *
Selection: Terminal node 3. .The split criterion is LoyalCH > 0.5036. The number of observations is 448 and with a deviance of 356.50. The overall prediction for the CH branch of 86.38%%. and the remaining 13.62% belong to the MM branch..
(D) Create a plot of the tree, and interpret the results.
plot(OJ.tree)
text(OJ.tree, pretty=0)
The tree plot indicates the most important indicator of Purchase is LoyalCH, since the first branch differentiates the intensity of customer brand loyalty to CH.
(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?
tree.pred<-predict(OJ.tree, OJ.test, type = 'class')
obs.purch<-OJ.test$Purchase
caret::confusionMatrix(tree.pred, obs.purch)
## Confusion Matrix and Statistics
##
## Reference
## Prediction CH MM
## CH 142 24
## MM 25 79
##
## Accuracy : 0.8185
## 95% CI : (0.7673, 0.8626)
## No Information Rate : 0.6185
## P-Value [Acc > NIR] : 8.068e-13
##
## Kappa : 0.6161
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 0.8503
## Specificity : 0.7670
## Pos Pred Value : 0.8554
## Neg Pred Value : 0.7596
## Prevalence : 0.6185
## Detection Rate : 0.5259
## Detection Prevalence : 0.6148
## Balanced Accuracy : 0.8086
##
## 'Positive' Class : CH
##
The test error rate for the predictions is 18.15%.
(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))
## $size
## [1] 8 7 6 4 2 1
##
## $dev
## [1] 173 173 168 170 170 314
##
## $k
## [1] -Inf 0.0 2.0 6.5 7.0 154.0
##
## $method
## [1] "misclass"
##
## attr(,"class")
## [1] "prune" "tree.sequence"
The optimal tree size it 6 nodes.
(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,xlab = "Size of Tree",ylab = "Deviance",type = "b")
tree.min <- which.min(OJ.cv$dev)
points(tree.min, OJ.cv$dev[tree.min], col = "red", cex = 2, pch = 20)
(H) Which tree size corresponds to the lowest cross-validated classification error rate?
The plot suggest that a tree with 3 nodes will have the lowest classification error rate.
(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.misclass(OJ.tree, best = 3)
plot(OJ.prune)
text(OJ.prune, pretty = 0)
(J) Compare the training error rates between the pruned and un-pruned trees. Which is higher?
summary(OJ.tree)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7532 = 596.6 / 792
## Misclassification error rate: 0.1638 = 131 / 800
summary(OJ.prune)
##
## Classification tree:
## snip.tree(tree = OJ.tree, nodes = c(13L, 2L))
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 4
## Residual mean deviance: 0.8778 = 698.7 / 796
## Misclassification error rate: 0.1825 = 146 / 800
The misclassifications error rate fort the pruned tree (OJ.prune) is 0.1825 which is slightly higher than the un-pruned tree’s (OJ.tree) misclassification error rate of 0.1638.
(K) Compare the test error rates between the pruned and unpruned trees. Which is higher?
prune.pred<-predict(OJ.prune, OJ.test, type = "class")
caret::confusionMatrix(prune.pred, obs.purch)
## Confusion Matrix and Statistics
##
## Reference
## Prediction CH MM
## CH 127 12
## MM 40 91
##
## Accuracy : 0.8074
## 95% CI : (0.7552, 0.8527)
## No Information Rate : 0.6185
## P-Value [Acc > NIR] : 1.585e-11
##
## Kappa : 0.6121
##
## Mcnemar's Test P-Value : 0.000181
##
## Sensitivity : 0.7605
## Specificity : 0.8835
## Pos Pred Value : 0.9137
## Neg Pred Value : 0.6947
## Prevalence : 0.6185
## Detection Rate : 0.4704
## Detection Prevalence : 0.5148
## Balanced Accuracy : 0.8220
##
## 'Positive' Class : CH
##
The test error rate for the prediction of the pruned tree is 19.26% and the test error rate for or the predictions of the un-pruned tree is 18.15%. The pruned tree’s test erro rate is slightly higher.