library(ISLR)
library(tidyverse) # plot
library(plotly) # plot
library(tree) # DT
library(Metrics)
library(rpart) # for some DT plots
library(randomForest) # Bagging and RF
library(caret) #predict 

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

Hint: In a setting with two classes, ˆpm1 = 1− ˆpm2. You could make this plot by hand, but it will be much easier to make in R.

gini.index = as_tibble(list(p=seq(0, 1, 0.001))) %>% 
  mutate(Value = p * (1-p) * 2,
         Measure = "Gini")

ent = as_tibble(list(p=seq(0, 1, 0.001))) %>%
  mutate(Value=-(p * log(p) + (1 - p) * log(1 - p)),
         Measure="Entropy")

error = as_tibble(list(p=seq(0, 1, 0.001))) %>%
  mutate(Value=1 - pmax(p, 1 - p),
         Measure="Classification Error")

df = bind_rows(gini.index, ent, error) %>% 
  arrange(Measure, p)

c = ggplot(df, aes(x=p,y=Value,col=Measure)) + 
  geom_line()+
  scale_color_manual(values=c("#657898","#901E56","#ECC919"))+
  labs(
    x = "p",
    y = "Value for Split",
    title = "Max value for each criterion occurs at p=0.50"
  ) +
  theme_minimal() 

plot1 = ggplotly(c,width=600,height=300)
plot1



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

attach(Carseats)

Part a)

Split the data set into a training set and a test set.

set.seed(123)
idx.train = sample(1:nrow(Carseats), size = 0.7 * nrow(Carseats))
train.df = Carseats[idx.train,]
test.df = Carseats[-idx.train,]

Part b)

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

dt.fit = tree(Sales ~ ., data = train.df)
summary(dt.fit)
## 
## Regression tree:
## tree(formula = Sales ~ ., data = train.df)
## Variables actually used in tree construction:
## [1] "ShelveLoc"   "Price"       "CompPrice"   "Age"         "Advertising"
## Number of terminal nodes:  19 
## Residual mean deviance:  2.373 = 619.2 / 261 
## Distribution of residuals:
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -4.1570 -1.0160  0.1123  0.0000  0.8903  4.0310
dt.preds = predict(dt.fit, newdata = test.df)
dt.mse = mean((test.df$Sales - dt.preds)^2)
# dt.mse = mse(test.df$Sales, dt.preds)
dt.mse
## [1] 3.602818

Answer: The Test MSE is 3.602818 (I actually tried different sizes of train/test split, and the one that brought back the lowest MSE was 70/30 split)

Plot the tree

dev.new(width=5, height=24, unit="in")
plot(dt.fit)
text(dt.fit, pretty = 0, cex=.55)

Part c)

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

set.seed(123)
cv.carseats = cv.tree(dt.fit, FUN = prune.tree)
par(mfrow=c(1,2))
plot(cv.carseats$size, cv.carseats$dev, type = "b")
plot(cv.carseats$k, cv.carseats$dev, type = "b")

par(mfrow = c(1,1))

From the plot above we see that the dev (error rate) reaches the first “lowest rate” at size 8 before going up. Hence, best size of our tree is 8.

# Best size = 8

dt.prune = prune.tree(dt.fit, best = 8)
plot(dt.prune)
text(dt.prune, pretty = 0, cex =0.70)

dt.preds.prune = predict(dt.prune, test.df)
dt.mse.prune = mean((test.df$Sales - dt.preds.prune)^2)
# dt.mse.prune = mse(test.df$Sales, dt.preds.prune)
dt.mse.prune
## [1] 4.353022

Comments: I tried different combinations of “seeds” and different splits of train/test, but mostly if I got a very low MSE in the original tree, the pruned tree MSE would come back higher. So just for a reference, original tree MSE = 3.6028 and pruned tree MSE = 4.353022.

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

bag.fit = randomForest(Sales ~ ., data = train.df, mtry = 10, ntree = 500, importance = T)
bag.preds = predict(bag.fit, test.df)
bag.mse = mse(test.df$Sales, bag.preds)
bag.mse
## [1] 2.286133

The MSE obtained is 2.2616, way lower than the one obtained by the single decision tree.

importance(bag.fit)
##                 %IncMSE IncNodePurity
## CompPrice   35.04398428    262.634020
## Income       7.72174845    118.463245
## Advertising 21.14653227    152.547657
## Population   1.51144119     65.516741
## Price       62.16044208    619.102777
## ShelveLoc   73.51790884    688.827708
## Age         18.88136946    178.342130
## Education    3.24288784     64.750094
## Urban        0.03439107      8.988814
## US           1.82268211      7.648748
varImpPlot(bag.fit)

Comments: We can see that all three of \(ShelveLoc\), \(Price\) and \(CompPrice\) are the most important predictors for the Sale Price.



Exercise 9

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

detach(Carseats)
attach(OJ)

Part a)

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

set.seed(123)
idx.train1 = sample(nrow(OJ), 800)
train.dfOJ = OJ[idx.train1,]
test.dfOJ = OJ[-idx.train1,]

Part 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?

dt.oj = tree(Purchase ~ ., data = train.dfOJ)
summary(dt.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = train.dfOJ)
## 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

Our tree has 8 terminal nodes, it uses only 2 variables: \(LoyalCH\) and \(PriceDiff\), the Training error is 0.165 (16.5%).

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

dt.oj
## node), split, n, deviance, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 800 1071.00 CH ( 0.60875 0.39125 )  
##    2) LoyalCH < 0.5036 350  415.10 MM ( 0.28000 0.72000 )  
##      4) LoyalCH < 0.276142 170  131.00 MM ( 0.12941 0.87059 )  
##        8) LoyalCH < 0.0356415 56   10.03 MM ( 0.01786 0.98214 ) *
##        9) LoyalCH > 0.0356415 114  108.90 MM ( 0.18421 0.81579 ) *
##      5) LoyalCH > 0.276142 180  245.20 MM ( 0.42222 0.57778 )  
##       10) PriceDiff < 0.05 74   74.61 MM ( 0.20270 0.79730 ) *
##       11) PriceDiff > 0.05 106  144.50 CH ( 0.57547 0.42453 ) *
##    3) LoyalCH > 0.5036 450  357.10 CH ( 0.86444 0.13556 )  
##      6) PriceDiff < -0.39 27   32.82 MM ( 0.29630 0.70370 ) *
##      7) PriceDiff > -0.39 423  273.70 CH ( 0.90071 0.09929 )  
##       14) LoyalCH < 0.705326 130  135.50 CH ( 0.78462 0.21538 )  
##         28) PriceDiff < 0.145 43   58.47 CH ( 0.58140 0.41860 ) *
##         29) PriceDiff > 0.145 87   62.07 CH ( 0.88506 0.11494 ) *
##       15) LoyalCH > 0.705326 293  112.50 CH ( 0.95222 0.04778 ) *

Here the tree object includes all nodes, splits and terminal nodes. The way we can recognize a terminal node is when we see a (*) next to it (in here the number of terminal nodes is 8 which matches what we saw before). If we go one by one, we can see a complete description of the visual tree. For example, node 8): starts from the root, and then due to having a value of LoyalCH < 0.5036 goes to node 4, and then again when LoyalCH < 0.2761 goes to node 8). The number after the % rate to split, is the number of observations that go to that node. For node 8, the deviance is 10.03, and the Sales = MM.

Part d)

Create a plot of the tree, and interpret the results.

plot(dt.oj)
text(dt.oj, pretty = 0, cex=.70)

Answer: Here we can see a little less information than from the full tree explanation, however we do see the terminal nodes and the criterion to split, which is what interests use the most.

Part 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?

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

Answer: Test accuracy is 81.48% , therefore test error rate is = 18.52%.

Part f)

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

set.seed(123)
cv.oj = cv.tree(dt.oj, FUN = prune.tree)

Part 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")

Part h)

Which tree size corresponds to the lowest cross-validated classification error rate?

Comments: Optimal tree size through cross-validation is 6.

Part 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(dt.oj, best = 6)

Part j)

Compare the training error rates between the pruned and unpruned trees. Which is higher?

summary(prune.oj)
## 
## Classification tree:
## snip.tree(tree = dt.oj, 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
summary(dt.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = train.dfOJ)
## 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

Comments: The training error rates from the unpruned and pruned trees is 16.5%

Part k)

Compare the test error rates between the pruned and unpruned trees. Which is higher?

unpruned_pred = predict(dt.oj, test.dfOJ, type = "class")
unpruned_error = sum(test.dfOJ$Purchase != unpruned_pred)
unpruned_error/length(unpruned_pred)
## [1] 0.1851852
pruned_pred = predict(prune.oj, test.dfOJ, type = "class")
pruned_error = sum(test.dfOJ$Purchase != pruned_pred)
pruned_error/length(pruned_pred)
## [1] 0.1851852

Comments: Both the test error rate from the unpruned and pruned tree is 18.5% , however, this is higher than the training rate, as it was expected.