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 ${m1} \(. **The x-axis should display **\){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, *\){m1}=1-{m2}$. You could make this plot by hand, but it will be much easier to make in R.
p = seq(0, 1, 0.01)
gini_index = p * (1 - p) * 2
entropy = -(p * log(p) + (1 - p) * log(1 - p))
classification_err = 1 - pmax(p, 1 - p)
matplot(p, cbind(gini_index, entropy, classification_err), type = 'l')
(8.0) 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.
data(Carseats)
str(Carseats)
## 'data.frame': 400 obs. of 11 variables:
## $ Sales : num 9.5 11.22 10.06 7.4 4.15 ...
## $ CompPrice : num 138 111 113 117 141 124 115 136 132 132 ...
## $ Income : num 73 48 35 100 64 113 105 81 110 113 ...
## $ Advertising: num 11 16 10 4 3 13 0 15 0 0 ...
## $ Population : num 276 260 269 466 340 501 45 425 108 131 ...
## $ Price : num 120 83 80 97 128 72 108 120 124 124 ...
## $ ShelveLoc : Factor w/ 3 levels "Bad","Good","Medium": 1 2 3 3 1 1 3 2 3 3 ...
## $ Age : num 42 65 59 55 38 78 71 67 76 76 ...
## $ Education : num 17 10 12 14 13 16 15 10 10 17 ...
## $ Urban : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 2 2 1 1 ...
## $ US : Factor w/ 2 levels "No","Yes": 2 2 2 2 1 2 1 2 1 2 ...
(8.a) Split the data set into a training set and a test set.
set.seed(1)
training_indicator = sample(1: nrow(Carseats), nrow(Carseats)/2)
train = Carseats[training_indicator,]
test = Carseats[-training_indicator,]
(8.b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
set.seed(1)
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" "Advertising" "CompPrice"
## [6] "US"
## Number of terminal nodes: 18
## Residual mean deviance: 2.167 = 394.3 / 182
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -3.88200 -0.88200 -0.08712 0.00000 0.89590 4.09900
plot(tree.carseats); text(tree.carseats, pretty = 0)
pred.carseats = predict(tree.carseats, test); mean((test$Sales - pred.carseats)^2)
## [1] 4.922039
(8.b) Answer: According to this decision tree ShelveLoc= ‘Good’, Price < 135, and US store leads to the leaf with the highest number of sales. The test MSE is 4.922039
(8.c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
set.seed(10)
cv.carseats = cv.tree(tree.carseats, FUN = prune.tree)
par(mfrow = c(1, 2))
plot(cv.carseats$size, cv.carseats$dev, type = "l")
plot(cv.carseats$k, cv.carseats$dev, type = "l")
pruned.carseats = prune.tree(tree.carseats, best = cv.carseats$size[which.min(cv.carseats$dev)])
par(mfrow = c(1, 1))
plot(pruned.carseats)
text(pruned.carseats, pretty = 0)
pred.pruned = predict(pruned.carseats, test)
mean((test$Sales - pred.pruned)^2)
## [1] 4.966929
(8.c) Answer: The test MSE is 4.966929
(8.d) 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(123)
bag.carseats = randomForest(Sales ~ .,
data = train,
ntree = 500,
importance = T)
bag.pred = predict(bag.carseats, test)
mean((test$Sales - bag.pred)^2)
## [1] 3.034679
importance(bag.carseats)
## %IncMSE IncNodePurity
## CompPrice 15.9798090 154.74702
## Income 3.9262250 133.27867
## Advertising 9.5034904 104.02220
## Population -1.9168315 93.90404
## Price 34.7891781 396.52698
## ShelveLoc 36.6558536 291.06552
## Age 13.4679974 173.48227
## Education 0.3123937 75.68286
## Urban 0.4711800 15.93681
## US 5.8566680 32.89546
(8.d) Answer: The test mse I obtained with the bagging approach is 3.034679 with top three most important predictors being ShelveLoc, Price, and CompPrice.
(8.e) 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(123)
rf.carseats = randomForest(Sales ~ .,
data = train,
mtry = 6,
ntree = 500,
importance = T)
rf.pred = predict(rf.carseats, test)
mean((test$Sales - rf.pred)^2)
## [1] 2.624757
importance(rf.carseats)
## %IncMSE IncNodePurity
## CompPrice 21.6525686 165.06757
## Income 5.7193926 105.60429
## Advertising 12.5085839 105.48610
## Population -1.5843703 72.33136
## Price 47.8431705 464.80130
## ShelveLoc 44.1976889 348.11493
## Age 15.9447350 160.15240
## Education 1.0589162 53.76078
## Urban 0.1465555 10.42207
## US 5.3056248 24.27223
(8.e) Answer: The test mse I obtained with random forest is 2.624757 with top three most important predictors being Price, ShelveLoc, and CompPrice. Setting a m<p seemed to lower the error rate
(9.0) This problem involves the OJ data set which is part of the ISLR package.
data(OJ)
str(OJ)
## 'data.frame': 1070 obs. of 18 variables:
## $ Purchase : Factor w/ 2 levels "CH","MM": 1 1 1 2 1 1 1 1 1 1 ...
## $ WeekofPurchase: num 237 239 245 227 228 230 232 234 235 238 ...
## $ StoreID : num 1 1 1 1 7 7 7 7 7 7 ...
## $ PriceCH : num 1.75 1.75 1.86 1.69 1.69 1.69 1.69 1.75 1.75 1.75 ...
## $ PriceMM : num 1.99 1.99 2.09 1.69 1.69 1.99 1.99 1.99 1.99 1.99 ...
## $ DiscCH : num 0 0 0.17 0 0 0 0 0 0 0 ...
## $ DiscMM : num 0 0.3 0 0 0 0 0.4 0.4 0.4 0.4 ...
## $ SpecialCH : num 0 0 0 0 0 0 1 1 0 0 ...
## $ SpecialMM : num 0 1 0 0 0 1 1 0 0 0 ...
## $ LoyalCH : num 0.5 0.6 0.68 0.4 0.957 ...
## $ SalePriceMM : num 1.99 1.69 2.09 1.69 1.69 1.99 1.59 1.59 1.59 1.59 ...
## $ SalePriceCH : num 1.75 1.75 1.69 1.69 1.69 1.69 1.69 1.75 1.75 1.75 ...
## $ PriceDiff : num 0.24 -0.06 0.4 0 0 0.3 -0.1 -0.16 -0.16 -0.16 ...
## $ Store7 : Factor w/ 2 levels "No","Yes": 1 1 1 1 2 2 2 2 2 2 ...
## $ PctDiscMM : num 0 0.151 0 0 0 ...
## $ PctDiscCH : num 0 0 0.0914 0 0 ...
## $ ListPriceDiff : num 0.24 0.24 0.23 0 0 0.3 0.3 0.24 0.24 0.24 ...
## $ STORE : num 1 1 1 1 0 0 0 0 0 0 ...
(9.a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(1)
training_indicator2 = sample(dim(OJ)[1], 800)
train2 = OJ[training_indicator2, ]
test2 = OJ[-training_indicator2, ]
(9.b) 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?.
set.seed(9)
oj.tree = tree(Purchase ~ ., data = train2); summary(oj.tree)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train2)
## 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
(9.b) The variables that are used as internal nodes in the tree are: “LoyalCH”, “PriceDiff”,“SpecialCH”,“ListPriceDiff”,“PctDiscMM”. The number of terminal is 9. The training error rate is ~16%.
(9.c) 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.
oj.tree
## 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.196197 55 73.14 CH ( 0.61818 0.38182 ) *
## 25) PctDiscMM > 0.196197 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 ) *
(9.c) Terminal Node 8: The splitting variable at this node is LoyalCH. The splitting value of this node is 0.0356415. There are 59 points in the subtree below this node. The deviance for all points contained in region below this node is 10.14. The prediction at this node is Sales = MM. About ~1.7% points in this node have CH as value of Sales. Remaining 98.3% points have MM as value of Sales.
(9.d) Create a plot of the tree, and interpret the results.
plot(oj.tree)
text(oj.tree, pretty = 0)
(9.d) LoyalCH is the most important variable of the tree, in fact top 3.5 nodes contain LoyalCH. If LoyalCH< 0.0356415, the tree predicts MM. If LoyalCH > 0.764572, the tree predicts CH. For intermediate values of LoyalCH, the decision also depends on the value of PriceDiff, ListPriceDiff, SpecialCH, and PctDiscMM.
(9.e) 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?.
oj.pred = predict(oj.tree, test2, type = "class")
caret::confusionMatrix(table(test2$Purchase, oj.pred))
## Confusion Matrix and Statistics
##
## oj.pred
## CH MM
## CH 160 8
## MM 38 64
##
## Accuracy : 0.8296
## 95% CI : (0.7794, 0.8725)
## No Information Rate : 0.7333
## P-Value [Acc > NIR] : 0.0001259
##
## Kappa : 0.6154
##
## Mcnemar's Test P-Value : 1.904e-05
##
## Sensitivity : 0.8081
## Specificity : 0.8889
## Pos Pred Value : 0.9524
## Neg Pred Value : 0.6275
## Prevalence : 0.7333
## Detection Rate : 0.5926
## Detection Prevalence : 0.6222
## Balanced Accuracy : 0.8485
##
## 'Positive' Class : CH
##
(9.e) The test error rate is ~0.1703.
(9.f) Apply the cv.tree() function to the training set in order to determine the optimal tree size.
cv.oj = cv.tree(oj.tree, FUN = prune.tree)
(9.g) Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.
set.seed(1)
plot(cv.oj$size, cv.oj$dev, type = "l", xlab = "Tree Size", ylab = "Deviance")
(9.h) which tree size corresponds to the lowest cross-validated classification error rate?
cv.oj$size[which.min(cv.oj$dev)]
## [1] 8
(9.h) Answer: Size of 5 gives lowest cross-validation error.
(9.i) 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.
set.seed(1)
oj.pruned = prune.tree(oj.tree, best = (cv.oj$size[which.min(cv.oj$dev)]))
par(mfrow = c(1, 1))
plot(oj.pruned)
text(oj.pruned, pretty = 0)
(9.j) Compare the training error rates between the pruned and unpruned trees. Which is higher?
set.seed(1)
summary(oj.tree)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train2)
## 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
summary(oj.pruned)
##
## Classification tree:
## snip.tree(tree = oj.tree, nodes = 10L)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff" "PctDiscMM"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7582 = 600.5 / 792
## Misclassification error rate: 0.1625 = 130 / 800
(9.j) The training error rate for the un-pruned oj tree is ~16%. The training error rate for the pruned oj tree is ~21%. The pruned tree error rate is higher.
(9.k) Compare the test error rates between the pruned and un-pruned trees. Which is higher?
set.seed(1)
pred.unpruned = predict(oj.pruned, test2, type = "class")
(sum(test2$Purchase != pred.unpruned))/length(pred.unpruned)
## [1] 0.162963
(sum(test2$Purchase != oj.pred))/length(oj.pred)
## [1] 0.1703704
(9.k) The pruned oj tree has an error rate of 0.1962963. The un-pruned oj tree has an error rate of 0.1703704. The pruned oj tree has a higher error rate.