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.
p_m1 <- seq(0, 1, 0.01)
gini <- p_m1 * (1 - p_m1) * 2
entropy <- -(p_m1 * log(p_m1) + (1 - p_m1) * log(1 - p_m1))
class.err <- 1 - pmax(p_m1, 1 - p_m1)
df = data.frame(p_m1 = p_m1, gini = gini, entropy = entropy, class.err = class.err)
df_long=gather(df, key = "variable", value = "value", -p_m1)
ggplot(df_long, aes(x = p_m1, y = value, color = variable)) +
geom_line() +
scale_color_manual(values = c("blue", "black", "red")) +
labs(x = "pm1", y = "Error", title = "Error vs. Probability")
### PROBLEM 8
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.
- Split the data set into a training set and a test set.
set.seed(1)
Carseat1 = as.data.frame(Carseats)
Carseat1$id <- 1:nrow(Carseat1)
#75% used as training
train <- Carseat1 %>% dplyr::sample_frac(0.75)
test <- dplyr::anti_join(Carseat1, train, by = 'id')
- Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
tree.carseats = tree(Sales ~., data = train)
summary(tree.carseats)
##
## Regression tree:
## tree(formula = Sales ~ ., data = train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "Age" "Income" "CompPrice"
## [6] "Advertising"
## Number of terminal nodes: 17
## Residual mean deviance: 2.411 = 682.4 / 283
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -5.0760 -0.9920 -0.0225 0.0000 1.0250 3.5930
plot(tree.carseats)
text(tree.carseats, pretty = 0)
pred.carseats = predict(tree.carseats, test)
mean((test$Sales - pred.carseats)^2)
## [1] 4.910268
MSE is 4.9103
- Use CV to determine the optimal level of tree complexity. Does pruning improve the test MSE?
cv.carseats = cv.tree(tree.carseats, FUN = prune.tree)
par(mfrow = c(1,2))
plot(cv.carseats$size, cv.carseats$dev, type = "b")
plot(cv.carseats$k, cv.carseats$dev, type = "b")
prunecarseat = prune.tree(tree.carseats, best = 11)
par(mfrow = c(1,1))
plot(prunecarseat)
text(prunecarseat, pretty = 0)
pred.pruned = predict(prunecarseat, test)
mean((test$Sales - pred.pruned)^2)
## [1] 5.236696
test MSE increased from 4.9103 to 5.2367
- 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(1)
bag_seats = randomForest(Sales ~., data = train, mtry = 10, ntree = 500,
importance = T)
bag_pred = predict(bag_seats, test)
mean((test$Sales - bag_pred)^2)
## [1] 2.934259
importance(bag_seats)
## %IncMSE IncNodePurity
## CompPrice 33.351963 219.34986
## Income 8.432082 116.64953
## Advertising 19.956345 165.94762
## Population -3.063205 64.12733
## Price 72.234733 678.42019
## ShelveLoc 78.870780 689.01439
## Age 26.848631 240.69414
## Education 2.539456 54.35227
## Urban -1.500024 10.59890
## US 2.898631 12.07578
## id 1.411834 82.25598
varImpPlot(bag_seats)
Bagging seemed to work well, improving the MSE to 2.9343.
When using the importance function we can see it return
the variabels ShelveLoc, Price, and Age and the 3 most important.
- Use random forests to analyze this data. What test MSE do you obtain? Use the
importance()function to determine which variables are the most important. Describe the effect of m, the number of variables considered at ea split, on the error rate obtained.
set.seed(1)
rfseats_5 = randomForest(Sales ~., data = train, mtry = 5, ntree = 500, importance = TRUE)
rfseats_3 = randomForest(Sales ~., data = train, mtry = 3, ntree = 500, importance = TRUE)
rf_pred = predict(rfseats_5, test)
mean((test$Sales - rf_pred)^2)
## [1] 2.873991
importance(rfseats_5)
## %IncMSE IncNodePurity
## CompPrice 24.449695 204.65554
## Income 6.030735 142.90546
## Advertising 16.465910 164.43011
## Population -1.341464 100.70538
## Price 55.220510 597.72000
## ShelveLoc 61.794228 606.96091
## Age 20.458955 253.03220
## Education 1.976336 70.67067
## Urban -1.494537 14.64024
## US 4.704765 23.54904
## id 3.024552 119.35342
par(mfrow = c(1,4))
varImpPlot(rfseats_5)
rf_pred = predict(rfseats_3, test)
mean((test$Sales - rf_pred)^2)
## [1] 3.216692
importance(rfseats_3)
## %IncMSE IncNodePurity
## CompPrice 16.8872024 194.55784
## Income 5.9002735 158.36698
## Advertising 12.1084746 175.14621
## Population -1.4516209 130.34421
## Price 43.9594891 544.80758
## ShelveLoc 47.5473675 507.33506
## Age 16.5073412 263.07407
## Education 0.4317667 87.54421
## Urban -2.5976990 19.59042
## US 1.8101526 28.03173
## id 2.3821924 151.97785
varImpPlot(rfseats_3)
With mtry = 5 we return a value of 2.8740 With mtry = 3 we return a value of 3.2167
The same variables (ShelveLoc, Price, Age) are the most important. Interestingly enough however Price overtakes ShelveLoc when mtry=3.
In conclusion, the random forest method with mtry=5 seems to return the best result with bagging second.
- Now analyze the data using BART, and report your results.
library(BART)
xtrain <- train[, 1:10]
ytrain <- train$Sales
xtest <- test[, 1:10]
bart.ft <- gbart(xtrain, ytrain, x.test = xtest)
## *****Calling gbart: type=1
## *****Data:
## data:n,p,np: 300, 13, 100
## y1,yn: 2.720100, 1.220100
## x1,x[n*p]: 10.360000, 1.000000
## xp1,xp[np*p]: 10.060000, 1.000000
## *****Number of Trees: 200
## *****Number of Cut Points: 100 ... 1
## *****burn,nd,thin: 100,1000,1
## *****Prior:beta,alpha,tau,nu,lambda,offset: 2,0.95,0.276302,3,8.49132e-30,7.6399
## *****sigma: 0.000000
## *****w (weights): 1.000000 ... 1.000000
## *****Dirichlet:sparse,theta,omega,a,b,rho,augment: 0,0,1,0.5,1,13,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
summary(bart.ft)
## Length Class Mode
## sigma 1100 -none- numeric
## yhat.train 300000 -none- numeric
## yhat.test 100000 -none- numeric
## varcount 13000 -none- numeric
## varprob 13000 -none- numeric
## treedraws 2 -none- list
## proc.time 5 proc_time numeric
## hostname 1 -none- logical
## yhat.train.mean 300 -none- numeric
## sigma.mean 1 -none- numeric
## LPML 1 -none- numeric
## yhat.test.mean 100 -none- numeric
## ndpost 1 -none- numeric
## offset 1 -none- numeric
## varcount.mean 13 -none- numeric
## varprob.mean 13 -none- numeric
## rm.const 13 -none- numeric
bart_pred = bart.ft$yhat.test.mean
MSEbart = mean((bart_pred - test$Sales)^2)
MSEbart
## [1] 0.1107504
Using the BART method we result in an MSE of .1108 which
is ridiculously low. This is now the best method by a long shot.
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.
set.seed(1)
Default = as.data.frame(OJ)
Default$id <- 1:nrow(Default)
train <- Default %>% dplyr::sample_frac(0.748)
test <- dplyr::anti_join(Default, train, by = 'id')
dim(train)
## [1] 800 19
dim(test)
## [1] 270 19
- Fit a tree to the training data, with
Purchaseas the response and the other variables as 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?
ojtree = tree(Purchase ~., data = train)
summary(ojtree)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "SpecialCH" "ListPriceDiff"
## [5] "PctDiscMM" "id"
## Number of terminal nodes: 10
## Residual mean deviance: 0.7286 = 575.6 / 790
## Misclassification error rate: 0.1588 = 127 / 800
The Error rate is calculated as .1588, and the terminal nodes are listed as:
“LoyalCH” “PriceDiff” “SpecialCH” “ListPriceDiff” “PctDiscMM” “id”
- 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.
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 )
## 48) id < 267 11 0.00 CH ( 1.00000 0.00000 ) *
## 49) id > 267 44 60.91 CH ( 0.52273 0.47727 ) *
## 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 ) *
I’ll pick node 4. The splitting variable is “LoyalCH” with a value of .280875. There are 177 points below this node. The deviance for the points is 140.50.
- Create a plot of the tree, and interpret the results.
plot(ojtree)
text(ojtree, pretty = 0)
“LoyalCH” shows high importance in the model.
- Predict the response on the data, and produce a confusion matrix comparing the test labels to predict test labels. What is the test error rate?
ojpred = predict(ojtree, test, type = "class")
table(test$Purchase, ojpred)
## ojpred
## CH MM
## CH 160 8
## MM 38 64
total.preds <- sum(table(test$Purchase, ojpred))
incorrect.preds <- total.preds - sum(diag(table(test$Purchase, ojpred)))
oj_error_rate <- incorrect.preds / total.preds
oj_error_rate
## [1] 0.1703704
The returned error rate is .1704
- Apply the cv.tree() function to the training set in order to determine the optimal tree size.
cv.oj = cv.tree(ojtree, FUN = prune.tree)
cv.oj
## $size
## [1] 10 9 8 7 6 5 4 3 2 1
##
## $dev
## [1] 704.9056 723.2379 723.4760 715.7605 715.7605 714.1093 725.4734
## [8] 780.2099 790.0301 1074.2062
##
## $k
## [1] -Inf 12.23818 12.62207 13.94616 14.35384 26.21539 35.74964
## [8] 43.07317 45.67120 293.15784
##
## $method
## [1] "deviance"
##
## 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(cv.oj$size, cv.oj$dev, type = "b", xlab = "Size", ylab = "Deviance")
- Which tree size corresponds to the lowest cross-validated classification error rate?
Size 5 seems like the best tree to choose.
- 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.pruned = prune.tree(ojtree, best = 5)
plot(oj.pruned)
text(oj.pruned, pretty = 0)
> (j) Compare the training error rates between the pruned and
unpruned trees. Which is higher?
summary(oj.pruned)
##
## Classification tree:
## snip.tree(tree = ojtree, nodes = c(4L, 12L, 5L))
## Variables actually used in tree construction:
## [1] "LoyalCH" "ListPriceDiff"
## Number of terminal nodes: 5
## Residual mean deviance: 0.8239 = 655 / 795
## Misclassification error rate: 0.205 = 164 / 800
The pruned model returns a value of .205, while unpruned returned .1588. Not too different.
- Compare the test error rates between the pruned and unpruned trees. Which is higher?
pred.unpruned = predict(ojtree, test, type = "class")
misclass_unpr = sum(test$Purchase != pred.unpruned)
misclass_unpr/length(pred.unpruned)
## [1] 0.1703704
pred.pruned = predict(oj.pruned, test, type = "class")
misclass_unpr = sum(test$Purchase != pred.pruned)
misclass_unpr/length(pred.pruned)
## [1] 0.1925926
We can see that the test error rate for unpruned OJ is .17 while pruned is .19. Although pruned is higher, there isn’t much difference between the two.