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 \(\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.
p = seq(0, 1, 0.01)
gini.index = p * (1 - p) * 2
entropy = -(p * log(p) + (1 - p) * log(1 - p))
class.err = 1 - pmax(p, 1 - p)
matplot(p, cbind(gini.index, class.err, entropy), col = c("green", "purple", "blue"), pch=16, ylab = "gini.index, class.error, entropy")
legend('bottom', legend = c('gini.index', 'class.error', 'entropy'), col = c("green", "purple", "blue"), pch=c(16))

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)
## Warning: package 'ISLR' was built under R version 4.1.2
attach(Carseats)
(a) Split the data set into a training set and a test set.
set.seed(123)
train = sample(dim(Carseats)[1], dim(Carseats)[1]/2)
Carseats.train = Carseats[train, ]
Carseats.test = Carseats[-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)
## Warning: package 'tree' was built under R version 4.1.3
## Registered S3 method overwritten by 'tree':
## method from
## print.tree cli
tree.carseats = tree(Sales ~ ., data=Carseats.train)
summary(tree.carseats)
##
## Regression tree:
## tree(formula = Sales ~ ., data = Carseats.train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "Income" "Age" "Population"
## [6] "Education" "CompPrice" "Advertising"
## Number of terminal nodes: 18
## Residual mean deviance: 2.132 = 388.1 / 182
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -4.08000 -0.92870 0.06244 0.00000 0.87020 3.71700
plot(tree.carseats)
text(tree.carseats, pretty = 0)

pred.carseats = predict(tree.carseats, Carseats.test)
mse=mean((Carseats.test$Sales - pred.carseats)^2)
mse
## [1] 4.395357
(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)
plot(cv.carseats$size, cv.carseats$dev, type = "b")

prune.carseats=prune.tree(tree.carseats, best=7)
plot(prune.carseats)
text(prune.carseats, pretty=0)

pred.pruned=predict(prune.carseats, Carseats.test)
mean((Carseats.test$Sales - pred.pruned)^2)
## [1] 4.696596
The MSE is slightly higher after pruning.
(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.
bag.carseats=randomForest(Sales~., data=Carseats.train, mtry=10, importance=T)
bag.pred=predict(bag.carseats, Carseats.test)
bag.mse=mean((Carseats.test$Sales - bag.pred)^2)
bag.mse
## [1] 2.706945
importance(bag.carseats)
## %IncMSE IncNodePurity
## CompPrice 20.45893952 163.315084
## Income 5.99352172 88.626184
## Advertising 6.70900949 73.007073
## Population -1.84004720 53.079505
## Price 46.01586429 395.251820
## ShelveLoc 49.31816789 391.948958
## Age 17.74691675 171.659574
## Education 2.98753578 57.308595
## Urban 0.04864498 7.721022
## US 0.05207339 6.011265
The most important variables are ShelveLoc, Price, CompPrice, and
Age.
(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.
rf.carseats=randomForest(Sales~., data=Carseats.train, mtry=sqrt(10), importance=T)
rf.pred=predict(rf.carseats, Carseats.test)
rf.mse=mean((Carseats.test$Sales - rf.pred)^2)
rf.mse
## [1] 3.575026
importance(rf.carseats)
## %IncMSE IncNodePurity
## CompPrice 11.2053520 151.60036
## Income 4.3779492 117.99648
## Advertising 6.1512828 96.48365
## Population -0.2036319 104.22389
## Price 29.8215710 297.83618
## ShelveLoc 34.5359445 279.70714
## Age 18.8567285 208.55522
## Education 1.5141906 72.05700
## Urban -1.2098009 15.28180
## US 2.7549016 15.43075
rf.carseats
##
## Call:
## randomForest(formula = Sales ~ ., data = Carseats.train, mtry = sqrt(10), importance = T)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 3
##
## Mean of squared residuals: 3.315215
## % Var explained: 53.93
The number of variables considered at each split was 3 and the MSE is
higher than that found with bagging, but still better than the MSEs
found in (b) and (c).
detach(Carseats)
9. This problem involves the OJ data set which is part of the ISLR
package.
attach(OJ)
(a) Create a training set containing a random sample of 800
observations, and a test set containing the remaining observations.
set.seed(123)
train = sample(dim(OJ)[1], 800)
OJ.train = OJ[train, ]
OJ.test = OJ[-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?
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"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7625 = 603.9 / 792
## Misclassification error rate: 0.165 = 132 / 800
The tree has 8 terminal nodes and the two variables used are LoyalCh
and PriceDiff. The training error rate is 0.165.
(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 1071.00 CH ( 0.60875 0.39125 )
## 2) LoyalCH < 0.5036 350 415.10 MM ( 0.28000 0.72000 )
## 4) LoyalCH < 0.276142 170 131.00 MM ( 0.12941 0.87059 )
## 8) LoyalCH < 0.0356415 56 10.03 MM ( 0.01786 0.98214 ) *
## 9) LoyalCH > 0.0356415 114 108.90 MM ( 0.18421 0.81579 ) *
## 5) LoyalCH > 0.276142 180 245.20 MM ( 0.42222 0.57778 )
## 10) PriceDiff < 0.05 74 74.61 MM ( 0.20270 0.79730 ) *
## 11) PriceDiff > 0.05 106 144.50 CH ( 0.57547 0.42453 ) *
## 3) LoyalCH > 0.5036 450 357.10 CH ( 0.86444 0.13556 )
## 6) PriceDiff < -0.39 27 32.82 MM ( 0.29630 0.70370 ) *
## 7) PriceDiff > -0.39 423 273.70 CH ( 0.90071 0.09929 )
## 14) LoyalCH < 0.705326 130 135.50 CH ( 0.78462 0.21538 )
## 28) PriceDiff < 0.145 43 58.47 CH ( 0.58140 0.41860 ) *
## 29) PriceDiff > 0.145 87 62.07 CH ( 0.88506 0.11494 ) *
## 15) LoyalCH > 0.705326 293 112.50 CH ( 0.95222 0.04778 ) *
Terminal node 29 shows PriceDiff > 0.145 as the split criterion,
there are 87 observations in that branch, the deviance equals 62.07, and
the overall prediction in that branch is CH. 89% of the values in the
branch are CH and 11% are MM.
(d) Create a plot of the tree, and interpret the results.
plot(tree.oj)
text(tree.oj, pretty=0)

If LoyalCH is less than 0.504, then MM is the more likely result. If
LoyalCH is greater than 0.504, CH is the more likely result.
(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(tree.oj, newdata=OJ.test, type="class")
table(tree.pred,OJ.test$Purchase)
##
## tree.pred CH MM
## CH 150 34
## MM 16 70
Error rate: 16+34/270 = 0.185
(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.tree)
(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 Error")

(h) Which tree size corresponds to the lowest cross-validated
classification error rate?
According to (g), 6 is the lowest tree size.
(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(tree.oj, best=6)
plot(prune.oj)
text(prune.oj, pretty=0)

(j) Compare the training error rates between the pruned and unpruned
trees. Which is higher?
summary(tree.oj)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7625 = 603.9 / 792
## Misclassification error rate: 0.165 = 132 / 800
summary(prune.oj)
##
## Classification tree:
## snip.tree(tree = tree.oj, nodes = c(4L, 14L))
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 6
## Residual mean deviance: 0.7945 = 630.9 / 794
## Misclassification error rate: 0.165 = 132 / 800
They are the same.
(k) Compare the test error rates between the pruned and unpruned
trees. Which is higher?
prune.pred = predict(prune.oj, OJ.test, type = "class")
table(prune.pred, OJ.test$Purchase)
##
## prune.pred CH MM
## CH 150 34
## MM 16 70
Error rate: 16+34/270 = 0.185. They are the same.