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.
# Generate P1 and P2
p1 <- seq(0, 1, length.out = 300)
p2 <- 1 - p1
# Calc Gini index
gini <- 1 - p1^2 - p2^2
entropy <- -p1*log2(p1) - p2*log2(p2)
entropy[is.nan(entropy)] <- 0
class_error <- 1 - pmax(p1, p2)
# Plot Result
plot(p1, gini, type = "l", col = "blue", lwd = 2,
ylim = c(0, 1), ylab = "Value", xlab = expression(hat(p)[m1]),
main = "Gini, Classification Error, and Entropy vs. p1")
lines(p1, class_error, col = "red", lwd = 2, lty = 2)
lines(p1, entropy, col = "darkgreen", lwd = 2, lty = 3)
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.
library(ISLR2)
library(tree)
library(randomForest)
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
library(BayesTree)
set.seed(1)
nRows <- nrow(Carseats)
TrainIndex <- sample(seq_len(nRows), size = 0.7 * nRows)
TrainingSet <- Carseats[ TrainIndex, ] # Train: 70%
TestSet <- Carseats[-TrainIndex, ] # Test: 30%
head(Carseats)
## Sales CompPrice Income Advertising Population Price ShelveLoc Age Education
## 1 9.50 138 73 11 276 120 Bad 42 17
## 2 11.22 111 48 16 260 83 Good 65 10
## 3 10.06 113 35 10 269 80 Medium 59 12
## 4 7.40 117 100 4 466 97 Medium 55 14
## 5 4.15 141 64 3 340 128 Bad 38 13
## 6 10.81 124 113 13 501 72 Bad 78 16
## Urban US
## 1 Yes Yes
## 2 Yes Yes
## 3 Yes Yes
## 4 Yes Yes
## 5 Yes No
## 6 No Yes
Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
Answer: Price is first Split variable. Leaves give the average Sales in each region of the predictor space. MSE is 4.208383
pairs(Carseats) # Check Coreloation
# Fit Regression Tree
RegressionTreeModel <- tree(Sales ~ CompPrice + Income + Advertising + Price + ShelveLoc + Age + Education + Urban + US, data = TrainingSet)
# Plot the tree
plot(RegressionTreeModel)
text(RegressionTreeModel, pretty = 0)
# Predict on test set
TreePredictions <- predict(RegressionTreeModel, newdata = TestSet)
# Calc Mean
TreeTestMSE <- mean((TreePredictions - TestSet$Sales)^2)
TreeTestMSE
## [1] 4.208383
Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE? The MSE with Pruning does not improve than orig one
CVTree <- cv.tree(RegressionTreeModel)
# Plot Result
plot(CVTree$size, CVTree$dev, type = "b",
xlab = "Tree Size",
ylab = "Deviance")
# Find best size and prune
OptimalSize <- CVTree$size[which.min(CVTree$dev)]
PrunedTree <- prune.tree(RegressionTreeModel, best = OptimalSize)
# Plot pruned tree
plot(PrunedTree)
text(PrunedTree, pretty = 0)
# Compute test MSE for pruned tree
PrunedPredictions <- predict(PrunedTree, newdata = TestSet)
PrunedTestMSE <- mean((PrunedPredictions - TestSet$Sales)^2)
PrunedTestMSE
## [1] 4.208383
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.
** MSE is 2.573252. Price is most important.**
# Number of predictors
NumPredictors <- ncol(TrainingSet) - 1
set.seed(1)
# Fit bagging model
BaggingModel <- randomForest(Sales ~ ., data = TrainingSet, mtry = NumPredictors, importance = TRUE)
# Test MSE
BaggingPredictions <- predict(BaggingModel, newdata = TestSet)
BaggingTestMSE <- mean((BaggingPredictions - TestSet$Sales)^2)
cat(sprintf("\n>> MSE of the bagging approach: %f\n\n", BaggingTestMSE))
##
## >> MSE of the bagging approach: 2.573252
# Variable importance
BaggingImportance <- importance(BaggingModel)
BaggingImportance
## %IncMSE IncNodePurity
## CompPrice 35.324343 230.55353
## Income 7.923790 118.79213
## Advertising 19.736816 155.03099
## Population -3.479681 63.11975
## Price 70.613500 673.11982
## ShelveLoc 68.147204 637.69500
## Age 20.964215 228.90345
## Education 4.705263 63.13124
## Urban -2.098091 11.66651
## US 1.389570 11.15329
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 ofvariables considered at each split, on the error rateobtained.
Answer: MSE is 2.916397. Price is most important. As the value of m increases, the test MSE decreases.
# Fit a default random forest (mtry = sqrt of p)
set.seed(1)
# Random Forest
DefaultRF <- randomForest(Sales ~ ., data = TrainingSet, mtry = floor(sqrt(NumPredictors)), importance = TRUE)
# Calc MSE
RFPredictions <- predict(DefaultRF, newdata = TestSet)
RFTestMSE <- mean((RFPredictions - TestSet$Sales)^2)
cat(sprintf("\n>> MSE of the Random Forest: %f\n\n", RFTestMSE))
##
## >> MSE of the Random Forest: 2.916397
# Variable importance
RFImportance <- importance(DefaultRF)
varImpPlot(DefaultRF)
# Effect of mtry on error
MtryValues <- c(1, floor(NumPredictors/3), floor(NumPredictors/2), NumPredictors)
MSEbyMtry <- sapply(MtryValues, function(m) {
rf <- randomForest(Sales ~ ., data = TrainingSet, mtry = m)
mean((predict(rf, TestSet) - TestSet$Sales)^2)
})
data.frame(Mtry = MtryValues, TestMSE = MSEbyMtry)
## Mtry TestMSE
## 1 1 4.475980
## 2 3 2.869746
## 3 5 2.563764
## 4 10 2.573084
Now analyze the data using BART, and report your results.
MES of BART is 1.442571. It is best MSE valuse.
# Prepare model matrices
X_train <- model.matrix(Sales ~ . -1, data = TrainingSet)
Y_train <- TrainingSet$Sales
X_test <- model.matrix(Sales ~ . -1, data = TestSet)
# Fit BART model
set.seed(42)
BARTModel <- bart(x.train = X_train, y.train = Y_train, x.test = X_test)
##
##
## Running BART with numeric y
##
## number of trees: 200
## Prior:
## k: 2.000000
## degrees of freedom in sigma prior: 3
## quantile in sigma prior: 0.900000
## power and base for tree prior: 2.000000 0.950000
## use quantiles for rule cut points: 0
## data:
## number of training observations: 280
## number of test observations: 120
## number of explanatory variables: 12
##
##
## Cutoff rules c in x<=c vs x>c
## Number of cutoffs: (var: number of possible c):
## (1: 100) (2: 100) (3: 100) (4: 100) (5: 100)
## (6: 100) (7: 100) (8: 100) (9: 100) (10: 100)
## (11: 100) (12: 100)
##
##
## Running mcmc loop:
## iteration: 100 (of 1100)
## iteration: 200 (of 1100)
## iteration: 300 (of 1100)
## iteration: 400 (of 1100)
## iteration: 500 (of 1100)
## iteration: 600 (of 1100)
## iteration: 700 (of 1100)
## iteration: 800 (of 1100)
## iteration: 900 (of 1100)
## iteration: 1000 (of 1100)
## iteration: 1100 (of 1100)
## time for loop: 4
##
## Tree sizes, last iteration:
## 4 1 3 2 2 3 3 2 1 2 3 2 4 2 3 3 2 4 2 2
## 2 4 2 2 4 2 2 3 2 2 2 4 2 2 2 3 2 2 3 2
## 2 2 2 2 3 2 2 3 3 3 2 3 3 3 3 2 2 2 3 2
## 2 3 2 3 3 1 1 2 2 2 2 3 3 3 3 2 3 2 2 2
## 2 3 3 4 2 3 2 2 3 3 5 2 2 2 3 2 1 3 5 3
## 4 3 1 2 3 2 2 3 2 2 3 1 2 3 3 2 3 6 2 2
## 2 2 2 2 2 3 2 2 2 2 3 2 1 3 4 3 2 4 2 4
## 2 2 2 2 3 2 2 2 2 1 2 3 2 3 3 4 2 1 2 2
## 3 2 2 3 2 2 3 3 3 2 1 3 2 2 2 4 3 2 2 2
## 3 2 2 2 4 2 1 2 1 2 2 2 2 2 3 3 4 2 2 2
## Variable Usage, last iteration (var:count):
## (1: 35) (2: 27) (3: 24) (4: 28) (5: 29)
## (6: 20) (7: 25) (8: 15) (9: 20) (10: 19)
## (11: 15) (12: 29)
## DONE BART 11-2-2014
# Calc MSE
BARTPredictions <- BARTModel$yhat.test.mean
BARTTestMSE <- mean((BARTPredictions - TestSet$Sales)^2)
cat(sprintf("\n>> MSE of the BART: %f\n\n", BARTTestMSE))
##
## >> MSE of the BART: 1.442571
This problem involves the OJ data set which is part of the ISLR2 package.
Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
library(ISLR2)
library(tree)
set.seed(1)
# Sample 800 rows for training set
TrainIndex <- sample(1:nrow(OJ), 800)
OJTrain <- OJ[TrainIndex, ]
OJTest <- OJ[-TrainIndex, ]
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?
The training error rate is 15.88%. The tree has 9 terminal nodes
# Fit classification tree
OJTree <- tree(Purchase ~ ., data = OJTrain)
# Summary of the tree
summary(OJTree)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = OJTrain)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "SpecialCH" "ListPriceDiff"
## [5] "PctDiscMM"
## Number of terminal nodes: 9
## Residual mean deviance: 0.7432 = 587.8 / 791
## Misclassification error rate: 0.1588 = 127 / 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. Answer: Node 8 predicts MM, with a very high confidence (MM probability = 0.983).
OJTree
## node), split, n, deviance, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 1073.00 CH ( 0.60625 0.39375 )
## 2) LoyalCH < 0.5036 365 441.60 MM ( 0.29315 0.70685 )
## 4) LoyalCH < 0.280875 177 140.50 MM ( 0.13559 0.86441 )
## 8) LoyalCH < 0.0356415 59 10.14 MM ( 0.01695 0.98305 ) *
## 9) LoyalCH > 0.0356415 118 116.40 MM ( 0.19492 0.80508 ) *
## 5) LoyalCH > 0.280875 188 258.00 MM ( 0.44149 0.55851 )
## 10) PriceDiff < 0.05 79 84.79 MM ( 0.22785 0.77215 )
## 20) SpecialCH < 0.5 64 51.98 MM ( 0.14062 0.85938 ) *
## 21) SpecialCH > 0.5 15 20.19 CH ( 0.60000 0.40000 ) *
## 11) PriceDiff > 0.05 109 147.00 CH ( 0.59633 0.40367 ) *
## 3) LoyalCH > 0.5036 435 337.90 CH ( 0.86897 0.13103 )
## 6) LoyalCH < 0.764572 174 201.00 CH ( 0.73563 0.26437 )
## 12) ListPriceDiff < 0.235 72 99.81 MM ( 0.50000 0.50000 )
## 24) PctDiscMM < 0.196196 55 73.14 CH ( 0.61818 0.38182 ) *
## 25) PctDiscMM > 0.196196 17 12.32 MM ( 0.11765 0.88235 ) *
## 13) ListPriceDiff > 0.235 102 65.43 CH ( 0.90196 0.09804 ) *
## 7) LoyalCH > 0.764572 261 91.20 CH ( 0.95785 0.04215 ) *
Create a plot of the tree, and interpret the results. LoyalCH is first Split. The tree splits based on variables like LoyalCH and PriceDiff.
# Plot the tree structure
plot(OJTree)
text(OJTree, pretty = 0)
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? The error rate is 17.04%.
# Predict on test set
PredictedTest <- predict(OJTree, newdata = OJTest, type = "class")
# Confusion matrix
ConfMatrix <- table(PredictedTest, OJTest$Purchase)
ConfMatrix
##
## PredictedTest CH MM
## CH 160 38
## MM 8 64
# Test error rate
TestErrorRate <- mean(PredictedTest != OJTest$Purchase)
TestErrorRate
## [1] 0.1703704
Apply the cv.tree() function to the training set in order to determine the optimal tree size.
# Cross-validation for tree pruning
CVTree <- cv.tree(OJTree, FUN = prune.misclass)
# cross-validation results
CVTree
## $size
## [1] 9 8 7 4 2 1
##
## $dev
## [1] 150 150 149 158 172 315
##
## $k
## [1] -Inf 0.000000 3.000000 4.333333 10.500000 151.000000
##
## $method
## [1] "misclass"
##
## attr(,"class")
## [1] "prune" "tree.sequence"
Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.
# Plot tree size vs. CV error rate
plot(CVTree$size, CVTree$dev, type = "b",
xlab = "Tree Size (Number of Terminal Nodes)",
ylab = "CV Classification Error Rate",
main = "Optimal Tree Size")
Which tree size corresponds to the lowest cross-validated classification error rate? Answer: 7
# Find optimal tree size
OptimalTreeSize <- CVTree$size[which.min(CVTree$dev)]
OptimalTreeSize
## [1] 7
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 tree to optimal size
PrunedOJTree <- prune.misclass(OJTree, best = OptimalTreeSize)
# Plot pruned tree
plot(PrunedOJTree)
text(PrunedOJTree, pretty = 0)
Answer: Pruned is higher
# Training predictions
PredTrainUnpruned <- predict(OJTree, type = "class")
TrainErrUnpruned <- mean(PredTrainUnpruned != OJTrain$Purchase)
PredTrainPruned <- predict(PrunedOJTree, type = "class")
TrainErrPruned <- mean(PredTrainPruned != OJTrain$Purchase)
TrainErrUnpruned
## [1] 0.15875
TrainErrPruned
## [1] 0.1625
Answer: Unpurned is higher
# Test predictions
PredTestUnpruned <- predict(OJTree, newdata = OJTest, type = "class")
TestErrUnpruned <- mean(PredTestUnpruned != OJTest$Purchase)
PredTestPruned <- predict(PrunedOJTree, newdata = OJTest, type = "class")
TestErrPruned <- mean(PredTestPruned != OJTest$Purchase)
TestErrUnpruned
## [1] 0.1703704
TestErrPruned
## [1] 0.162963