library(caret)
## Warning: package 'caret' was built under R version 4.0.3
## Loading required package: lattice
## Loading required package: ggplot2
library(ISLR)
## Warning: package 'ISLR' was built under R version 4.0.3
library(tree)
## Warning: package 'tree' was built under R version 4.0.4
library(rattle)
## Warning: package 'rattle' was built under R version 4.0.4
## Loading required package: tibble
## Loading required package: bitops
## Warning: package 'bitops' was built under R version 4.0.3
## Rattle: A free graphical interface for data science with R.
## Version 5.4.0 Copyright (c) 2006-2020 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.0.4
## Loading required package: rpart
## Warning: package 'rpart' was built under R version 4.0.3
library(gbm)
## Warning: package 'gbm' was built under R version 4.0.4
## Loaded gbm 2.1.8
library(tidyverse)
## Registered S3 method overwritten by 'cli':
## method from
## print.tree tree
## -- Attaching packages --------------------------------------- tidyverse 1.3.0 --
## v tidyr 1.1.2 v dplyr 1.0.2
## v readr 1.3.1 v stringr 1.4.0
## v purrr 0.3.4 v forcats 0.5.0
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
## x purrr::lift() masks caret::lift()
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.0.4
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
## The following object is masked from 'package:dplyr':
##
## combine
## The following object is masked from 'package:rattle':
##
## importance
## The following object is masked from 'package:ggplot2':
##
## margin
Consider the Gini index, classification error, and entropy in a simple classification setting with two classes. Create a single plotthat 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
p=seq(0,1,0.01)
gini= 2*p*(1-p)
classerror= 1-pmax(p,1-p)
crossentropy= -(p*log(p)+(1-p)*log(1-p))
plot(NA,NA,xlim=c(0,1),ylim=c(0,1),xlab='p',ylab='f')
lines(p,gini,type='l')
lines(p,classerror,col='blue')
lines(p,crossentropy,col='red')
legend(x='top',legend=c('gini','class error','cross entropy'),
col=c('black','blue','red'),lty=1,text.width = 0.22)
data("Carseats")
8a. Split data into a training and a test set.
set.seed(12)
inTrain = createDataPartition(Carseats$Sales, p = 0.7, list = FALSE)
train = Carseats[inTrain,]
test = Carseats[-inTrain,]
8b. Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
model.1 = tree(Sales ~., train)
summary(model.1)
##
## Regression tree:
## tree(formula = Sales ~ ., data = train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "CompPrice" "Age"
## Number of terminal nodes: 15
## Residual mean deviance: 2.656 = 706.4 / 266
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -6.025 -1.107 -0.012 0.000 1.190 4.607
plot(model.1)
text(model.1, pretty = 0)
The most important variables in the decision tree are shelveloc and price.
preds = predict(model.1, test)
mean((preds - test$Sales)^2)
## [1] 4.095362
The test MSE is 4.09
8c. Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
cv.tree.model = cv.tree(model.1)
plot(cv.tree.model$size,
cv.tree.model$dev,
type = "b",
xlab = "Tree Size",
ylab = "MSE")
which.min(cv.tree.model$dev)
## [1] 7
cv.tree.model$size[7]
## [1] 8
prune the tree to size 12
prune.model = prune.tree(model.1, best = 8)
plot(prune.model)
text(prune.model, pretty = 0 )
preds.prune = predict(prune.model, test)
mean((preds.prune - test$Sales)^2)
## [1] 4.63248
Pruning the tree increased the the MSE.
8d. 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.
set.seed(12)
bag.model = randomForest(Sales ~., data = train, mtry = 10, importance = TRUE)
importance(bag.model)
## %IncMSE IncNodePurity
## CompPrice 31.4080787 239.230365
## Income 5.0167583 97.269113
## Advertising 16.6538238 142.551868
## Population -0.2226358 72.183972
## Price 65.7997237 749.415383
## ShelveLoc 73.5154159 742.841775
## Age 18.0128163 177.772356
## Education 1.3211542 53.251851
## Urban -1.9878459 11.277518
## US 0.2413997 6.436934
varImpPlot(bag.model)
The variables that are most important are Price and SheleLoc
preds.3 = predict(bag.model, test)
mean((preds.3 - test$Sales)^2)
## [1] 2.293345
The test MSE for is 2.29. The bagging model has achieved the lowest MSE.
8e. 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(12)
rf.model = randomForest(Sales ~., data = train, importance =TRUE, mtry = sqrt(10))
importance(rf.model)
## %IncMSE IncNodePurity
## CompPrice 13.07278275 207.93180
## Income 3.42353043 165.83689
## Advertising 13.43996420 179.78457
## Population 0.08396205 151.57201
## Price 44.05610700 573.39168
## ShelveLoc 50.13142796 550.16246
## Age 15.74705935 256.71304
## Education 0.27689514 88.59211
## Urban -1.01833330 20.26719
## US 2.85927905 22.77852
varImpPlot(rf.model)
ShelveLoc and Price are the most important variables
preds.rf = predict(rf.model, test)
mean((preds.rf - test$Sales)^2)
## [1] 2.534537
The test MSE increased from the bagging model.
data("OJ")
9a. Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(12)
train.1 = sample(1:nrow(OJ), 800)
oj.train = OJ[train.1,]
oj.test = OJ[-train.1,]
9b. 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?
model.2 = tree(Purchase ~., oj.train)
summary(model.2)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "SalePriceMM" "PriceDiff" "ListPriceDiff"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7667 = 608 / 793
## Misclassification error rate: 0.1588 = 127 / 800
This model has 7 nodes and a misclassification of 15.88%
9c. 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.
#model.2
Denoted by the asterisk, we will look at terminal 10. The plot criterion is SalePriceMM < 2.01 and the number of observations is 125 with a deviance of 125.10. 0.20 of the observations in MM and .80 of the observations in MM.
9d. Create a plot of the tree, and interpret the results.
plot(model.2)
text(model.2,pretty=0)
we can see the LoyalCH is very important in predicting purchase. The left branch shows that when customer loyalty is low, people will buy Minute Made. In the right branch we can see that the more the customer is loyal, the more likely they are to stay with Citrus Hill.
9e.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?
preds.oj = predict(model.2, oj.test, type = "class")
table(preds.oj, oj.test$Purchase)
##
## preds.oj CH MM
## CH 129 15
## MM 36 90
(36 + 15)/(129 + 15 + 36 + 90)
## [1] 0.1888889
The error rate is 18.89%
10f Apply the cv.tree() function to the training set in order to determine the optimal tree size.
cv.tree.oj = cv.tree(model.2, FUN = prune.misclass)
cv.tree.oj
## $size
## [1] 7 5 2 1
##
## $dev
## [1] 154 152 160 312
##
## $k
## [1] -Inf 0.000000 7.333333 163.000000
##
## $method
## [1] "misclass"
##
## attr(,"class")
## [1] "prune" "tree.sequence"
10g.Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.
plot(cv.tree.oj$size, cv.tree.oj$dev, type = "b", xlab = "Tree size", ylab = "Deviance")
10h.Which tree size corresponds to the lowest cross-validated classification error rate?
which.min(cv.tree.oj$size)
## [1] 4
The tree size that has the lowest cross-validation rate is 4
10i.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.tree = prune.misclass(model.2, best = 4)
plot(oj.prune.tree)
text(oj.prune.tree,pretty=0)
10j.Compare the training error rates between the pruned and unpruned trees. Which is higher?
summary(model.2)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "SalePriceMM" "PriceDiff" "ListPriceDiff"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7667 = 608 / 793
## Misclassification error rate: 0.1588 = 127 / 800
summary(oj.prune.tree)
##
## Classification tree:
## snip.tree(tree = model.2, nodes = 2L)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff"
## Number of terminal nodes: 5
## Residual mean deviance: 0.8135 = 646.7 / 795
## Misclassification error rate: 0.1588 = 127 / 800
The misclassification error rate between the unpruned model and the pruned model are the same.
10k. Compare the test error rates between the pruned and unpruned trees. Which is higher?
preds.oj.2 = predict(oj.prune.tree, oj.test, type = "class")
table(preds.oj.2, oj.test$Purchase)
##
## preds.oj.2 CH MM
## CH 129 15
## MM 36 90
(36+15)/(129+15+36+90)
## [1] 0.1888889
The test error rate for the pruned tree is the same as the test error rate of the unpruned tree.