library(ggplot2) # graphics library
library(ISLR) # contains code and data from the textbook
library(knitr) # contains kable() function
library(tree) # For the tree-fitting 'tree' function
library(rpart) # For nicer tree fitting
library(partykit) # For nicer tree plotting
## Loading required package: grid
library(MASS) # For Boston data
options(scipen = 4) # Suppresses scientific notation
You will need the
Carseats
data set from theISLR
library in order to complete this exercise.
Please run all of the code indicated in §8.3.1 of ISLR, even if I don’t explicitly ask you to do so in this document.
View()
command on the Carseats
data to see what the data set looks like.#View(Carseats)
High
variable for the purpose of classification. Our goal will be to classify whether Carseat sales in a store are high or not.High <- with(Carseats, ifelse(Sales <= 8, "No", "Yes"))
Carseats <- data.frame(Carseats, High)
# Edit me
tree
command to fit a decision tree to every other variable in the Carseats
data other than Sales
. Run summary
on your tree object. Run the plot
and text
commands on your tree object.# Edit me
# Edit me
# Edit me
plot
. (You do not need to write down an answer)# Edit me
*
at the end mean? How many High = yes
observations are there at this node?18) Population < 207.5 16 21.170 Yes ( 0.37500 0.62500 ) *
tree.carseats
model to just the training data.set.seed(2)
train <- sample(1:nrow(Carseats), 200)
Carseats.test <- Carseats[-train,]
High.test <- High[-train]
tree.carseats <- tree(High~.-Sales,Carseats,subset=train)
tree.pred <- predict(tree.carseats,Carseats.test,type="class")
table(tree.pred,High.test)
## High.test
## tree.pred No Yes
## No 86 27
## Yes 30 57
cv.tree
command to produce an object called cv.carseats
by carrying out 10-Fold Cross-Validation pruning on tree.subsets
. You’ll need to supply FUN = prune.misclass
as an argument to ensure that the error metric is taken to be the number of misclassifications instead of the deviance.# Edit me
# par(mfrow = c(1,2))
# plot(cv.carseats$size, cv.carseats$dev, type="b")
# plot(cv.carseats$k, cv.carseats$dev, type="b")
prune.misclass
command to prune tree.carseats
down to the subtree that has the lowest CV error. Plot this tree, and overlay text. Compare the variables that get used in this tree compared to those that get used in the unpruned tree. Does the pruned tree wind up using fewer variables?# Edit me
# tree.pred <- predict(prune.carseats, Carseats.test, type="class")
# confusion.pred <- table(tree.pred, High.test)
# confusion.pred
# Edit me
rpart
command instead of tree
. This results in a fit that can be converted into a party
object, and plotted in a more aesthetically pleasing way. The code below illustrates how to perform this conversion and how to get a tree out of it. There are some accompanying questions below the code.# Fit a decision tree using rpart
# Note: when you fit a tree using rpart, the fitting routine automatically
# performs 10-fold CV and stores the errors for later use
# (such as for pruning the tree)
carseats.rpart <- rpart(High ~ . -Sales , Carseats, method="class", subset=train)
# Plot the CV error curve for the tree
plotcp(carseats.rpart)
# Identify the value of the complexity parameter that produces
# the lowest CV error
cp.min <- carseats.rpart$cptable[which.min(carseats.rpart$cptable[,"xerror"]),"CP"]
# Prune using the CV error minimizing choice of the complexity parameter cp
carseats.rpart.pruned <- prune(carseats.rpart, cp = cp.min)
# Convert pruned tree to a party object
carseats.party <- as.party(carseats.rpart.pruned)
# Plot
plot(carseats.party)
These questions prompt you to follow along with §8.3.2 in ISL. We’ll once again be working with the
Boston
data set.
set.seed(1)
train <- sample(1:nrow(Boston), nrow(Boston)/2)
tree.boston <- tree(medv ~ . ,Boston,subset=train)
summary(tree.boston)
##
## Regression tree:
## tree(formula = medv ~ ., data = Boston, subset = train)
## Variables actually used in tree construction:
## [1] "lstat" "rm" "dis"
## Number of terminal nodes: 8
## Residual mean deviance: 12.65 = 3099 / 245
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -14.10000 -2.04200 -0.05357 0.00000 1.96000 12.60000
plot(tree.boston)
text(tree.boston, pretty=0)
set.seed(2)
for(i in 1:10) {
train.b <- sample(1:nrow(Boston), nrow(Boston)/2)
tree.boston.b <- tree(medv ~ . , Boston, subset=train.b)
print(as.character(summary(tree.boston.b)$used))
}
## [1] "lstat" "rm" "dis" "nox" "crim"
## [1] "lstat" "rm" "dis" "nox" "crim"
## [1] "rm" "lstat" "crim" "ptratio"
## [1] "rm" "lstat" "age" "crim"
## [1] "lstat" "rm" "dis" "ptratio" "nox" "crim"
## [1] "lstat" "rm" "nox"
## [1] "lstat" "rm" "ptratio" "tax" "nox"
## [1] "lstat" "rm" "dis" "indus" "nox" "crim"
## [1] "lstat" "rm" "dis" "age" "crim"
## [1] "rm" "lstat" "dis"
dev
stands for “deviance”, which is the same as MSE for regression (prediction) problems.# Run CV to find best level at which to prune
cv.boston <- cv.tree(tree.boston)
# Construct a plot (dev = MSE on y-axis)
plot(cv.boston$size,cv.boston$dev,type='b')
# Prune the tree, display pruned tree
prune.boston <- prune.tree(tree.boston,best=5)
plot(prune.boston)
text(prune.boston,pretty=0)
# Get predictions from pruned tree
yhat.tree <- predict(tree.boston, newdata=Boston[-train,])
boston.test <- Boston[-train,"medv"]
# Construct plot of observed values (x-axis) vs predicted values (y-axis)
plot(yhat.tree, boston.test)
# Add a diagonal line
abline(0, 1)
# Calculate test set MSE
mean((yhat.tree-boston.test)^2)
## [1] 25.04559