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.
p = seq(0, 1, 0.01)
gini = p * (1-p) * 2
entropy = -(p * log(p) + (1 - p) * log(1-p))
err.class = 1 - pmax(p, 1 - p)
matplot(p, cbind(gini, entropy, err.class), col = c("blue", "green", "black"))
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(1)
subset = sample(nrow(Carseats), nrow(Carseats)*0.7)
car.train = Carseats[subset, ]
car.test = Carseats[-subset, ]
(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.0.4
car.model.train = tree(Sales ~ ., car.train)
summary(car.model.train)
##
## Regression tree:
## tree(formula = Sales ~ ., data = car.train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "Age" "Income" "CompPrice"
## [6] "Advertising"
## Number of terminal nodes: 18
## Residual mean deviance: 2.409 = 631.1 / 262
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -4.77800 -0.96100 -0.08865 0.00000 1.01800 4.14100
plot(car.model.train)
text(car.model.train, pretty = 0 )
tree.prediction<-predict(car.model.train,newdata=car.test)
tree.mse<-mean((car.test$Sales-tree.prediction)^2)
tree.mse
## [1] 4.208383
The test MSE is just about 4.2.
(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
set.seed(1)
cv.car<-cv.tree(car.model.train)
plot(cv.car$size,cv.car$dev,xlab = "Size of Tree",ylab = "Deviance",type = "b")
prune.car = prune.tree(car.model.train, best=6)
plot(prune.car)
text(prune.car, pretty=0)
prune.predict = predict(prune.car, car.test)
mean((prune.predict-car.test$Sales)^2)
## [1] 5.118217
Using cross validation we determine that the best size for the tree to be pruned to was 8, and for this pruned tree we get an MSE of 5.11 compared to the original 4.2.
(d) Use the bagging approach in order to analyze this data. What test MSE do you obtain? Use importance() function to determine which variables are most important.
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.0.5
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
bag.car<-randomForest(Sales~.,car.train,importance=TRUE,mtry=13)
## Warning in randomForest.default(m, y, ...): invalid mtry: reset to within valid
## range
importance(bag.car)
## %IncMSE IncNodePurity
## CompPrice 34.6322504 233.60705
## Income 5.3645204 116.93827
## Advertising 18.8175105 153.05938
## Population -3.0858810 64.26621
## Price 70.9386948 698.15948
## ShelveLoc 74.2328945 645.49148
## Age 20.8561302 224.71954
## Education 1.3723565 61.47839
## Urban -1.9986734 10.51832
## US 0.8095402 10.19895
bag.car.predict<-predict(bag.car,car.test)
mean((bag.car.predict-car.test$Sales)^2)
## [1] 2.571169
The test set MSE is 2.57, which means that bagging has helped in reducing the MSE. CompPrice and Income appear to be the most important variables as chosen by the bagging model.
(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.car<-randomForest(Sales~.,car.train,importance=TRUE,mtry=sqrt(13))
importance(rf.car)
## %IncMSE IncNodePurity
## CompPrice 20.7300392 213.78497
## Income 3.5122804 148.32279
## Advertising 15.6121947 159.16307
## Population 0.5759461 113.69354
## Price 51.9015680 594.84872
## ShelveLoc 51.4866473 539.23503
## Age 18.6833946 261.97525
## Education 3.0894573 88.05427
## Urban -2.4726183 17.29229
## US 4.0933782 27.11808
rf.car.predict<-predict(rf.car,car.test)
mean((rf.car.predict-car.test$Sales)^2)
## [1] 2.674922
Using RF increased the MSE compared to the bagging model. The important variables are the same as the previous model. Further pruning is needed in order to perform better than bagging.
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(1013)
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?
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" "ListPriceDiff" "SalePriceMM"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7564 = 599.8 / 793
## Misclassification error rate: 0.1612 = 129 / 800
The tree uses 4 variables, LoyalCH, PriceDiff, ListPriceDiff, and SalePriceMM. It has 7 terminal nodes, and the training error rate for this tree is .1612
(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 1069.00 CH ( 0.61125 0.38875 )
## 2) LoyalCH < 0.5036 344 407.30 MM ( 0.27907 0.72093 )
## 4) LoyalCH < 0.276142 163 121.40 MM ( 0.12270 0.87730 ) *
## 5) LoyalCH > 0.276142 181 246.30 MM ( 0.41989 0.58011 )
## 10) PriceDiff < 0.065 75 75.06 MM ( 0.20000 0.80000 ) *
## 11) PriceDiff > 0.065 106 144.50 CH ( 0.57547 0.42453 ) *
## 3) LoyalCH > 0.5036 456 366.30 CH ( 0.86184 0.13816 )
## 6) LoyalCH < 0.753545 189 224.30 CH ( 0.71958 0.28042 )
## 12) ListPriceDiff < 0.235 79 109.40 MM ( 0.48101 0.51899 )
## 24) SalePriceMM < 1.64 22 20.86 MM ( 0.18182 0.81818 ) *
## 25) SalePriceMM > 1.64 57 76.88 CH ( 0.59649 0.40351 ) *
## 13) ListPriceDiff > 0.235 110 75.81 CH ( 0.89091 0.10909 ) *
## 7) LoyalCH > 0.753545 267 85.31 CH ( 0.96255 0.03745 ) *
Looking at terminal node 10, the variable is PriceDiff. The splitting value for the node is .065. There are 75 points in the subtree below the node. The deviance for all points contianed in region below this nod3 is 75.06. The prediction at this node is Sales = MM and about 20% of the points in the node have CH as value of sales and the rest have MM as value of sales.
(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. Top 3 nodes include LoyalCH. If LoyalCH is less than .27 the tree predicts MM and if LoyalCH is greater than .75 the tree predicts CH. For intermediate values of LoyalCH, the tree predicts PriceDiff, however ListPriceDiff also has a hand in making a decision.
(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 149 15
## MM 30 76
The test error rate is 16.67%
(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)
(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?
Size of 6 gives 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.tree(oj.tree, best = 6)
(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 = 12L)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff"
## Number of terminal nodes: 6
## Residual mean deviance: 0.7701 = 611.5 / 794
## Misclassification error rate: 0.175 = 140 / 800
The missclassification error rate is slightly higher than the unpruned tree. The pruned tree training error rate is higher.
(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.1666667
pred.pruned = predict(oj.pruned, OJ.test, type = "class")
misclass.pruned = sum(OJ.test$Purchase != pred.pruned)
misclass.pruned/length(pred.pruned)
## [1] 0.2
The test error rate is higher for the pruned tree than the unpruned tree.