Consider the Gini index, classification error, and cross-entropy in a simple classification setting with two classes. Create a single plot that displays each of these quantities as a function of \(\hat{p}_{m1}\). The \(x\)-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, length.out = 200)
data.frame(
x = p,
"Gini Index" = p * (1 - p) * 2,
"Entropy" = -(p * log(p) + (1 - p) * log(1 - p)),
"Error" = 1 - pmax(p, 1 - p),
check.names = FALSE
) |>
pivot_longer(!x) |>
ggplot(aes(x = x, y = value, color = name)) +
geom_line(na.rm = TRUE)
In the lab, a classification tree was applied to the
Carseatsdata set after convertingSalesinto a qualitative response variable. Now we will seek to predictSalesusing regression trees and related approaches, treating the response as a quantitative variable.
- Split the data set into a training set and a test set.
set.seed(42)
train <- sample(c(TRUE, FALSE), nrow(Carseats), replace = TRUE)
- Fit a regression tree to the training set. Plot the tree, and interpret the results. What test error rate do you obtain?
library(tree)
tr <- tree(Sales ~ ., data = Carseats[train, ])
summary(tr)
##
## Regression tree:
## tree(formula = Sales ~ ., data = Carseats[train, ])
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "Income" "Advertising" "CompPrice"
## [6] "Age"
## Number of terminal nodes: 16
## Residual mean deviance: 2.356 = 424.1 / 180
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -4.54900 -0.82980 0.03075 0.00000 0.89250 4.83100
plot(tr)
text(tr, pretty = 0, digits = 2, cex = 0.8)
carseats_mse <- function(model) {
p <- predict(model, newdata = Carseats[!train, ])
mean((p - Carseats[!train, "Sales"])^2)
}
carseats_mse(tr)
## [1] 4.559764
- Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test error rate?
res <- cv.tree(tr)
plot(res$size, res$dev, type = "b", xlab = "Tree size", ylab = "Deviance")
min <- which.min(res$dev)
abline(v = res$size[min], lty = 2, col = "red")
Pruning improves performance very slightly (though this is not repeatable in different rounds of cross-validation). Arguably, a good balance is achieved when the tree size is 11.
ptr <- prune.tree(tr, best = 11)
plot(ptr)
text(ptr, pretty = 0, digits = 2, cex = 0.8)
carseats_mse(ptr)
## [1] 4.625875
- Use the bagging approach in order to analyze this data. What test error rate do you obtain? Use the
importance()function to determine which variables are most important.
# Here we can use random Forest with mtry = 10 = p (the number of predictor
# variables) to perform bagging
bagged <- randomForest(Sales ~ .,
data = Carseats[train, ], mtry = 10,
ntree = 200, importance = TRUE
)
carseats_mse(bagged)
## [1] 2.817206
importance(bagged)
## %IncMSE IncNodePurity
## CompPrice 8.2970627 98.312231
## Income 4.6957454 76.226936
## Advertising 12.1075097 132.852681
## Population 4.0844033 59.771960
## Price 35.2997951 445.388522
## ShelveLoc 35.8777698 374.984663
## Age 8.8264739 146.004305
## Education -0.3138546 33.929961
## Urban 0.3881661 7.082776
## US 2.6158020 6.413648
The test error rate is ~2.8 which is a substantial improvement over the pruned regression tree above.
- Use random forests to analyze this data. What test error rate 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 <- randomForest(Sales ~ .,
data = Carseats[train, ], mtry = 3,
ntree = 500, importance = TRUE
)
carseats_mse(rf)
## [1] 3.470226
importance(rf)
## %IncMSE IncNodePurity
## CompPrice 11.7883412 119.64651
## Income 4.2893733 113.40215
## Advertising 14.9694831 125.44317
## Population 1.6258038 104.84474
## Price 33.0534342 339.54276
## ShelveLoc 41.6438226 306.61977
## Age 9.6425759 142.10949
## Education -0.1060637 66.02581
## Urban 0.5022826 13.35025
## US 5.0858693 22.10218
The test error rate is ~3.0 which is a substantial improvement over the pruned regression tree above, although not quite as good as the bagging approach.
- Now analyze the data using BART, and report your results.
library(BART)
## Loading required package: nlme
##
## Attaching package: 'nlme'
## The following object is masked from 'package:ggtree':
##
## collapse
## The following object is masked from 'package:dplyr':
##
## collapse
## Loading required package: survival
# For ease, we'll create a fake "predict" method that just returns
# yhat.test.mean regardless of provided "newdata"
predict.wbart <- function(model, ...) model$yhat.test.mean
bartfit <- gbart(Carseats[train, 2:11], Carseats[train, 1],
x.test = Carseats[!train, 2:11]
)
## *****Calling gbart: type=1
## *****Data:
## data:n,p,np: 196, 14, 204
## y1,yn: 2.070867, 2.280867
## x1,x[n*p]: 138.000000, 1.000000
## xp1,xp[np*p]: 141.000000, 1.000000
## *****Number of Trees: 200
## *****Number of Cut Points: 58 ... 1
## *****burn,nd,thin: 100,1000,1
## *****Prior:beta,alpha,tau,nu,lambda,offset: 2,0.95,0.287616,3,0.21118,7.42913
## *****sigma: 1.041218
## *****w (weights): 1.000000 ... 1.000000
## *****Dirichlet:sparse,theta,omega,a,b,rho,augment: 0,0,1,0.5,1,14,0
## *****printevery: 100
##
## MCMC
## done 0 (out of 1100)
## done 100 (out of 1100)
## done 200 (out of 1100)
## done 300 (out of 1100)
## done 400 (out of 1100)
## done 500 (out of 1100)
## done 600 (out of 1100)
## done 700 (out of 1100)
## done 800 (out of 1100)
## done 900 (out of 1100)
## done 1000 (out of 1100)
## time: 2s
## trcnt,tecnt: 1000,1000
carseats_mse(bartfit)
## [1] 1.605435
The test error rate is ~1.6 which is an improvement over random forest and bagging.
This problem involves the
OJdata set which is part of theISLR2package.
- Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(42)
train <- sample(1:nrow(OJ), 800)
test <- setdiff(1:nrow(OJ), train)
- Fit a tree to the training data, with
Purchaseas the response and the other variables except forBuyas predictors. Use thesummary()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?
tr <- tree(Purchase ~ ., data = OJ[train, ])
summary(tr)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ[train, ])
## Variables actually used in tree construction:
## [1] "LoyalCH" "SalePriceMM" "PriceDiff"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7392 = 585.5 / 792
## Misclassification error rate: 0.1638 = 131 / 800
- 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.
tr
## node), split, n, deviance, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 1066.00 CH ( 0.61500 0.38500 )
## 2) LoyalCH < 0.48285 285 296.00 MM ( 0.21404 0.78596 )
## 4) LoyalCH < 0.064156 64 0.00 MM ( 0.00000 1.00000 ) *
## 5) LoyalCH > 0.064156 221 260.40 MM ( 0.27602 0.72398 )
## 10) SalePriceMM < 2.04 128 123.50 MM ( 0.18750 0.81250 ) *
## 11) SalePriceMM > 2.04 93 125.00 MM ( 0.39785 0.60215 ) *
## 3) LoyalCH > 0.48285 515 458.10 CH ( 0.83689 0.16311 )
## 6) LoyalCH < 0.753545 230 282.70 CH ( 0.69565 0.30435 )
## 12) PriceDiff < 0.265 149 203.00 CH ( 0.57718 0.42282 )
## 24) PriceDiff < -0.165 32 38.02 MM ( 0.28125 0.71875 ) *
## 25) PriceDiff > -0.165 117 150.30 CH ( 0.65812 0.34188 )
## 50) LoyalCH < 0.703993 105 139.60 CH ( 0.61905 0.38095 ) *
## 51) LoyalCH > 0.703993 12 0.00 CH ( 1.00000 0.00000 ) *
## 13) PriceDiff > 0.265 81 47.66 CH ( 0.91358 0.08642 ) *
## 7) LoyalCH > 0.753545 285 111.70 CH ( 0.95088 0.04912 ) *
- Create a plot of the tree, and interpret the results.
plot(tr)
text(tr, pretty = 0, digits = 2, cex = 0.8)
- 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?
table(predict(tr, OJ[test, ], type = "class"), OJ[test, "Purchase"])
##
## CH MM
## CH 125 15
## MM 36 94
- Apply the
cv.tree()function to the training set in order to determine the optimal tree size.
set.seed(42)
res <- cv.tree(tr)
- Produce a plot with tree size on the \(x\)-axis and cross-validated classification error rate on the \(y\)-axis.
plot(res$size, res$dev, type = "b", xlab = "Tree size", ylab = "Deviance")
min <- which.min(res$dev)
abline(v = res$size[min], lty = 2, col = "red")
- Which tree size corresponds to the lowest cross-validated classification error rate?
res$size[min]
## [1] 6
- 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.
ptr <- prune.tree(tr, best = res$size[min])
plot(ptr)
text(ptr, pretty = 0, digits = 2, cex = 0.8)
- Compare the training error rates between the pruned and unpruned trees. Which is higher?
oj_misclass <- function(model) {
summary(model)$misclass[1] / summary(model)$misclass[2]
}
oj_misclass(tr)
## [1] 0.16375
oj_misclass(ptr)
## [1] 0.16375
The training misclassification error rate is slightly higher for the pruned tree.
- Compare the test error rates between the pruned and unpruned trees. Which is higher?
oj_err <- function(model) {
p <- predict(model, newdata = OJ[test, ], type = "class")
mean(p != OJ[test, "Purchase"])
}
oj_err(tr)
## [1] 0.1888889
oj_err(ptr)
## [1] 0.1888889
The test misclassification error rate is slightly higher for the pruned tree.