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 xaxis 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.index=2 * p * (1 - p)
class.error=1 - pmax(p, 1 - p)
cross.entropy=- (p * log(p) + (1 - p) * log(1 - p))
par(bg = "white")
matplot(p, cbind(gini.index, class.error, cross.entropy), pch=c(15,17,19) ,ylab = "gini.index, class.error, cross.entropy",col = c("green" , "yellow", "red"), type = 'b')
legend('bottom', inset=.01, legend = c('gini.index', 'class.error', 'cross.entropy'), col = c("green" , "yellow", "red"), pch=c(15,17,19))
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)
library(tree)
## Warning: package 'tree' was built under R version 4.1.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.1.3
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
set.seed(1)
attach(Carseats)
c=Carseats
train_sample=sample(1:nrow(c), nrow(c)/2)
train=c[train_sample,]
test=c[-train_sample,]
(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
tree.c=tree(Sales~., data=train)
plot(tree.c)
text(tree.c, pretty = 0)
yhat.tree=predict(tree.c, test)
obs.sales<-test$Sales
mean((yhat.tree-obs.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?
cv.c=cv.tree(tree.c)
cv.c
## $size
## [1] 18 17 16 15 14 13 12 11 10 8 7 6 5 4 3 2 1
##
## $dev
## [1] 831.3437 852.3639 868.6815 862.3400 862.3400 893.4641 911.2580
## [8] 950.2691 955.2535 1039.1241 1066.6899 1125.0894 1205.5806 1273.2889
## [15] 1302.8607 1349.9273 1620.4687
##
## $k
## [1] -Inf 16.99544 20.56322 25.01730 25.57104 28.01938 30.36962
## [8] 31.56747 31.80816 40.75445 44.44673 52.57126 76.21881 99.59459
## [15] 116.69889 159.79501 337.60153
##
## $method
## [1] "deviance"
##
## attr(,"class")
## [1] "prune" "tree.sequence"
plot(cv.c$size,cv.c$dev, xlab = 'size', ylab = 'cv error ')
abline(h = min(cv.c$dev) + .2*sd(cv.c$dev))
prune.c=list()
yhat.prune=list()
mse.prune=list()
for (i in 2:16) {
prune.c[[i]]=prune.tree(tree.c, best=i)
yhat.prune[[i]]=predict(prune.c[[i]], test)
obs.sales<-test$Sales
mse.prune[[i]]=mean((yhat.prune[[i]]-obs.sales)^2)}
mse.mat=as.matrix(mse.prune)
mse.df=as.data.frame(mse.mat)
matplot(2:16, mse.df[-1,1], xlab = 'size', ylab = 'MSE', main = "What size tree \n gives the lowest MSE?")
lines(2:16, mse.df[-1,1], type = "b")
mse.df=data.frame(size=2:16,lapply(mse.df, unlist))
mse.df$mse.rank<-rank(mse.df$V1)
names(mse.df)[2]='mse'
mse.df[mse.df$mse.rank %in% 1:3,]
## size mse mse.rank
## 6 7 4.861001 2
## 10 11 4.757881 1
## 15 16 4.903443 3
(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.
##
## Attaching package: 'randomForest'
## The following object is masked from 'package:dplyr':
##
## combine
set.seed(1)
bag.car=randomForest(Sales ~ ., data = train, mtry = 10, importance = TRUE)
bag.car
##
## Call:
## randomForest(formula = Sales ~ ., data = train, mtry = 10, importance = TRUE)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 10
##
## Mean of squared residuals: 2.889221
## % Var explained: 63.26
bag.predict=predict(bag.car, newdata = test)
mean((bag.predict - test$Sales)^2)
## [1] 2.605253
importance(bag.car)
## %IncMSE IncNodePurity
## CompPrice 24.8888481 170.182937
## Income 4.7121131 91.264880
## Advertising 12.7692401 97.164338
## Population -1.8074075 58.244596
## Price 56.3326252 502.903407
## ShelveLoc 48.8886689 380.032715
## Age 17.7275460 157.846774
## Education 0.5962186 44.598731
## Urban 0.1728373 9.822082
## US 4.2172102 18.073863
We see from the table that Price, Shelveloc, and CompPrice appear to be the most important.
(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.
set.seed(1)
rf.car=randomForest(Sales ~ ., data = train, mtry =5, importance = TRUE)
bag.car
##
## Call:
## randomForest(formula = Sales ~ ., data = train, mtry = 10, importance = TRUE)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 10
##
## Mean of squared residuals: 2.889221
## % Var explained: 63.26
rf.predict=predict(rf.car, newdata = test)
mean((rf.predict - test$Sales)^2)
## [1] 2.714168
importance(rf.car)
## %IncMSE IncNodePurity
## CompPrice 17.4126238 157.53631
## Income 2.9969399 110.40731
## Advertising 11.0485672 105.75049
## Population -1.5321044 80.73318
## Price 43.3572135 452.02367
## ShelveLoc 44.4474163 331.64508
## Age 14.5322339 176.64252
## Education 0.8237454 55.91141
## Urban -2.7805788 11.07321
## US 3.7773881 23.75322
In this instance, we obtained a better MSE, and once again the most important variables in prediction are the Price and Shelveloc variables.
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.
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?
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
Here the tree only has two variables: LoyalCH and PriceDiff. It has 7 terminal nodes, and a training error rate of 0.155.
(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 ) *
Node 5 has a split of 0.276142, and has 189 observations. For the prediction about 42% of points in this node have CH as a value, the remaining 58% have MM as 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, 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.
(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
(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?
Tree size of 6 appears to have the lowest CV 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
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
We can see from the table that the misclasification rate for the pruned oj 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
We see that the pruned has a higher error rate.