Tree-based methods for regression and classification involve stratifying or segmenting the predictor space into a number of simple regions. In order to make a prediction for a given observation, we typically use the mean or the mode of the training observations in the region to which it belongs. In this exercise we compare the criterion for splitting, fit a tree, bagged tree, and random forest to the Carseats
data, and fit a tree to the OJ
data.
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
.
#LOAD HELPFUL LIBRARIES
library(tidyverse)
library(plotly)
#BUILD GINI INDEX DATA
gini<-as_tibble(list(P=seq(0, 1, 0.001))) %>%
mutate(Value=P * (1 - P) * 2,
Measure="Gini")
#BUILD ENTROPY DATA
ent<-as_tibble(list(P=seq(0, 1, 0.001))) %>%
mutate(Value=-(P * log(P) + (1 - P) * log(1 - P)),
Measure="Entropy")
#BUILD CLASSIFICATION ERROR DATA
error=as_tibble(list(P=seq(0, 1, 0.001))) %>%
mutate(Value=1 - pmax(P, 1 - P),
Measure="Classification Error")
#PUT GINI, ENTROPY, AND ERROR DATA TOGETHER
df<-bind_rows(gini, ent, error) %>%
arrange(Measure, P)
#PLOT IT
c<-ggplot(df, aes(x=P,y=Value,col=Measure)) +
geom_line()+
scale_color_manual(values=c("#377eb8","#e41a1c","#4daf4a"))+
labs(
x = "P",
y = "Value for Split",
title = "Max value for each criterion occurs at P=0.50"
) +
theme_minimal()
#CREATE INTERACTIVE GRAPHIC
fig<-ggplotly(c,width=600,height=300)
fig
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)
inTrain = sample(nrow(Carseats), nrow(Carseats)/2)
cs_train = Carseats[inTrain, ]
cs_test = Carseats[-inTrain, ]
(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
library(tree)
package 㤼㸱tree㤼㸲 was built under R version 3.6.3Registered S3 method overwritten by 'tree':
method from
print.tree cli
car_tree = tree(Sales ~ ., data = cs_train)
summary(car_tree)
Regression tree:
tree(formula = Sales ~ ., data = cs_train)
Variables actually used in tree construction:
[1] "ShelveLoc" "Price" "Age" "Advertising" "CompPrice" "US"
Number of terminal nodes: 18
Residual mean deviance: 2.167 = 394.3 / 182
Distribution of residuals:
Min. 1st Qu. Median Mean 3rd Qu. Max.
-3.88200 -0.88200 -0.08712 0.00000 0.89590 4.09900
dev.new(width=5, height=24, unit="in")
plot(car_tree)
text(car_tree, pretty = 0, cex=.55)
car_pred = predict(car_tree, cs_test)
(car_mse<-mean((cs_test$Sales - car_pred)^2))
[1] 4.922039
The test MSE is about 4.9220391
(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
cv_car = cv.tree(car_tree, FUN = prune.tree)
dev.new(width=5, height=4, unit="in")
par(mfrow = c(1, 2))
plot(cv_car$size, cv_car$dev, type = "b")
plot(cv_car$k, cv_car$dev, type = "b")
# Best size = 9
car_prune = prune.tree(car_tree, best = 9)
dev.new(width=5, height=24, unit="in")
par(mfrow = c(1, 1))
plot(car_prune)
text(car_prune, pretty = 0, cex=.55)
prune_pred = predict(car_prune, cs_test)
(prune_mse=mean((cs_test$Sales - prune_pred)^2))
[1] 4.918134
Pruning the tree decreases the test MSE to 4.9181344.
(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)
car_bag = randomForest(Sales ~ ., data = cs_train, mtry = 10, ntree = 500, importance = T)
pred_bag = predict(car_bag, cs_test)
(bag_mse=mean((cs_test$Sales - pred_bag)^2))
[1] 2.657296
(imp<-as_tibble(importance(car_bag)) %>%
mutate(variable=row.names(importance(car_bag)),
per_inc_mse=`%IncMSE`,
inc_node_purity=IncNodePurity) %>%
select(variable,per_inc_mse,inc_node_purity) %>%
arrange(desc(per_inc_mse)))
Bagging improves the test MSE to 2.6572962. We also see that Price
, ShelveLoc
and CompPrice
are three most important predictors of Sale
.
(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.
car_rf = randomForest(Sales ~ ., data = cs_train, mtry = 7, ntree = 500,
importance = T)
pred_rf = predict(car_rf, cs_test)
(rf_mse=mean((cs_test$Sales - pred_rf)^2))
[1] 2.624779
(imp<-as_tibble(importance(car_rf)) %>%
mutate(variable=row.names(importance(car_rf)),
per_inc_mse=`%IncMSE`,
inc_node_purity=IncNodePurity) %>%
select(variable,per_inc_mse,inc_node_purity) %>%
arrange(desc(per_inc_mse)))
In this case, random forest outperforms the MSE on test set by 0.0325175. Changing m varies test MSE between 2.6 to 3. We again see that Price
, ShelveLoc
and CompPrice
are three most important predictors of Sale
.
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)
inTrain = sample(nrow(OJ), 800)
train_oj = OJ[inTrain, ]
test_oj = OJ[-inTrain, ]
(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)
tree_oj = tree(Purchase ~ ., data = train_oj)
summary(tree_oj)
Classification tree:
tree(formula = Purchase ~ ., data = train_oj)
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 only uses four variables: LoyalCH
, PriceDiff
, ListPriceDiff
, and SalePriceMM
. It has 7 terminal nodes. Training error rate (misclassification error) for the tree is 0.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.
tree_oj
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 ) *
Let’s pick terminal node labeled “10)”. The splitting variable at this node is PriceDiff
. The splitting value of this node is 0.065. There are 75 points in the subtree below this node. The deviance for all points contained in region below this node is 75.06 A *
in the line denotes that this is in fact a terminal node. The prediction at this node is Sales = MM
. About 42% points in this node have CH
as value of Sales
. Remaining 58% points have MM
as value of Sales
.
(d) Create a plot of the tree, and interpret the results.
dev.new(width=5, height=24, unit="in")
plot(tree_oj)
text(tree_oj, pretty = 0,cex=0.55)
LoyalCH
is the most important variable of the tree, in fact top 3 nodes contain LoyalCH
. If LoyalCH<0.0.27, the tree predicts MM. If LoyalCH>0.75, the tree predicts CH. For intermediate values of LoyalCH
, the decision also depends on the value of the three additional variables.
(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?
library(caret)
pred_oj= predict(tree_oj, test_oj, type = "class")
confusionMatrix(test_oj$Purchase, pred_oj)
Confusion Matrix and Statistics
Reference
Prediction CH MM
CH 149 15
MM 30 76
Accuracy : 0.8333
95% CI : (0.7834, 0.8758)
No Information Rate : 0.663
P-Value [Acc > NIR] : 2.739e-10
Kappa : 0.6416
Mcnemar's Test P-Value : 0.03689
Sensitivity : 0.8324
Specificity : 0.8352
Pos Pred Value : 0.9085
Neg Pred Value : 0.7170
Prevalence : 0.6630
Detection Rate : 0.5519
Detection Prevalence : 0.6074
Balanced Accuracy : 0.8338
'Positive' Class : CH
(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 = "Deviance")
(h) Which tree size corresponds to the lowest cross-validated classification error rate?
Size of 6 gives lowest cross-validation error.
(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)
(j) Compare the training error rates between the pruned and unpruned trees. Which is higher?
summary(prune_oj)
Classification tree:
snip.tree(tree = tree_oj, 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
(k) Compare the test error rates between the pruned and unpruned trees. Which is higher?
unpruned_pred = predict(tree_oj, test_oj, type = "class")
unpruned_error = sum(test_oj$Purchase != unpruned_pred)
unpruned_error/length(unpruned_pred)
[1] 0.1666667
pruned_pred = predict(prune_oj, test_oj, type = "class")
pruned_error = sum(test_oj$Purchase != pruned_pred)
pruned_error/length(pruned_pred)
[1] 0.2
Unpruned tree has a lower test error rate compared to the pruned tree.