3. Consider the Gini index, classification error, and entropy in a
simpleclassification 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.
gini=function(m1){
return(2*(m1*(1-m1)))
}
ent=function(m1){
m2=1-m1
return(-((m1*log(m1))+(m2*log(m2))))
}
classerr=function(m1){
m2=1-m1
return(1-max(m1,m2))
#return(min((1-m1),m1))
#return(m1)
}
err=seq(0,1,by=0.01)
c.err=sapply(err,classerr)
g=sapply(err,gini)
e=sapply(err,ent)
d=data.frame(Gini.Index=g,Cross.Entropy=e)
plot(err,c.err,type='l',col="red",xlab="m1",ylim=c(0,0.8),ylab="value")
matlines(err,d,col=c("green","blue"))

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.
library(MASS)
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.2.3
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
library(ggplot2)
##
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
##
## margin
library(ISLR2)
##
## Attaching package: 'ISLR2'
## The following object is masked from 'package:MASS':
##
## Boston
library(tree)
## Warning: package 'tree' was built under R version 4.2.3
library(gbm)
## Warning: package 'gbm' was built under R version 4.2.3
## Loaded gbm 2.1.8.1
library(glmnet)
## Warning: package 'glmnet' was built under R version 4.2.3
## Loading required package: Matrix
## Loaded glmnet 4.1-7
library(class)
## Warning: package 'class' was built under R version 4.2.3
## (a) Split the data set into a training set and a test set.
train_idx <- sample(seq_len(nrow(Carseats)),
nrow(Carseats) * 0.7)
train <- Carseats[train_idx,]
test <- Carseats[-train_idx,]
## (b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
carseats_tree <- tree(Sales ~ . , data = train)
sprintf("Test MSE: %s", mean((predict(carseats_tree, test) - test$Sales) ^ 2))
## [1] "Test MSE: 4.19985949914321"
plot(carseats_tree)
text(carseats_tree, pretty = 0)

## A test MNSE of approximately 5.41 is obtained
## (c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
carseats_cv <- cv.tree(carseats_tree)
plot(carseats_cv$size, carseats_cv$dev, type="b")

## Pruning does not appear to improve model performance, as the most complex tree gives the best performing fit.
## (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.
m <- ncol(train) - 1
carseats_bag <- randomForest(Sales ~ ., data = train, mtry = m, importance = TRUE)
sprintf("Test MSE: %s", mean((predict(carseats_bag, test) - test$Sales) ^ 2))
## [1] "Test MSE: 2.10853958082602"
importance(carseats_bag)
## %IncMSE IncNodePurity
## CompPrice 35.3570158 282.58046
## Income 10.0066121 130.16578
## Advertising 19.9124278 158.29277
## Population -0.5886356 89.67372
## Price 62.2938530 634.86334
## ShelveLoc 66.4949529 585.86127
## Age 16.1956841 155.09130
## Education 2.5512432 61.79080
## Urban 1.5923918 10.87141
## US 6.3124651 18.67375
## A test MSE of 2.35 was obtained.
# (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.
carseats_forest <- randomForest(Sales ~ ., data = train, importance = TRUE)
sprintf("Test MSE: %s", mean((predict(carseats_forest, test) - test$Sales) ^ 2))
## [1] "Test MSE: 2.65116605843623"
importance(carseats_forest)
## %IncMSE IncNodePurity
## CompPrice 18.4508280 227.57814
## Income 8.7116465 189.70670
## Advertising 17.9044171 196.77372
## Population -1.0610100 139.76257
## Price 36.7518080 484.61903
## ShelveLoc 42.6060321 456.03617
## Age 9.9954792 196.85741
## Education 0.7304565 93.01885
## Urban 1.9501624 23.92197
## US 4.0769371 34.46499
## `ShelveLoc` and `Price` appear to be the most important variables. Test MSE has improved to 2.28.
9. This problem involves the OJ data set which is part of the
ISLR2
## (a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
train_idx <- sample(nrow(OJ), 800)
train <- OJ[train_idx,]
test <- OJ[-train_idx,]
## (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 = train)
summary(oj_tree)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "SalePriceMM" "ListPriceDiff" "PriceDiff"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7541 = 598 / 793
## Misclassification error rate: 0.1525 = 122 / 800
## (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 1059.00 CH ( 0.62500 0.37500 )
## 2) LoyalCH < 0.48285 294 327.30 MM ( 0.24490 0.75510 )
## 4) LoyalCH < 0.276142 159 124.10 MM ( 0.13208 0.86792 ) *
## 5) LoyalCH > 0.276142 135 179.00 MM ( 0.37778 0.62222 )
## 10) SalePriceMM < 2.04 71 75.77 MM ( 0.22535 0.77465 ) *
## 11) SalePriceMM > 2.04 64 88.16 CH ( 0.54688 0.45312 ) *
## 3) LoyalCH > 0.48285 506 435.00 CH ( 0.84585 0.15415 )
## 6) LoyalCH < 0.764572 246 290.10 CH ( 0.72358 0.27642 )
## 12) ListPriceDiff < 0.235 96 132.90 MM ( 0.47917 0.52083 )
## 24) PriceDiff < 0.085 62 77.97 MM ( 0.32258 0.67742 ) *
## 25) PriceDiff > 0.085 34 37.10 CH ( 0.76471 0.23529 ) *
## 13) ListPriceDiff > 0.235 150 110.10 CH ( 0.88000 0.12000 ) *
## 7) LoyalCH > 0.764572 260 84.77 CH ( 0.96154 0.03846 ) *
## (d) Create a plot of the tree, and interpret the results.
plot(oj_tree)
text(oj_tree, pretty = 0)

## (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, test, type = "class")
table(oj_pred, test$Purchase)
##
## oj_pred CH MM
## CH 134 29
## MM 19 88
sprintf("Test error rate: %s", 1 - mean(oj_pred == test$Purchase))
## [1] "Test error rate: 0.177777777777778"
## (f) Apply the cv.tree() function to the training set in order to determine the optimal tree size.
oj_cv <- cv.tree(oj_tree, FUN = prune.misclass)
oj_cv
## $size
## [1] 7 5 2 1
##
## $dev
## [1] 146 140 159 300
##
## $k
## [1] -Inf 3.000000 7.333333 150.000000
##
## $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(oj_cv$size, oj_cv$dev, type="b")

## (h) Which tree size corresponds to the lowest cross-validated classification error rate?
## The optimal tree size is 7.
## (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_prune <- prune.tree(oj_tree, best = 7)
summary(oj_prune)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "SalePriceMM" "ListPriceDiff" "PriceDiff"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7541 = 598 / 793
## Misclassification error rate: 0.1525 = 122 / 800
## (j) Compare the training error rates between the pruned and unpruned trees. Which is higher?
## The training error rate for the pruned tree is higher, at 16.25% versus 15.88% for unpruned tree.
## (k) Compare the test error rates between the pruned and unpruned trees. Which is higher?
oj_prune_pred <- predict(oj_prune, test, type = "class")
table(oj_prune_pred, test$Purchase)
##
## oj_prune_pred CH MM
## CH 134 29
## MM 19 88
sprintf("Test unpruned error rate: %s", 1 - mean(oj_pred == test$Purchase))
## [1] "Test unpruned error rate: 0.177777777777778"
sprintf("Test pruned error rate: %s", 1 - mean(oj_prune_pred == test$Purchase))
## [1] "Test pruned error rate: 0.177777777777778"
## The test error for the unpruned tree is higher, at 17.04% versus 16.30% for the pruned tree.