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 \(ˆ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, \(ˆpm1=1−ˆpm2\). You could make this plot by hand, but it will be much easier to make inR.

p = seq(0, 1, 0.001)
gini.index = 2 * p * (1 - p)
classification.error = 1 - pmax(p, 1 - p)
cross.entropy = - (p * log(p) + (1 - p) * log(1 - p))
matplot(p, cbind(gini.index, classification.error, cross.entropy), col = c("purple", "blue", "yellow"))

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.

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

library(ISLR)
attach = Carseats
set.seed(100 )
train = sample(1:nrow(Carseats), nrow(Carseats) / 2)
Car.train = Carseats[train, ]
Car.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)
regression.tree = tree(Sales~.,data = Car.train)
summary(regression.tree)
## 
## Regression tree:
## tree(formula = Sales ~ ., data = Car.train)
## Variables actually used in tree construction:
## [1] "ShelveLoc"   "Price"       "Age"         "CompPrice"   "Advertising"
## [6] "Education"  
## Number of terminal nodes:  17 
## Residual mean deviance:  1.844 = 337.5 / 183 
## Distribution of residuals:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -3.81700 -0.89580 -0.01857  0.00000  0.92000  2.91800
plot(regression.tree)
text(regression.tree ,pretty =0)

pred.carseats = predict(regression.tree,newdata = Car.test)
mean((pred.carseats - Car.test$Sales)^2)
## [1] 5.395751

The test MSE is 5.395751

(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?

set.seed(100)
crossval.car = cv.tree(regression.tree)
plot(crossval.car$size, crossval.car$dev, type = "b")

The optimal level of tree complexity is approximately 13.

prune.car = prune.tree(regression.tree, best = 13)
plot(prune.car)
text(prune.car,pretty=0)

pred.carseats2 = predict(prune.car, newdata= Car.test)
mean((pred.carseats2 - Car.test$Sales)^2)
## [1] 5.39241

Prunning the tree decreased the MSE slightly to 5.39241 with an optimal tree complexity of 13.

(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(100)
bag.car = randomForest(Sales~.,data=Car.train,mtry = 10, importance = TRUE)
pred.bag = predict(bag.car,newdata=Car.test)
mean((pred.bag-Car.test$Sales)^2)
## [1] 3.232086
importance(bag.car)
##                 %IncMSE IncNodePurity
## CompPrice   22.03715485    121.684322
## Income      -2.06471346     59.203923
## Advertising 12.04860526     68.661153
## Population  -0.04479465     50.769726
## Price       50.10510920    344.292522
## ShelveLoc   63.21499092    600.988200
## Age         16.88765951    150.242555
## Education    1.95643155     39.643977
## Urban       -0.78701388      4.491141
## US           4.57627564      5.201986
varImpPlot(bag.car)

The MSE is 3.232086. The most important variables are the price and shelving location.

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

library(randomForest)
set.seed(100)
randomforest.car = randomForest(Sales~.,data=Car.train,mtry = 3, importance = TRUE)
pred.rf = predict(randomforest.car,newdata=Car.test)
mean((pred.rf-Car.test$Sales)^2)
## [1] 3.514128

The MSE increased to 3.514128 when using random forests.

Problem 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)
attach = OJ
set.seed(100)
train = sample(dim(OJ)[1],800)
OJ.train = OJ[train,]
OJ.test = OJ[-train,]

(b) Fit a tree to the training data, with `Purchase1 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"     "ListPriceDiff" "SalePriceMM"  
## Number of terminal nodes:  8 
## Residual mean deviance:  0.7235 = 573 / 792 
## Misclassification error rate: 0.1588 = 127 / 800

The training error rate is 0.1588. The tree has 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 1070.00 CH ( 0.61000 0.39000 )  
##    2) LoyalCH < 0.5036 355  420.20 MM ( 0.27887 0.72113 )  
##      4) LoyalCH < 0.280875 167  130.20 MM ( 0.13174 0.86826 )  
##        8) LoyalCH < 0.0356415 59   10.14 MM ( 0.01695 0.98305 ) *
##        9) LoyalCH > 0.0356415 108  106.40 MM ( 0.19444 0.80556 ) *
##      5) LoyalCH > 0.280875 188  254.40 MM ( 0.40957 0.59043 )  
##       10) PriceDiff < 0.05 81   74.58 MM ( 0.17284 0.82716 ) *
##       11) PriceDiff > 0.05 107  144.90 CH ( 0.58879 0.41121 ) *
##    3) LoyalCH > 0.5036 445  336.80 CH ( 0.87416 0.12584 )  
##      6) LoyalCH < 0.764572 180  204.60 CH ( 0.74444 0.25556 )  
##       12) ListPriceDiff < 0.18 49   66.27 MM ( 0.40816 0.59184 ) *
##       13) ListPriceDiff > 0.18 131  101.10 CH ( 0.87023 0.12977 )  
##         26) SalePriceMM < 2.04 51   59.94 CH ( 0.72549 0.27451 ) *
##         27) SalePriceMM > 2.04 80   25.59 CH ( 0.96250 0.03750 ) *
##      7) LoyalCH > 0.764572 265   85.16 CH ( 0.96226 0.03774 ) *

Node 8 is terminal Split criterion = LoyalCH < 0.0356415 number of observations = 59 deviance = 10.14 overall prediction = Less than 2% of the obs take the value of CH; remaining 98% take value MM

(d) Create a plot of the tree, and interpret the results.

plot(OJ.tree)
text(OJ.tree,pretty=TRUE)

The most important indicator of “Purchase” appears to be “LoyalCH”.

(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(OJ.tree, newdata = OJ.test, type = "class")
table(tree.pred,OJ.test$Purchase)
##          
## tree.pred  CH  MM
##        CH 142  36
##        MM  23  69
(142+69)/270
## [1] 0.7814815

78% of the test observation are correctly classified so the test error rate is 22%.

(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.misclass)
cv.OJ
## $size
## [1] 8 6 4 2 1
## 
## $dev
## [1] 137 137 144 161 312
## 
## $k
## [1]  -Inf   0.0   4.5   9.5 157.0
## 
## $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 = "Deviance")

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

The 8 node tree is the smallest with the lowest 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.misclass(OJ.tree, best=8)
plot(prune.OJ)
text(prune.OJ,pretty=0)

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

summary(OJ.tree)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "ListPriceDiff" "SalePriceMM"  
## Number of terminal nodes:  8 
## Residual mean deviance:  0.7235 = 573 / 792 
## Misclassification error rate: 0.1588 = 127 / 800
summary(prune.OJ)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "ListPriceDiff" "SalePriceMM"  
## Number of terminal nodes:  8 
## Residual mean deviance:  0.7235 = 573 / 792 
## Misclassification error rate: 0.1588 = 127 / 800

The missclassification error rate is 0.1588 for both.

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

tree.pred = predict(prune.OJ, newdata = OJ.test, type = "class")
table(tree.pred,OJ.test$Purchase)
##          
## tree.pred  CH  MM
##        CH 142  36
##        MM  23  69
(142+69)/270
## [1] 0.7814815

The pruned and unpruned have the same test error rate of approximately 22%.