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.

# Define the sequence of probabilities
p <- seq(0, 1, length.out = 1000)

# Gini index
gini <- 2 * p * (1 - p)

# Classification error
class_error <- 1 - pmax(p, 1 - p)

# Entropy (handle 0*log(0) = 0 gracefully)
entropy <- -p * log2(p) - (1 - p) * log2(1 - p)
entropy[is.nan(entropy)] <- 0  # Replace NaNs from log(0) with 0

# Plot all three on the same graph
plot(p, gini, type = "l", col = "blue", lwd = 2, ylim = c(0, 1),
     ylab = "Impurity Measure", xlab = expression(hat(p)[m1]),
     main = "Gini, Classification Error, and Entropy vs p")

lines(p, class_error, col = "red", lwd = 2, lty = 2)
lines(p, entropy, col = "darkgreen", lwd = 2, lty = 3)

legend("top", legend = c("Gini Index", "Classification Error", "Entropy"),
       col = c("blue", "red", "darkgreen"), lwd = 2, lty = c(1, 2, 3))

# 8

In the lab, a classification tree was applied to the Carseats data set after converting Sales into a qualitative response variable. Now we willseek 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(tree)
## Warning: package 'tree' was built under R version 4.4.3
library(caret)
## Warning: package 'caret' was built under R version 4.4.2
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 4.4.3
## Loading required package: lattice
library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.4.2
library(rattle)
## Warning: package 'rattle' was built under R version 4.4.3
## Loading required package: tibble
## Loading required package: bitops
## Rattle: A free graphical interface for data science with R.
## Version 5.5.1 Copyright (c) 2006-2021 Togaware Pty Ltd.
## Type 'rattle()' to shake, rattle, and roll your data.
library(rpart.plot)
## Warning: package 'rpart.plot' was built under R version 4.4.3
## Loading required package: rpart
## Warning: package 'rpart' was built under R version 4.4.3
data(Carseats)
index = createDataPartition(Carseats$Sales,p = .75, list = F)
train = Carseats[index,]
test = Carseats[-index,]

(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?

tree.carseats = tree(Sales ~., train)
summary(tree.carseats)
## 
## Regression tree:
## tree(formula = Sales ~ ., data = train)
## Variables actually used in tree construction:
## [1] "ShelveLoc"  "Price"      "Age"        "Income"     "CompPrice" 
## [6] "Population"
## Number of terminal nodes:  15 
## Residual mean deviance:  2.68 = 766.4 / 286 
## Distribution of residuals:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -3.7710 -1.1200  0.0344  0.0000  1.1350  4.5890
plot(tree.carseats)
text(tree.carseats, pretty = 0)

ShelveLoc is the first split in the regression tree, which happens to be a factor variable. Is the shelving location of the carseat in a good or bad location. If ShelveLoc is in a true than the it splits to price being less than 106.5.

yhat = predict(tree.carseats, newdata = test)
mean((yhat - test$Sales)^2)
## [1] 5.434363

The test MSE on fitting a regression tree is 4.74, which is relatively close to zero, but the tree has not be pruned and can possibly lead to overfitting.

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

cv.carseats = cv.tree(tree.carseats)
plot(cv.carseats$size,cv.carseats$dev, type = "b")

prune.carseats = prune.tree(tree.carseats, best = 7)
plot(prune.carseats)
text(prune.carseats, pretty  = 0)

yhat = predict(prune.carseats, newdata = test)
mean((yhat - test$Sales)^2)
## [1] 5.34862

Pruning the tree does not improve the test MSE, instead it makes it slightly worse.

(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.4.3
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:rattle':
## 
##     importance
## The following object is masked from 'package:ggplot2':
## 
##     margin
set.seed(1)
bag.carseats = randomForest(Sales~., data = train , mtry = 10)

bag.carseats
## 
## Call:
##  randomForest(formula = Sales ~ ., data = train, mtry = 10) 
##                Type of random forest: regression
##                      Number of trees: 500
## No. of variables tried at each split: 10
## 
##           Mean of squared residuals: 2.56784
##                     % Var explained: 68.83
yhat = predict(bag.carseats, newdata = test)
mean((yhat-test$Sales)^2)
## [1] 2.526056
importance(bag.carseats)
##             IncNodePurity
## CompPrice      225.625792
## Income         120.411029
## Advertising    135.391734
## Population      87.441971
## Price          824.522977
## ShelveLoc      700.376310
## Age            243.921299
## Education       62.679789
## Urban            8.250823
## US              11.963974

The variables that are found to be important are ShelveLoc and Price.

varImpPlot(bag.carseats, main = "Variables of Importance")

(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.carseats = randomForest(Sales ~., data = train, mtry = 11/3)
rf.carseats
## 
## Call:
##  randomForest(formula = Sales ~ ., data = train, mtry = 11/3) 
##                Type of random forest: regression
##                      Number of trees: 500
## No. of variables tried at each split: 4
## 
##           Mean of squared residuals: 2.593947
##                     % Var explained: 68.51
yhat = predict(rf.carseats, newdata = test)

mean((yhat - test$Sales)^2)
## [1] 2.531505

When there are less variables considered at each split the error rate appears to go down.

(f) Now analyze the data using BART, and report your results.

library(BART)
## Warning: package 'BART' was built under R version 4.4.3
## Loading required package: nlme
## Loading required package: survival
## Warning: package 'survival' was built under R version 4.4.3
## 
## Attaching package: 'survival'
## The following object is masked from 'package:caret':
## 
##     cluster
x = Carseats[,1:11] # want these columns
y = Carseats[,"Sales"] # response variable
xtrain = x[index,]
ytrain = y[index]
xtest = x[-index,]
ytest = y[-index]

set.seed(123)
bart = gbart(xtrain,ytrain, x.test = xtest)
## Warning in summary.lm(lm(y.train ~ ., data.frame(t(x.train), y.train))):
## essentially perfect fit: summary may be unreliable
## *****Calling gbart: type=1
## *****Data:
## data:n,p,np: 301, 15, 99
## y1,yn: 2.009668, 2.219668
## x1,x[n*p]: 9.500000, 1.000000
## xp1,xp[np*p]: 10.810000, 1.000000
## *****Number of Trees: 200
## *****Number of Cut Points: 100 ... 1
## *****burn,nd,thin: 100,1000,1
## *****Prior:beta,alpha,tau,nu,lambda,offset: 2,0.95,0.287616,3,8.29824e-31,7.49033
## *****sigma: 0.000000
## *****w (weights): 1.000000 ... 1.000000
## *****Dirichlet:sparse,theta,omega,a,b,rho,augment: 0,0,1,0.5,1,15,0
## *****printevery: 100
## 
## MCMC
## done 0 (out of 1100)
## done 100 (out of 1100)
## done 200 (out of 1100)
## done 300 (out of 1100)
## done 400 (out of 1100)
## done 500 (out of 1100)
## done 600 (out of 1100)
## done 700 (out of 1100)
## done 800 (out of 1100)
## done 900 (out of 1100)
## done 1000 (out of 1100)
## time: 2s
## trcnt,tecnt: 1000,1000
yhat.bart = bart$yhat.test.mean
mean((ytest-yhat.bart)^2)
## [1] 0.03442918

The test error rate with the Bayesian Additive Regression Tree model yields an error rate of .10.

9

This problem involves the OJ data set which is part of the ISLR2 package.

(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.

set.seed(123)
data(OJ)

oj.index = sample(1:nrow(OJ), 800)

oj.train = OJ[oj.index,]
oj.test = OJ[-oj.index,]

(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,subset = oj.index)
summary(oj.tree)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ, subset = oj.index)
## Variables actually used in tree construction:
## [1] "LoyalCH"   "PriceDiff"
## Number of terminal nodes:  8 
## Residual mean deviance:  0.7625 = 603.9 / 792 
## Misclassification error rate: 0.165 = 132 / 800

There are 8 terminal nodes within the decision tree and the training error rate is .165. LoyalCH and PriceDiff appear to be the important variables within this data.

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

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

plot(oj.tree)
text(oj.tree, pretty = 0)

The first split is at LoyalCH < .50 which is the brand loyalty for Citrius Hill. If LoyalCH is > .50 is true than one would work to the right which asks the next question. Is LoyalCH < .27 if so than go to the right, if not go to the right. So on and so forth.

(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.predict = predict(oj.tree, oj.test, type = "class")

confusionMatrix(oj.predict,oj.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 150  34
##         MM  16  70
##                                           
##                Accuracy : 0.8148          
##                  95% CI : (0.7633, 0.8593)
##     No Information Rate : 0.6148          
##     P-Value [Acc > NIR] : 9.56e-13        
##                                           
##                   Kappa : 0.596           
##                                           
##  Mcnemar's Test P-Value : 0.01621         
##                                           
##             Sensitivity : 0.9036          
##             Specificity : 0.6731          
##          Pos Pred Value : 0.8152          
##          Neg Pred Value : 0.8140          
##              Prevalence : 0.6148          
##          Detection Rate : 0.5556          
##    Detection Prevalence : 0.6815          
##       Balanced Accuracy : 0.7883          
##                                           
##        'Positive' Class : CH              
## 

The overall accuracy is .81 meaning the misclassification is .19.

(f) Apply the cv.tree() function to the training set in order to determine the optimal tree size.

(g) Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.

cv.oj = cv.tree(oj.tree)
plot(cv.oj$size,cv.oj$dev, type = "b")

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

(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 = 6)
summary(oj.prune)
## 
## Classification tree:
## snip.tree(tree = oj.tree, nodes = c(4L, 14L))
## Variables actually used in tree construction:
## [1] "LoyalCH"   "PriceDiff"
## Number of terminal nodes:  6 
## Residual mean deviance:  0.7945 = 630.9 / 794 
## Misclassification error rate: 0.165 = 132 / 800

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

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

oj.prune.predict = predict(oj.prune, newdata = oj.test,type = "class")

confusionMatrix(oj.prune.predict, oj.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 150  34
##         MM  16  70
##                                           
##                Accuracy : 0.8148          
##                  95% CI : (0.7633, 0.8593)
##     No Information Rate : 0.6148          
##     P-Value [Acc > NIR] : 9.56e-13        
##                                           
##                   Kappa : 0.596           
##                                           
##  Mcnemar's Test P-Value : 0.01621         
##                                           
##             Sensitivity : 0.9036          
##             Specificity : 0.6731          
##          Pos Pred Value : 0.8152          
##          Neg Pred Value : 0.8140          
##              Prevalence : 0.6148          
##          Detection Rate : 0.5556          
##    Detection Prevalence : 0.6815          
##       Balanced Accuracy : 0.7883          
##                                           
##        'Positive' Class : CH              
##