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_index <- 2 * p * (1 - p)
classification_error <- 1 - pmax(p, 1 - p)
entropy <- -(p * log(p) + (1 - p) * log(1 - p))
matplot(p, cbind(gini_index, classification_error, entropy), pch=c(15,17,19) ,ylab = "Gini Index, Classification Error, Entropy",col = c("green" , "yellow", "red"), type = 'b')
legend('bottom', inset=.01, legend = c('Gini Index', 'Classification Error', 'Entropy'), col = c("green" , "yellow", "red"), pch=c(15,17,19))
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(ISLR2)
library(tree)
attach(Carseats)
(a) Split the data set into a training set and a test set.
set.seed(1)
inTrain <- sample(nrow(Carseats), nrow(Carseats)/2)
carseats_train <- Carseats[inTrain,]
carseats_test <- Carseats[-inTrain,]
(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
tree_carseats <- tree(Sales~., data=carseats_train)
plot(tree_carseats)
text(tree_carseats, pretty = 0)
pred_carseats <- predict(tree_carseats, carseats_test)
mean((carseats_test$Sales - pred_carseats)^2)
## [1] 4.922039
After fitting a regression tree the the training set we obtained a test MSE of 4.922039.
(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
cv_carseats <- cv.tree(tree_carseats, FUN = prune.tree)
plot(cv_carseats$size, cv_carseats$dev, type = 'b')
prune_carseats <- prune.tree(tree_carseats, best=17)
tree_pred <- predict(prune_carseats, carseats_test)
mean((carseats_test$Sales - tree_pred)^2)
## [1] 4.827162
After pruning the tree it lowered the test MSE from 4.922039 to 4.827162.
(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)
set.seed(2)
bag_carseats <- randomForest(Sales ~ ., data = carseats_train, mtry = 10, importance = TRUE)
bag_pred <- predict(bag_carseats, carseats_test)
mean((carseats_test$Sales - bag_pred)^2)
## [1] 2.586535
importance(bag_carseats)
## %IncMSE IncNodePurity
## CompPrice 25.7444826 170.66690
## Income 4.7699543 90.24851
## Advertising 12.3934240 104.10313
## Population -2.0752891 59.47636
## Price 55.2142251 505.28250
## ShelveLoc 47.2885836 376.66846
## Age 17.0744805 156.14233
## Education 2.1151607 45.21764
## Urban -0.9618328 8.82340
## US 5.3624960 18.75708
Using the bagging approach the test MSE decreased to 2.586535 and using the importance() function we determined that the most important variables are ‘Price’ and ‘ShelveLoc’ while ‘CompPrice’ and ‘Age’ are important but less so.
(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(3)
rf_carseats <- randomForest(Sales~., data=carseats_train, mtry = 10, importance = TRUE)
rf_pred <- predict(rf_carseats, carseats_test)
mean((carseats_test$Sales - rf_pred)^2)
## [1] 2.630702
importance(rf_carseats)
## %IncMSE IncNodePurity
## CompPrice 25.6368749 169.596380
## Income 5.5092406 93.989153
## Advertising 13.0320872 99.531672
## Population -1.3427420 56.478915
## Price 52.4411414 498.870909
## ShelveLoc 47.4964524 384.768230
## Age 16.7659587 153.617412
## Education -0.4141856 44.838301
## Urban 0.2914200 9.449681
## US 5.1460185 15.033204
Using random forests to analyze the data, the test MSE increased compared to the bagging approach to 2.630702 and the important variables stay the same.
(f) Now analyze the data using BART, and report your results
library(BART)
set.seed(4)
x <- Carseats[,1:11]
y <- Carseats[,"Sales"]
xtrain <- x[inTrain, ]
ytrain <- y[inTrain]
xtest <- x[-inTrain, ]
ytest <- y[-inTrain]
bart_fit <- gbart(xtrain, ytrain, x.test=xtest)
## *****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: 2s
## trcnt,tecnt: 1000,1000
yhat_bart <- bart_fit$yhat.test.mean
mean((ytest-yhat_bart)^2)
## [1] 0.1990626
Using BART to analyze the data, the test MSE decreased to 0.1990626.
detach(Carseats)
This problem involves the OJ data set which is part of the ISLR2 package.
library(ISLR2)
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)
inTrain <- sample(dim(OJ)[1],800)
OJ_train <- OJ[inTrain,]
OJ_test <- OJ[-inTrain,]
(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?
tree_oj <- tree(Purchase~., data=OJ_train)
summary(tree_oj)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ_train)
## 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
After fitting a tree to the training data with Purchase as the response and the other variables as predictors, we can see that the training error rate is 0.1588 and the tree has 9 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.
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 ) *
Looking at node 13, it has 102 observations with a PriceDiff greater than 0.235 with a deviance of 65.43 and is correct 90.2% of the time.
(d) Create a plot of the tree, and interpret the results.
plot(tree_oj)
text(tree_oj,pretty=0)
It appears that brand loyalty is the most important factor and only when the price difference becomes too large does the customer switch to the cheaper alternative.
(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?
oj_pred <- predict(tree_oj, newdata=OJ_test, type="class")
table(OJ_test$Purchase, oj_pred)
## oj_pred
## CH MM
## CH 160 8
## MM 38 64
mean(oj_pred != OJ_test$Purchase)
## [1] 0.1703704
After comparing the test labels to the predicted test labels, we received a test error rate of 0.1703704.
(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 8 7 4 2 1
##
## $dev
## [1] 150 150 149 158 172 315
##
## $k
## [1] -Inf 0.000000 3.000000 4.333333 10.500000 151.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, type="b", xlab="Tree Size", ylab="CV Classification Error Rate")
(h) Which tree size corresponds to the lowest cross-validated classification error rate?
Based on the tree created in (g), it appears that a tree size of 7 gave 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.
oj_pruned <- prune.misclass(tree_oj, best=7)
plot(oj_pruned)
text(oj_pruned, pretty=0)
(j) Compare the training error rates between the pruned and unpruned trees. Which is higher?
summary(oj_pruned)
##
## Classification tree:
## snip.tree(tree = tree_oj, nodes = c(4L, 10L))
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff" "PctDiscMM"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7748 = 614.4 / 793
## Misclassification error rate: 0.1625 = 130 / 800
The unpruned tree gave a slightly high training error rate of 0.1703704 whereas the pruned tree gave a training error rate of 0.1625.
(k) Compare the test error rates between the pruned and unpruned trees. Which is higher?
ojprune_pred <- predict(oj_pruned, newdata=OJ_test, type="class")
table(ojprune_pred, OJ_test$Purchase)
##
## ojprune_pred CH MM
## CH 160 36
## MM 8 66
mean(ojprune_pred != OJ_test$Purchase)
## [1] 0.162963
The error rate on the unpruned tree is still slightly higher than the pruned tree.
detach(OJ)