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 \(\hat{p}_{m1}\) . The x-axis should
display \(\hat{p}_{m1}\) , 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, \(\hat{p}_{m1} = 1 − \hat{p}_{m2}\) . You
could make this plot by hand, but it will be much easier to make in
R.
library(tidyverse)
library(plotly)
gini<-as_tibble(list(P=seq(0, 1, 0.001))) %>% mutate(Value=P*(1-P)*2, Measure="Gini")
ent<-as_tibble(list(P=seq(0, 1, 0.001))) %>% mutate(Value=-(P*log(P)+(1-P)*log(1-P)), Measure="Entropy")
error=as_tibble(list(P=seq(0, 1, 0.001))) %>% mutate(Value=1-pmax(P,1-P), Measure="Classification Error")
df<-bind_rows(gini, ent, error) %>% arrange(Measure,P)
c<-ggplot(df, aes(x=P,y=Value,col=Measure))+geom_line()+scale_color_manual(values=c("#377eb8","#e41a1c","#4daf4a"))+labs(x="P",y="Value for Split")+theme_minimal()
fig<-ggplotly(c,width=600,height=300)
fig
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(ISLR2)
attach(Carseats)
set.seed(1)
train=sample(dim(Carseats)[1], dim(Carseats)[1]/2)
test=-train
(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
library(tree)
tree.carseats=tree(formula=Sales~.,data=Carseats[train,])
tree.pred=predict(tree.carseats,Carseats[-train,])
plot(tree.carseats)
text(tree.carseats)
mean((tree.pred-Carseats[-train,'Sales'])^2)
## [1] 4.922039
(c) 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)
prune.carseats=prune.tree(tree.carseats,best=10)
plot(prune.carseats)
text(prune.carseats)
tree.pred=predict(prune.carseats,Carseats[-train,])
mean((tree.pred-Carseats[-train,'Sales'])^2)
## [1] 4.918134
This is a very slight improvement to the MSE.
(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(1)
carseats.rf=randomForest(Sales~.,data=Carseats[train,],mtry=10,importance=T,ntree=100)
tree.pred=predict(carseats.rf,Carseats[-train,])
mean((tree.pred-Carseats[-train,'Sales'])^2)
## [1] 2.616711
knitr::kable(importance(carseats.rf))
| %IncMSE | IncNodePurity | |
|---|---|---|
| CompPrice | 11.4033686 | 169.11991 |
| Income | 1.4751526 | 92.34927 |
| Advertising | 5.3836500 | 96.15208 |
| Population | -2.0667575 | 62.75983 |
| Price | 27.2224905 | 492.32337 |
| ShelveLoc | 22.7210914 | 363.27721 |
| Age | 9.1141420 | 154.10317 |
| Education | -0.6365854 | 46.57603 |
| Urban | -0.6581541 | 10.55949 |
| US | 2.1808079 | 16.20339 |
The MSE has improved to 2.616711. Price,
ShelveLoc, and CompPrice are the most
important predictors for Sales.
(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.
carseats.rf=randomForest(Sales~.,data=Carseats[train,],mtry=7,importance=T,ntree=100)
tree.pred=predict(carseats.rf,Carseats[-train,])
mean((tree.pred-Carseats[-train,'Sales'])^2)
## [1] 2.637936
In this case, random forests did not result in an improvement over bagging. The same variables are still the most important predictors.
(f) Now analyze the data using BART, and report your results.
library(BART)
x=Carseats[,2:11]
y=Carseats[,"Sales"]
xtrain=x[train,]
ytrain=y[train]
xtest=x[test,]
ytest=y[test]
set.seed(1)
bartfit=gbart(xtrain,ytrain,x.test=xtest)
## *****Calling gbart: type=1
## *****Data:
## data:n,p,np: 200, 14, 200
## y1,yn: 2.781850, 1.091850
## x1,x[n*p]: 107.000000, 1.000000
## xp1,xp[np*p]: 111.000000, 1.000000
## *****Number of Trees: 200
## *****Number of Cut Points: 63 ... 1
## *****burn,nd,thin: 100,1000,1
## *****Prior:beta,alpha,tau,nu,lambda,offset: 2,0.95,0.273474,3,0.23074,7.57815
## *****sigma: 1.088371
## *****w (weights): 1.000000 ... 1.000000
## *****Dirichlet:sparse,theta,omega,a,b,rho,augment: 0,0,1,0.5,1,14,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=bartfit$yhat.test.mean
mean((ytest-yhat.bart)^2)
## [1] 1.450842
detach(Carseats)
This problem involves the OJ data set which is
part of the ISLR2 package.
(a) Create a training set containing a random sample of 800
observations, and a test set containing the remaining
observations.
attach(OJ)
set.seed(1)
train=sample(nrow(OJ),800)
test=-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" "SpecialCH" "ListPriceDiff"
## [5] "PctDiscMM"
## Number of terminal nodes: 9
## Residual mean deviance: 0.7432 = 587.8 / 791
## Misclassification error rate: 0.1588 = 127 / 800
The tree uses 5 variables and has 9 terminal nodes. We have a training error rate of 0.1588.
(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 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 ) *
For terminal node 8) the splitting variable is LoyalCH. The splitting
value is 0.0356415. There are 59 points in the subtree below this node.
The deviance for all points in this region is 10.14. The prediction at
this node is Sales = MM.
(d) Create a plot of the tree, and interpret the results.
plot(OJ.tree)
text(OJ.tree)
(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?
library(caret)
OJ.pred=predict(OJ.tree,OJ[test,],type='class')
confusionMatrix(OJ[test,'Purchase'],OJ.pred)
## Confusion Matrix and Statistics
##
## Reference
## Prediction CH MM
## CH 160 8
## MM 38 64
##
## Accuracy : 0.8296
## 95% CI : (0.7794, 0.8725)
## No Information Rate : 0.7333
## P-Value [Acc > NIR] : 0.0001259
##
## Kappa : 0.6154
##
## Mcnemar's Test P-Value : 1.904e-05
##
## Sensitivity : 0.8081
## Specificity : 0.8889
## Pos Pred Value : 0.9524
## Neg Pred Value : 0.6275
## Prevalence : 0.7333
## Detection Rate : 0.5926
## Detection Prevalence : 0.6222
## Balanced Accuracy : 0.8485
##
## 'Positive' Class : CH
##
(f) Apply the cv.tree() function to the training
set in order to determine the optimal tree size.
OJ.tree.cv=cv.tree(OJ.tree,FUN=prune.tree)
(g) Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.
plot(OJ.tree.cv)
(h) Which tree size corresponds to the lowest cross-validated classification error rate?
Size 8 produces the lowest cross-validation error.
(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.tree.prune=prune.tree(OJ.tree,best=8)
(j) Compare the training error rates between the pruned and unpruned trees. Which is higher?
summary(OJ.tree.prune)
##
## Classification tree:
## snip.tree(tree = OJ.tree, nodes = 10L)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff" "PctDiscMM"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7582 = 600.5 / 792
## Misclassification error rate: 0.1625 = 130 / 800
(k) Compare the test error rates between the pruned and unpruned trees. Which is higher?
unp.err= sum(OJ[test,'Purchase'] != OJ.pred)
unp.err/length(OJ.pred)
## [1] 0.1703704
OJ.pred.prune=predict(OJ.tree.prune,OJ[test,],type='class')
p.err= sum(OJ[test,'Purchase'] != OJ.pred.prune)
p.err/length(OJ.pred.prune)
## [1] 0.162963
The unpruned tree has a higher test error rate.