Homework 7

Problem 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 xaxis 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 = p * (1 - p) * 2
entropy = -(p * log(p) + (1 - p) * log(1 - p))
class.err = 1 - pmax(p, 1 - p)
matplot(p, cbind(gini, entropy, class.err), col = c("pink", "red", "purple"))

Problem 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.

Part A

Split the data set into a training set and a test set.

library(ISLR)
attach(Carseats)
set.seed(1)

train = sample(dim(Carseats)[1], dim(Carseats)[1]/2)
Carseats.train = Carseats[train, ]
Carseats.test = Carseats[-train, ]

Part 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 3.5.3
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"       "Age"         "Advertising" "Income"     
## [6] "CompPrice"  
## Number of terminal nodes:  18 
## Residual mean deviance:  2.36 = 429.5 / 182 
## Distribution of residuals:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -4.2570 -1.0360  0.1024  0.0000  0.9301  3.9130
plot(tree.carseats)
text(tree.carseats, pretty = 0)

pred.carseats = predict(tree.carseats, Carseats.test)
mean((Carseats.test$Sales - pred.carseats)^2)
## [1] 4.148897

We do find the MSE is roughly 4.15.

Part 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)
par(mfrow = c(1, 2))
plot(cv.carseats$size, cv.carseats$dev, type = "b")
plot(cv.carseats$k, cv.carseats$dev, type = "b")

# Best size = 9
pruned.carseats = prune.tree(tree.carseats, best = 9)
par(mfrow = c(1, 1))
plot(pruned.carseats)
text(pruned.carseats, pretty = 0)

pred.pruned = predict(pruned.carseats, Carseats.test)
mean((Carseats.test$Sales - pred.pruned)^2)
## [1] 4.993124

Our MSE is now to be seen to be increased to 4.99.

Part 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 3.5.3
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
bag.carseats = randomForest(Sales ~ ., data = Carseats.train, mtry = 10, ntree = 500, 
    importance = T)
bag.pred = predict(bag.carseats, Carseats.test)
mean((Carseats.test$Sales - bag.pred)^2)
## [1] 2.633915
importance(bag.carseats)
##                %IncMSE IncNodePurity
## CompPrice   16.9874366    126.852848
## Income       3.8985402     78.314126
## Advertising 16.5698586    123.702901
## Population   0.6487058     62.328851
## Price       55.3976775    514.654890
## ShelveLoc   42.7849818    319.133777
## Age         20.5135255    185.582077
## Education    3.4615211     42.253410
## Urban       -2.5125087      8.700009
## US           7.3586645     18.180651

Bagging improves the MSE we obtained to 2.58. We also see, using importance() that Price, Age and ShelveLoc are the three most important variables for Sale.

Part 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 = 5, ntree = 500, 
    importance = T)
rf.pred = predict(rf.carseats, Carseats.test)
mean((Carseats.test$Sales - rf.pred)^2)
## [1] 2.816693
importance(rf.carseats)
##               %IncMSE IncNodePurity
## CompPrice   11.304167     126.68519
## Income       5.423214     102.44073
## Advertising 13.351166     137.98835
## Population   1.131119      82.24483
## Price       46.600559     451.70021
## ShelveLoc   37.352447     278.79756
## Age         19.992113     194.99430
## Education    1.945616      51.70741
## Urban       -2.244558      10.87383
## US           6.261365      20.83998

Random Forest actually worsens the MSE to 2.87. Changing m varies test MSE between 2.6 to 3. Once again though Price, ShelveLoc and Age are three most important predictors of Sale.

Problem 9

This problem involves the OJ data set which is part of the ISLR package.

Part A

Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.

library(ISLR)
attach(OJ)
set.seed(1013)

train = sample(dim(OJ)[1], 800)
OJ.train = OJ[train, ]
OJ.test = OJ[-train, ]

Part 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?

library(tree)
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"
## Number of terminal nodes:  7 
## Residual mean deviance:  0.7517 = 596.1 / 793 
## Misclassification error rate: 0.155 = 124 / 800

The tree only uses two variables: LoyalCH and PriceDiff. It has 7 terminal nodes. Training error rate (misclassification error) for the tree is 0.155.

Part 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 1075.00 CH ( 0.60250 0.39750 )  
##    2) LoyalCH < 0.5036 359  422.80 MM ( 0.27577 0.72423 )  
##      4) LoyalCH < 0.276142 170  119.10 MM ( 0.11176 0.88824 ) *
##      5) LoyalCH > 0.276142 189  257.50 MM ( 0.42328 0.57672 )  
##       10) PriceDiff < 0.05 79   76.79 MM ( 0.18987 0.81013 ) *
##       11) PriceDiff > 0.05 110  148.80 CH ( 0.59091 0.40909 ) *
##    3) LoyalCH > 0.5036 441  343.30 CH ( 0.86848 0.13152 )  
##      6) LoyalCH < 0.764572 186  210.30 CH ( 0.74731 0.25269 )  
##       12) PriceDiff < -0.165 29   34.16 MM ( 0.27586 0.72414 ) *
##       13) PriceDiff > -0.165 157  140.90 CH ( 0.83439 0.16561 )  
##         26) PriceDiff < 0.265 82   95.37 CH ( 0.73171 0.26829 ) *
##         27) PriceDiff > 0.265 75   31.23 CH ( 0.94667 0.05333 ) *
##      7) LoyalCH > 0.764572 255   90.67 CH ( 0.95686 0.04314 ) *

Let’s pick terminal node labeled “10)”. The splitting variable at this node is PriceDiff. The splitting value of this node is 0.05. There are 79 points in the subtree below this node. The deviance for all points contained in region below this node is 80. A * in the line denotes that this is in fact a terminal node. The prediction at this node is Sales = MM. About 19% points in this node have CH as value of Sales. Remaining 81% points have MM as value of Sales.

Part D

Create a plot of the tree, and interpret the results

plot(oj.tree)
text(oj.tree, pretty = 0)

LoyalCH is the most important variable of the tree, in fact top 3 nodes contain LoyalCH. If LoyalCH<0.27, the tree predicts MM. If LoyalCH>0.76, the tree predicts CH. For intermediate values of LoyalCH, the decision also depends on the value of PriceDiff.

Part 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(oj.tree, OJ.test, type = "class")
table(OJ.test$Purchase, oj.pred)
##     oj.pred
##       CH  MM
##   CH 152  19
##   MM  32  67

Part F

Apply the cv.tree() function to the training set in order to determine the optimal tree size.

cv.oj = cv.tree(oj.tree, FUN = prune.tree)

Part 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 = "Deviance")

Part H

Which tree size corresponds to the lowest cross-validated classification error rate?

Size of 6 gives lowest cross-validation error.

Part 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.tree(oj.tree, best = 6)

Part J

Compare the training error rates between the pruned and unpruned trees. Which is higher?

summary(oj.pruned)
## 
## Classification tree:
## snip.tree(tree = oj.tree, nodes = 13L)
## Variables actually used in tree construction:
## [1] "LoyalCH"   "PriceDiff"
## Number of terminal nodes:  6 
## Residual mean deviance:  0.7689 = 610.5 / 794 
## Misclassification error rate: 0.155 = 124 / 800

Misclassification error of pruned tree is exactly same as that of original tree - 0.155.

Part K

Compare the test error rates between the pruned and unpruned trees. Which is higher?

pred.unpruned = predict(oj.tree, OJ.test, type = "class")
misclass.unpruned = sum(OJ.test$Purchase != pred.unpruned)
misclass.unpruned/length(pred.unpruned)
## [1] 0.1888889
pred.pruned = predict(oj.pruned, OJ.test, type = "class")
misclass.pruned = sum(OJ.test$Purchase != pred.pruned)
misclass.pruned/length(pred.pruned)
## [1] 0.1888889

Pruned and unpruned trees have same test error rate of 0.189.