Problem 3

Consider the Gini index, classification error, and entropy in a simple classfication setting with two classes. Create a single plot that displays each of these qualitites as a function of \(\hat{p}_m1\). The axis 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.

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))
matplot(p, cbind(gini.index, class.error, cross.entropy), col = c("red", "green", "blue"))

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

  1. Split the data set into a training set and a test set.
set.seed(123)
train = sample(nrow(Carseats), 200)
seats.train = Carseats[train,]
seats.test = Carseats[-train,]
  1. Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
tree.fit = tree(Sales~., data=seats.train)
summary(tree.fit)
## 
## Regression tree:
## tree(formula = Sales ~ ., data = seats.train)
## Variables actually used in tree construction:
## [1] "ShelveLoc"   "Price"       "Income"      "Age"         "Population" 
## [6] "Education"   "CompPrice"   "Advertising"
## Number of terminal nodes:  18 
## Residual mean deviance:  2.132 = 388.1 / 182 
## Distribution of residuals:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -4.08000 -0.92870  0.06244  0.00000  0.87020  3.71700
plot(tree.fit)
text(tree.fit, pretty = 0)

tree.preds = predict(tree.fit, seats.test)

test.mse = mean((tree.preds - seats.test$Sales)^2)

test.mse
## [1] 4.395357

We obtain a test MSE of 4.39

  1. 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.tree.fit = cv.tree(tree.fit)

plot(cv.tree.fit$size, cv.tree.fit$dev, type='b')

tree.min = which.min(cv.tree.fit$dev)

points(cv.tree.fit$size[tree.min],cv.tree.fit$dev[tree.min], col="red", cex=2, pch=20)

pruned.tree = prune.tree(tree.fit, best=7)

plot(pruned.tree)

text(pruned.tree, pretty=0)

prune.preds = predict(pruned.tree, seats.test)

pruned.test.mse = mean((prune.preds-seats.test$Sales)^2)

In this case the optimal tree size is 7 compared to the 18 terminal nodes seen in the summary output. The test MSE does not improve after pruning. It is less accurate going from 4.39 without pruning to 4.69 with pruning.

  1. 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.
# bagging approach is similar to random forests but uses all variables at each split?
bag.seats = randomForest(Sales~., data = seats.train, mtry = 10, ntree = 500, importance = TRUE)  

bag.preds = predict(bag.seats, seats.test)

bag.test.mse = mean((bag.preds-seats.test$Sales)^2)

importance(bag.seats)
##               %IncMSE IncNodePurity
## CompPrice   20.314863    165.247282
## Income       7.983399     93.277231
## Advertising  6.526357     74.739251
## Population  -1.156118     50.540570
## Price       47.182833    380.171717
## ShelveLoc   49.266950    387.018630
## Age         18.319586    176.976966
## Education    2.892331     56.176298
## Urban       -1.645249      8.109251
## US          -1.189827      5.885208
data.frame(importance = bag.seats$importanceSD) %>%
  tibble::rownames_to_column(var = "variable") %>%
  ggplot(aes(x = reorder(variable,importance), y = importance)) +
    geom_bar(stat = "identity", fill = "orange", color = "black")+
    coord_flip() +
     labs(x = "Variables", y = "Variable importance")

After using a bagging approach the test MSE decreases to 2.75, performing the best in the metric compared with all other models. We can conclude from the summary output that Price and ShelveLoc have a significant impact on Sales.

  1. 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.seats = randomForest(Sales~., data = seats.train, mtry=3, ntree=500, importance=T)

rf.preds = predict(rf.seats, seats.test)

rf.test.mse = mean((rf.preds - seats.test$Sales)^2)

data.frame(importance = rf.seats$importanceSD) %>%
  tibble::rownames_to_column(var = "variable") %>%
  ggplot(aes(x = reorder(variable,importance), y = importance)) +
    geom_bar(stat = "identity", fill = "orange", color = "black")+
    coord_flip() +
     labs(x = "Variables", y = "Variable importance")

The test MSE improves from our original regression tree model but, does worse than our bagged approach, achieving a test MSE of 3.60. Using \(m=p\) the lowest error rate is obtained. The same two variables were important with this random forest approach compared with other models.

Problem 9

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

  1. Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
train = sample(1:nrow(OJ), 800)
oj.train = OJ[train,]
oj.test = OJ[-train,]
  1. 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?
tree.oj = tree(Purchase ~., data=oj.train)

summary(tree.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "ListPriceDiff" "StoreID"      
## Number of terminal nodes:  9 
## Residual mean deviance:  0.721 = 570.3 / 791 
## Misclassification error rate: 0.1638 = 131 / 800

The fitted tree has 7 terminal nodes and a training error rate of 0.17

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

We pick the node labeled 8. The split criterion is LoyalCH < 0.035, the number of observations in that branch is 57 with a deviance of 10.07 and an overall prediction for the branch of MM. Less than 2% of the observations in that branch take the value of CH, and the remaining 98% take the value of MM.

  1. Create a plot of the tree, and interpret the results.
plot(tree.oj)
text(tree.oj, pretty=0)

The variable LoyalCH is seen in the top three nodes of the tree indicating it is most important when predicting Purchase.

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

confusionMatrix(as.factor(oj.preds), oj.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 136  30
##         MM  27  77
##                                          
##                Accuracy : 0.7889         
##                  95% CI : (0.7353, 0.836)
##     No Information Rate : 0.6037         
##     P-Value [Acc > NIR] : 6.866e-11      
##                                          
##                   Kappa : 0.5567         
##                                          
##  Mcnemar's Test P-Value : 0.7911         
##                                          
##             Sensitivity : 0.8344         
##             Specificity : 0.7196         
##          Pos Pred Value : 0.8193         
##          Neg Pred Value : 0.7404         
##              Prevalence : 0.6037         
##          Detection Rate : 0.5037         
##    Detection Prevalence : 0.6148         
##       Balanced Accuracy : 0.7770         
##                                          
##        'Positive' Class : CH             
## 
# test mse = 1 - (TP + TN) / Total
oj.test.mse = 1 - (149 + 78) / 270

Our test error rate is about 16%

  1. Apply the cv.tree() function to the training set in order to determine the optimal tree size.
set.seed(1)
cv.oj = cv.tree(tree.oj, FUN = prune.misclass)
  1. 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 = "CV Error Rate")

  1. Which tree size corresponds to the lowest cross-validated classification error rate?
tree.min = which.min(cv.oj$dev)
plot(cv.oj$size, cv.oj$dev, type='b', xlab =  'Tree Size', ylab = "CV Error Rate")
points(cv.oj$size[tree.min],cv.oj$dev[tree.min], col="red", cex=2, pch=20)

A tree size of 4 achieves the lowest cross-validated classfication error rate.

  1. 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.misclass(tree.oj, best = 4)
  1. Compare the training error rates between the pruned and unpruned trees. Which is higher?
summary(tree.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "PriceDiff"     "ListPriceDiff" "StoreID"      
## Number of terminal nodes:  9 
## Residual mean deviance:  0.721 = 570.3 / 791 
## Misclassification error rate: 0.1638 = 131 / 800
summary(prune.oj)
## 
## Classification tree:
## snip.tree(tree = tree.oj, nodes = 4:3)
## Variables actually used in tree construction:
## [1] "LoyalCH"   "PriceDiff"
## Number of terminal nodes:  4 
## Residual mean deviance:  0.8815 = 701.7 / 796 
## Misclassification error rate: 0.1775 = 142 / 800

The test error rate is slightly higher for the pruned tree, going from 0.163 in the original model to 0.178 in the pruned model.

  1. Compare the test error rates between the pruned and unpruned trees. Which is higher?
oj.prune.preds = predict(prune.oj, oj.test, type='class')

confusionMatrix(oj.prune.preds, oj.test$Purchase)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  CH  MM
##         CH 151  37
##         MM  12  70
##                                           
##                Accuracy : 0.8185          
##                  95% CI : (0.7673, 0.8626)
##     No Information Rate : 0.6037          
##     P-Value [Acc > NIR] : 2.381e-14       
##                                           
##                   Kappa : 0.6049          
##                                           
##  Mcnemar's Test P-Value : 0.0006068       
##                                           
##             Sensitivity : 0.9264          
##             Specificity : 0.6542          
##          Pos Pred Value : 0.8032          
##          Neg Pred Value : 0.8537          
##              Prevalence : 0.6037          
##          Detection Rate : 0.5593          
##    Detection Prevalence : 0.6963          
##       Balanced Accuracy : 0.7903          
##                                           
##        'Positive' Class : CH              
## 
# test mse = 1 - (TP + TN) / Total
prune.oj.mse = 1 - (151 + 71) / 270

The test MSE has increased from 0.15 to 0.17 after pruning the classification tree.