Consider the Gini index, classification error, and entropy in a simple classfication setting with two classes. Create a single plot that displays each of these qualitites as a function of \(\hat{p}_m1\). The 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, 0.01)
gini.index <- 2 * p * (1 - p)
class.error <- 1 - pmax(p, 1 - p)
cross.entropy <- - (p * log(p) + (1 - p) * log(1 - p))
matplot(p, cbind(gini.index, class.error, cross.entropy), col = c("red", "green", "blue"))
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.
set.seed(123)
train = sample(nrow(Carseats), 200)
seats.train = Carseats[train,]
seats.test = Carseats[-train,]
tree.fit = tree(Sales~., data=seats.train)
summary(tree.fit)
##
## Regression tree:
## tree(formula = Sales ~ ., data = seats.train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Price" "Income" "Age" "Population"
## [6] "Education" "CompPrice" "Advertising"
## Number of terminal nodes: 18
## Residual mean deviance: 2.132 = 388.1 / 182
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -4.08000 -0.92870 0.06244 0.00000 0.87020 3.71700
plot(tree.fit)
text(tree.fit, pretty = 0)
tree.preds = predict(tree.fit, seats.test)
test.mse = mean((tree.preds - seats.test$Sales)^2)
test.mse
## [1] 4.395357
We obtain a test MSE of 4.39
set.seed(1)
cv.tree.fit = cv.tree(tree.fit)
plot(cv.tree.fit$size, cv.tree.fit$dev, type='b')
tree.min = which.min(cv.tree.fit$dev)
points(cv.tree.fit$size[tree.min],cv.tree.fit$dev[tree.min], col="red", cex=2, pch=20)
pruned.tree = prune.tree(tree.fit, best=7)
plot(pruned.tree)
text(pruned.tree, pretty=0)
prune.preds = predict(pruned.tree, seats.test)
pruned.test.mse = mean((prune.preds-seats.test$Sales)^2)
In this case the optimal tree size is 7 compared to the 18 terminal nodes seen in the summary output. The test MSE does not improve after pruning. It is less accurate going from 4.39 without pruning to 4.69 with pruning.
# bagging approach is similar to random forests but uses all variables at each split?
bag.seats = randomForest(Sales~., data = seats.train, mtry = 10, ntree = 500, importance = TRUE)
bag.preds = predict(bag.seats, seats.test)
bag.test.mse = mean((bag.preds-seats.test$Sales)^2)
importance(bag.seats)
## %IncMSE IncNodePurity
## CompPrice 20.314863 165.247282
## Income 7.983399 93.277231
## Advertising 6.526357 74.739251
## Population -1.156118 50.540570
## Price 47.182833 380.171717
## ShelveLoc 49.266950 387.018630
## Age 18.319586 176.976966
## Education 2.892331 56.176298
## Urban -1.645249 8.109251
## US -1.189827 5.885208
data.frame(importance = bag.seats$importanceSD) %>%
tibble::rownames_to_column(var = "variable") %>%
ggplot(aes(x = reorder(variable,importance), y = importance)) +
geom_bar(stat = "identity", fill = "orange", color = "black")+
coord_flip() +
labs(x = "Variables", y = "Variable importance")
After using a bagging approach the test MSE decreases to 2.75, performing the best in the metric compared with all other models. We can conclude from the summary output that Price and ShelveLoc have a significant impact on Sales.
rf.seats = randomForest(Sales~., data = seats.train, mtry=3, ntree=500, importance=T)
rf.preds = predict(rf.seats, seats.test)
rf.test.mse = mean((rf.preds - seats.test$Sales)^2)
data.frame(importance = rf.seats$importanceSD) %>%
tibble::rownames_to_column(var = "variable") %>%
ggplot(aes(x = reorder(variable,importance), y = importance)) +
geom_bar(stat = "identity", fill = "orange", color = "black")+
coord_flip() +
labs(x = "Variables", y = "Variable importance")
The test MSE improves from our original regression tree model but, does worse than our bagged approach, achieving a test MSE of 3.60. Using \(m=p\) the lowest error rate is obtained. The same two variables were important with this random forest approach compared with other models.
This problem involves the OJ data set which is part of the ISLR package.
train = sample(1:nrow(OJ), 800)
oj.train = OJ[train,]
oj.test = OJ[-train,]
tree.oj = tree(Purchase ~., data=oj.train)
summary(tree.oj)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff" "StoreID"
## Number of terminal nodes: 9
## Residual mean deviance: 0.721 = 570.3 / 791
## Misclassification error rate: 0.1638 = 131 / 800
The fitted tree has 7 terminal nodes and a training error rate of 0.17
#tree.oj
We pick the node labeled 8. The split criterion is LoyalCH < 0.035, the number of observations in that branch is 57 with a deviance of 10.07 and an overall prediction for the branch of MM. Less than 2% of the observations in that branch take the value of CH, and the remaining 98% take the value of MM.
plot(tree.oj)
text(tree.oj, pretty=0)
The variable
LoyalCH is seen in the top three nodes of the tree indicating it is most important when predicting Purchase.
oj.preds = predict(tree.oj, oj.test, type='class')
confusionMatrix(as.factor(oj.preds), oj.test$Purchase)
## Confusion Matrix and Statistics
##
## Reference
## Prediction CH MM
## CH 136 30
## MM 27 77
##
## Accuracy : 0.7889
## 95% CI : (0.7353, 0.836)
## No Information Rate : 0.6037
## P-Value [Acc > NIR] : 6.866e-11
##
## Kappa : 0.5567
##
## Mcnemar's Test P-Value : 0.7911
##
## Sensitivity : 0.8344
## Specificity : 0.7196
## Pos Pred Value : 0.8193
## Neg Pred Value : 0.7404
## Prevalence : 0.6037
## Detection Rate : 0.5037
## Detection Prevalence : 0.6148
## Balanced Accuracy : 0.7770
##
## 'Positive' Class : CH
##
# test mse = 1 - (TP + TN) / Total
oj.test.mse = 1 - (149 + 78) / 270
Our test error rate is about 16%
set.seed(1)
cv.oj = cv.tree(tree.oj, FUN = prune.misclass)
plot(cv.oj$size, cv.oj$dev, type='b', xlab = 'Tree Size', ylab = "CV Error Rate")
tree.min = which.min(cv.oj$dev)
plot(cv.oj$size, cv.oj$dev, type='b', xlab = 'Tree Size', ylab = "CV Error Rate")
points(cv.oj$size[tree.min],cv.oj$dev[tree.min], col="red", cex=2, pch=20)
A tree size of 4 achieves the lowest cross-validated classfication error rate.
prune.oj = prune.misclass(tree.oj, best = 4)
summary(tree.oj)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = oj.train)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "ListPriceDiff" "StoreID"
## Number of terminal nodes: 9
## Residual mean deviance: 0.721 = 570.3 / 791
## Misclassification error rate: 0.1638 = 131 / 800
summary(prune.oj)
##
## Classification tree:
## snip.tree(tree = tree.oj, nodes = 4:3)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 4
## Residual mean deviance: 0.8815 = 701.7 / 796
## Misclassification error rate: 0.1775 = 142 / 800
The test error rate is slightly higher for the pruned tree, going from 0.163 in the original model to 0.178 in the pruned model.
oj.prune.preds = predict(prune.oj, oj.test, type='class')
confusionMatrix(oj.prune.preds, oj.test$Purchase)
## Confusion Matrix and Statistics
##
## Reference
## Prediction CH MM
## CH 151 37
## MM 12 70
##
## Accuracy : 0.8185
## 95% CI : (0.7673, 0.8626)
## No Information Rate : 0.6037
## P-Value [Acc > NIR] : 2.381e-14
##
## Kappa : 0.6049
##
## Mcnemar's Test P-Value : 0.0006068
##
## Sensitivity : 0.9264
## Specificity : 0.6542
## Pos Pred Value : 0.8032
## Neg Pred Value : 0.8537
## Prevalence : 0.6037
## Detection Rate : 0.5593
## Detection Prevalence : 0.6963
## Balanced Accuracy : 0.7903
##
## 'Positive' Class : CH
##
# test mse = 1 - (TP + TN) / Total
prune.oj.mse = 1 - (151 + 71) / 270
The test MSE has increased from 0.15 to 0.17 after pruning the classification tree.