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, 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= 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),xlab='pm1',ylab='values from 0 to 1')
lines(p,gini,col = 'blue')
lines(p,classerror,col='black')
lines(p,crossentropy,col='green')
legend(x='top',legend=c('gini','class error','cross entropy'),
col=c('blue','black','green'),lty=1,text.width = 0.22)
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.
library(ISLR)
set.seed(7)
# now time to build the training and test sets #
train = sample(1:nrow(Carseats), nrow(Carseats)/2)
Carseats_train <- Carseats[train,]
Carseats_test <- Carseats[-train,]
The data is now split into a training and test set.
(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
# first we get the regression tree on the training set #
library(tree)
## Warning: package 'tree' was built under R version 4.1.3
tree_Carseats <- tree(Sales~., data = Carseats_train)
#next we make a plot#
plot(tree_Carseats)
text(tree_Carseats)
based on this regression tree we can see that Shelve location and Price are the most important predictors.
Now we get the test MSE
# this code gets the test MSE #
tree_pred <- predict(tree_Carseats, Carseats_test)
test_mse <- mean((tree_pred-Carseats_test$Sales)^2)
test_mse
## [1] 4.765435
The test MSE is 4.765435.
(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
set.seed(7)
cv_Carseats <- cv.tree(tree_Carseats)
plot(cv_Carseats$size, cv_Carseats$dev, xlab = "# of terminal nodes", ylab = "cross validation error", type = "b")
We can see that the cv error does not dramatically decrease after more than 6 terminal nodes. Next we will prune the model to have 6 terminal nodes.
prune_Carseats <- prune.tree(tree_Carseats, best = 6)
# now we can get the test MSE of this pruned tree #
tree_pred <- predict(prune_Carseats, Carseats_test)
test_mse <- mean((tree_pred-Carseats_test$Sales)^2)
test_mse
## [1] 4.448592
Here we see that the test MSE has decreased to 4.448592.
(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.
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.1.3
## randomForest 4.7-1
## Type rfNews() to see new features/changes/bug fixes.
set.seed(7)
bag_Carseats <- randomForest(Carseats_train$Sales~., data = Carseats_train, mtry = 10, importance = TRUE)
bag_Carseats
##
## Call:
## randomForest(formula = Carseats_train$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.945681
## % Var explained: 67.23
#now get test MSE #
bag_pred <- predict(bag_Carseats, Carseats_test)
test_mse <- mean((bag_pred-Carseats_test$Sales)^2)
test_mse
## [1] 2.352134
#now plot#
plot(bag_Carseats)
varImpPlot(bag_Carseats)
Here we see that the mean square error decreases to 2.352 using bagging. The variable importance plot shows that shelve location and price are the most important variables.
(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(7)
rf_Carseats <- randomForest(Carseats_train$Sales~.,data = Carseats_train, importance=TRUE)
rf_Carseats
##
## Call:
## randomForest(formula = Carseats_train$Sales ~ ., data = Carseats_train, importance = TRUE)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 3
##
## Mean of squared residuals: 3.299988
## % Var explained: 63.29
# now get the test MSE #
yhat_rf <-predict(rf_Carseats, newdata = Carseats_test)
rf_mse <- mean((yhat_rf-Carseats_test$Sales)^2)
# now use importance function #
importance(rf_Carseats)
## %IncMSE IncNodePurity
## CompPrice 7.8250023 136.13136
## Income 0.6547144 105.42039
## Advertising 13.2914493 150.93588
## Population 1.5889887 113.39707
## Price 37.7823496 424.67020
## ShelveLoc 39.7564258 417.07473
## Age 17.2844151 221.63789
## Education 2.9320469 83.08323
## Urban 0.4656180 11.91653
## US 2.0176005 22.60699
rf_mse
## [1] 2.770891
Using the random forest technique, with m = 3 predictors, the test mean square error increased slightly from the bagging method to 2.770. We can see from the importance function that again shelve location and price are the most important predictors.
#testing with m=2#
set.seed(7)
rf_Carseats <- randomForest(Carseats_train$Sales~.,data = Carseats_train,mtry = 2, importance=TRUE)
# now get the test MSE #
yhat_rf <-predict(rf_Carseats, newdata = Carseats_test)
rf_mse <- mean((yhat_rf-Carseats_test$Sales)^2)
rf_mse
## [1] 3.136767
#testing with m=6#
set.seed(7)
rf_Carseats <- randomForest(Carseats_train$Sales~.,data = Carseats_train,mtry = 6, importance=TRUE)
# now get the test MSE #
yhat_rf <-predict(rf_Carseats, newdata = Carseats_test)
rf_mse <- mean((yhat_rf-Carseats_test$Sales)^2)
rf_mse
## [1] 2.425748
#testing with m=9#
set.seed(7)
rf_Carseats <- randomForest(Carseats_train$Sales~.,data = Carseats_train,mtry = 9, importance=TRUE)
# now get the test MSE #
yhat_rf <-predict(rf_Carseats, newdata = Carseats_test)
rf_mse <- mean((yhat_rf-Carseats_test$Sales)^2)
rf_mse
## [1] 2.342354
We can see from this that as m increases the test mean square error decreases.
9. 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.
library(ISLR)
set.seed(85)
model_train <- sample(1:nrow(OJ), 800)
OJ_train <- OJ[model_train,]
OJ_test <- OJ[-model_train,]
(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" "STORE"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7642 = 605.2 / 792
## Misclassification error rate: 0.1625 = 130 / 800
We can see from this summary that the training error rate is 16.25% and there are 8 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.
OJ_tree
## node), split, n, deviance, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 1078.00 CH ( 0.598750 0.401250 )
## 2) LoyalCH < 0.50395 355 418.30 MM ( 0.276056 0.723944 )
## 4) LoyalCH < 0.276142 173 127.90 MM ( 0.121387 0.878613 ) *
## 5) LoyalCH > 0.276142 182 248.00 MM ( 0.423077 0.576923 )
## 10) PriceDiff < 0.195 85 87.77 MM ( 0.211765 0.788235 ) *
## 11) PriceDiff > 0.195 97 129.90 CH ( 0.608247 0.391753 ) *
## 3) LoyalCH > 0.50395 445 366.50 CH ( 0.856180 0.143820 )
## 6) LoyalCH < 0.764572 193 226.90 CH ( 0.725389 0.274611 )
## 12) PriceDiff < 0.265 116 157.30 CH ( 0.586207 0.413793 )
## 24) PriceDiff < -0.35 17 15.84 MM ( 0.176471 0.823529 ) *
## 25) PriceDiff > -0.35 99 127.40 CH ( 0.656566 0.343434 ) *
## 13) PriceDiff > 0.265 77 37.01 CH ( 0.935065 0.064935 ) *
## 7) LoyalCH > 0.764572 252 90.41 CH ( 0.956349 0.043651 )
## 14) STORE < 1.5 139 11.86 CH ( 0.992806 0.007194 ) *
## 15) STORE > 1.5 113 67.58 CH ( 0.911504 0.088496 ) *
Here is the 4th split, which is a terminal node. 4) LoyalCH < 0.276142 173 127.90 MM ( 0.121387 0.878613 ) *. The split of this branch is LoyalCH < 0.276142 . There are 173 observations in this node, and the final prediction for this node is MM.
(d) Create a plot of the tree, and interpret the results.
plot(OJ_tree)
text(OJ_tree)
This tree shows us that when customers have a low loyalty to Citrus Hill, they are more likely to buy Minute Maid unless Citrus Hill costs 19.5 cents less than Minute Maid. If customers have a high loyalty to Citrus Hill, they are more likely to buy Citrus Hill over Minute Maid unless Minute Maid is 35 cents less expensive than Citrus Hill.
(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?
pred_OJ <- predict(OJ_tree, newdata = OJ_test, type = "class")
table(pred_OJ,OJ_test$Purchase)
##
## pred_OJ CH MM
## CH 158 32
## MM 16 64
48/270
## [1] 0.1777778
We can see from this result that the test error rate is 17.778, which is higher than the error rate for the training set as expected.
(f) Apply the cv.tree() function to the training set in order to determine the optimal tree size.
set.seed(85)
cv_OJ <- cv.tree(OJ_tree, FUN = prune.misclass)
cv_OJ
## $size
## [1] 8 7 4 2 1
##
## $dev
## [1] 151 151 152 165 321
##
## $k
## [1] -Inf 0.000000 3.666667 10.500000 159.000000
##
## $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 = "cross-validated classification", type = "b")
(h) Which tree size corresponds to the lowest cross-validated classification error rate?
based on the plot, it appears that trees with 7 or 8 terminal nodes have the lowest cross-validated 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.
prune_OJ <- prune.tree(OJ_tree, best = 5)
plot(prune_OJ)
text(prune_OJ)
(j) Compare the training error rates between the pruned and unpruned trees. Which is higher?
pred_prune = predict(prune_OJ, newdata = OJ_train, type = "class")
table(pred_prune,OJ_train$Purchase)
##
## pred_prune CH MM
## CH 381 64
## MM 98 257
(64+98)/800
## [1] 0.2025
the error rate on the training set after pruning is higher than the unpruned model.
(k) Compare the test error rates between the pruned and unpruned trees. Which is higher?
pred_prune = predict(prune_OJ, newdata = OJ_test, type = "class")
table(pred_prune,OJ_test$Purchase)
##
## pred_prune CH MM
## CH 139 17
## MM 35 79
(35+17)/270
## [1] 0.1925926
the error rate on the test set after pruning is higher than the error rate of the unpruned model.