ANSWER 3a:
require(ISLR)
## Loading required package: ISLR
require(dplyr)
## Loading required package: dplyr
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
require(caret)
## Loading required package: caret
## Loading required package: lattice
## Loading required package: ggplot2
require(ggplot2)
require(tidyr)
## Loading required package: tidyr
prop_class_1 <- seq(0, 1, 0.001)
prop_class_2 <- 1 - prop_class_1
classification_error <- 1 - pmax(prop_class_1, prop_class_2)
gini <- prop_class_1*(1-prop_class_1) + prop_class_2*(1-prop_class_2)
entropy <- -prop_class_1*log(prop_class_1) - prop_class_2*log(prop_class_2)
data.frame(prop_class_1, prop_class_2, classification_error, gini, entropy) %>%
pivot_longer(cols = c(classification_error, gini, entropy), names_to = "comb") %>%
ggplot(aes(x = prop_class_1, y = value, col = factor(comb)))+
geom_line(size = 1) +
scale_y_continuous(breaks = seq(0, 1, 0.1), minor_breaks = NULL) +
scale_color_hue(labels = c("Classification Error", "Entropy", "Gini")) +
labs(col = "comb",
y = "Value",
x = "Proportion (of class '1')")
#+
#scale_colour_manual(values = c("Classification Error" = "orange", "Entropy" = "blue", "Gini" = "red"))
ANSWER 8a:
Data is split as shown below for train and test sets:
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
set.seed(2, sample.kind = "Rounding")
train_index <- sample(1:nrow(Carseats), nrow(Carseats) / 2)
train <- Carseats[train_index, ]
test <- Carseats[-train_index, ]
ANSWER 8b:
ShelveLoc and Price appear to be the most important factors in predicting car seat sales as they appear at the top of the tree. There is a total of 17 terminal nodes and the test MSE result = 4.844991 as shown below:
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
require(tree)
## Loading required package: tree
tree_model <- tree(Sales ~ ., train)
plot(tree_model)
text(tree_model, cex = .50)
summary(tree_model)
##
## Regression tree:
## tree(formula = Sales ~ ., data = train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "Age" "Income" "CompPrice"
## [6] "Population" "Advertising"
## Number of terminal nodes: 17
## Residual mean deviance: 2.341 = 428.4 / 183
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -3.76700 -1.00900 -0.01558 0.00000 0.94900 3.58600
test_pred <- predict(tree_model, test)
mean((test_pred - test$Sales)^2)
## [1] 4.844991
ANSWER 8c:
The model selected with the lowest cross-validation error is the one with 17 Terminal Nodes as shown below. The optimal tree is the original fully grown tree without pruning, therefore, the test MSE is the same result from part 8b.
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
set.seed(3)
cv_tree_model <- cv.tree(tree_model, K = 10)
data.frame(n_leaves = cv_tree_model$size,
CV_RSS = cv_tree_model$dev) %>%
mutate(min_CV_RSS = as.numeric(min(CV_RSS) == CV_RSS)) %>%
ggplot(aes(x = n_leaves, y = CV_RSS)) +
geom_line(col = "blue") +
geom_point(size = 2, aes(col = factor(min_CV_RSS))) +
scale_x_continuous(breaks = seq(1, 17, 2)) +
scale_y_continuous(labels = scales::comma_format()) +
scale_color_manual(values = c("deepskyblue3", "orange")) +
theme(legend.position = "none") +
labs(title = "Carseats Dataset - Regression Tree",
subtitle = "Selecting the complexity parameter with cross-validation",
x = "Terminal Nodes",
y = "CV RSS")
pruned_tree_model <- prune.tree(tree_model, best = 17)
test_pred <- predict(pruned_tree_model, test)
mean((test_pred - test$Sales)^2)
## [1] 4.844991
ANSWER 8d:
By using the randomForest() function we can implement bagged trees as shown below. The test MSE obtained = 2.368674. By using the importance() function we find that the important variables are Price and Shelveloc for bagged trees.
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
require(randomForest)
## Loading required package: randomForest
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
##
## margin
## The following object is masked from 'package:dplyr':
##
## combine
require(tibble)
## Loading required package: tibble
set.seed(1)
bagged_trees_mdl <- randomForest(y = train$Sales, x = train[ ,-1], mtry = ncol(train) - 1, importance = T)
test_pred <- predict(bagged_trees_mdl, test)
mean((test_pred - test$Sales)^2)
## [1] 2.368674
importance(bagged_trees_mdl) %>% as.data.frame() %>% rownames_to_column("varname") %>% arrange(desc(IncNodePurity))
## varname %IncMSE IncNodePurity
## 1 Price 55.76266629 493.804969
## 2 ShelveLoc 53.87451311 446.816951
## 3 CompPrice 25.47984338 173.982449
## 4 Age 12.07366106 117.502364
## 5 Advertising 13.97464644 96.929928
## 6 Income 1.72616791 71.465227
## 7 Population 1.01449985 68.297498
## 8 Education 0.08382003 37.513944
## 9 Urban -3.06299457 6.909530
## 10 US 0.14346468 5.985091
ANSWER 8e:
Reducing the mtry increases the test MSE and increasing the mtry rapidly reduces the test error as shown in the plot below. The best random forest model uses an mtry = 10. The test MSE = 2.368674. By using the importance() function we find that the important variables are Price and Shelveloc for bagged trees as shown below.
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
test_MSE <- c()
j <- 1
for (Mtry in 1:10) {
set.seed(1)
rf_temp <- randomForest(y = train$Sales,
x = train[ ,-1],
mtry = Mtry,
importance = T)
test_pred <- predict(rf_temp, test)
test_MSE[j] <- mean((test_pred - test$Sales)^2)
j <- j + 1
}
data.frame(mtry = 1:10, test_MSE = test_MSE) %>%
mutate(min_test_MSE = as.numeric(min(test_MSE) == test_MSE)) %>%
ggplot(aes(x = mtry, y = test_MSE)) +
geom_line(col = "blue") +
geom_point(size = 2, aes(col = factor(min_test_MSE))) +
scale_x_continuous(breaks = seq(1, 10), minor_breaks = NULL) +
scale_color_manual(values = c("deepskyblue3", "orange")) +
theme(legend.position = "none") +
labs(title = "Carseats Dataset - Random Forests",
subtitle = "Selecting 'mtry' using the test MSE",
x = "mtry",
y = "Test MSE")
tail(test_MSE, 1)
## [1] 2.368674
importance(rf_temp) %>%as.data.frame() %>%rownames_to_column("varname") %>% arrange(desc(IncNodePurity))
## varname %IncMSE IncNodePurity
## 1 Price 55.76266629 493.804969
## 2 ShelveLoc 53.87451311 446.816951
## 3 CompPrice 25.47984338 173.982449
## 4 Age 12.07366106 117.502364
## 5 Advertising 13.97464644 96.929928
## 6 Income 1.72616791 71.465227
## 7 Population 1.01449985 68.297498
## 8 Education 0.08382003 37.513944
## 9 Urban -3.06299457 6.909530
## 10 US 0.14346468 5.985091
ANSWER 9a:
train and test sets are split below as shown:
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
#glimpse(OJ) # OJ dataset shows 1,070 rows
set.seed(5)
train_index <- sample(1:nrow(OJ), 800)
train <- OJ[train_index, ]
test <- OJ[-train_index, ]
ANSWER 9b:
The training error rate = 18.38%. There is 7 terminal nodes in the classification tree as shown below. There are only 3 predictors used in the tree construction(splits): LoyalCH, PriceDiff and DiscCH.
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
tree_mdl <- tree(Purchase ~ ., train)
summary(tree_mdl)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "DiscCH"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7786 = 617.4 / 793
## Misclassification error rate: 0.1838 = 147 / 800
ANSWER 9c:
Choosing Node #12: which is also a terminal node. From the root node, the following splits produce the terminal Node 12:
split at LoyalCH = 0.5036
split at LoyalCH = 0.705699
split at PriceDiff = 0.25
Node #12 is the subset of purchases where 0.5036 < LoyalCH < 0.705699 and PriceDiff < 0.25. The overall prediction isCH and the node shows 52.94% CH vs 47.05%MM.
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
tree_mdl
## node), split, n, deviance, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 1064.00 CH ( 0.61750 0.38250 )
## 2) LoyalCH < 0.5036 354 435.50 MM ( 0.30508 0.69492 )
## 4) LoyalCH < 0.142213 100 45.39 MM ( 0.06000 0.94000 ) *
## 5) LoyalCH > 0.142213 254 342.20 MM ( 0.40157 0.59843 )
## 10) PriceDiff < 0.235 136 153.00 MM ( 0.25000 0.75000 ) *
## 11) PriceDiff > 0.235 118 160.80 CH ( 0.57627 0.42373 ) *
## 3) LoyalCH > 0.5036 446 352.30 CH ( 0.86547 0.13453 )
## 6) LoyalCH < 0.705699 154 189.50 CH ( 0.69481 0.30519 )
## 12) PriceDiff < 0.25 85 117.50 CH ( 0.52941 0.47059 )
## 24) DiscCH < 0.15 77 106.60 MM ( 0.48052 0.51948 ) *
## 25) DiscCH > 0.15 8 0.00 CH ( 1.00000 0.00000 ) *
## 13) PriceDiff > 0.25 69 45.30 CH ( 0.89855 0.10145 ) *
## 7) LoyalCH > 0.705699 292 106.30 CH ( 0.95548 0.04452 ) *
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.
ANSWER 9d:
LoyalCH is the most important variable, followed by PriceDiff and DiscCH. We can see Node #12is the third terminal node from right to left (its shown where PriceDiff< 0.25). LoyalCH ranges from 0 to 1, the first split takes the less loyal to CH to the left and those more loyal to CH to the right.
Those that scored the lowest (LoyalCH < 0.142213) have been predicted to buy MM.Those that were a bit more loyal to CH (0.142213 < LoyalCH < 0.5036) will buy MMif the price is not to high (Price < 0.235), but if the price is high enough they will end up purchasing CH
Those on the right side of the tree are the most loyal to CH(LoyalCH > 0.705699) and this is also their predicted purchase. Those with lower brand loyalty (0.5036 < LoyalCH < 0.705699) will purchase CHif its cheaper (Price > 0.25) or at a discount(PriceDiff < 0.25 & DiscCH > 0.15). For cases where CH were not cheap enough(PriceDiff < 0.25) and at a discount(DiscCH < 0.15) the predicted purchase is MM.
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
require(tree)
plot(tree_mdl)
text(tree_mdl, cex = 0.5)
ANSWER 9e:
The test error rate is 0.2444444 as shown below:
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
test_pred <- predict(tree_mdl, test, type = "class")
table(test_pred, test_actual = test$Purchase)
## test_actual
## test_pred CH MM
## CH 125 32
## MM 34 79
1 - mean(test_pred == test$Purchase)
## [1] 0.2444444
ANSWER 9f:
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
set.seed(2)
cv_tree_model <- cv.tree(tree_mdl, K = 10, FUN = prune.misclass)
cv_tree_model
## $size
## [1] 7 4 2 1
##
## $dev
## [1] 164 164 177 298
##
## $k
## [1] -Inf 1 9 138
##
## $method
## [1] "misclass"
##
## attr(,"class")
## [1] "prune" "tree.sequence"
ANSWER 9g:
The cross-validated classification error rate and tree size plot is shown below:
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
data.frame(size = cv_tree_model$size, CV_Error = cv_tree_model$dev / nrow(train)) %>% mutate(min_CV_Error = as.numeric(min(CV_Error) == CV_Error)) %>%
ggplot(aes(x = size, y = CV_Error)) +
geom_line(col = "blue") +
geom_point(size = 2, aes(col = factor(min_CV_Error))) +
scale_x_continuous(breaks = seq(1, 7), minor_breaks = NULL) +
scale_y_continuous(labels = scales::percent_format()) +
scale_color_manual(values = c("deepskyblue3", "orange")) +
theme(legend.position = "none") +
labs(title = "OJ Dataset - Classification Tree",
subtitle = "Selecting tree 'size' (# of terminal nodes) using cross-validation",
x = "Tree Size",
y = "CV Error")
ANSWER 9h:
Using the previous plot from part 9g we can see that trees of sizes 4 and 7 have the lowest (and same) cross validation error.
ANSWER 9i:
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
pruned_tree_model <- prune.tree(tree_mdl, best = 4)
pruned_tree_model
## node), split, n, deviance, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 1064.00 CH ( 0.61750 0.38250 )
## 2) LoyalCH < 0.5036 354 435.50 MM ( 0.30508 0.69492 )
## 4) LoyalCH < 0.142213 100 45.39 MM ( 0.06000 0.94000 ) *
## 5) LoyalCH > 0.142213 254 342.20 MM ( 0.40157 0.59843 ) *
## 3) LoyalCH > 0.5036 446 352.30 CH ( 0.86547 0.13453 )
## 6) LoyalCH < 0.705699 154 189.50 CH ( 0.69481 0.30519 ) *
## 7) LoyalCH > 0.705699 292 106.30 CH ( 0.95548 0.04452 ) *
ANSWER 9j:
The training error = 0.21 for the pruned tree and its also higher than the unpruned tree training error as shown below. We expect the training error of a tree to decrease as the number of splits increase.
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
require(gam)
## Loading required package: gam
## Loading required package: splines
## Loading required package: foreach
## Loaded gam 1.20
mean(predict(pruned_tree_model, type = "class") != train$Purchase)
## [1] 0.21
#training error for pruned tree - 4 terminal nodes
mean(predict(tree_mdl, type = "class") != train$Purchase)
## [1] 0.18375
#training error for unpruned tree - 7 terminal nodes
ANSWER 9k:
The Test Error = 0.24 for the unpruned tree is higher than the pruned tree Test Error as shown below.
require(ISLR)
require(dplyr)
require(caret)
require(ggplot2)
mean(predict(pruned_tree_model, type = "class", newdata = test) != test$Purchase)
## [1] 0.1703704
#Test Error for the pruned tree
mean(predict(tree_mdl, type = "class", newdata = test) != test$Purchase)
## [1] 0.2444444
#Test Error for the unpruned tree