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 pˆm1. The x-axis should display pˆm1, ranging from 0 to 1, and the y-axis should display the value of the Gini index, classification error, and entropy.
p <- seq(0,1,0.01); x <- 0:1
gini <- 2*p*(1-p); cerror <- 1-pmax(p,1-p); entropy <- -(p*log(p)+(1-p)*log(1-p))
plot(NA,NA,xlim=x,ylim=x,xlab="p",ylab="value")
legend("topright", legend=c('entropy','Gini index','classification error'),pch=1, col=c('orange', 'turquoise','purple'))
lines(p,gini,col='turquoise'); lines(p,cerror,col='purple'); lines(p,entropy,col='orange')
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.
index <- createDataPartition(Carseats$Sales,p=0.5,list=FALSE)
train <- Carseats[index,]
test <- Carseats[-index,]
set.seed(10)
tree <- rpart(Sales~.,data=train, method="anova", control = rpart.control(cp=.001))
fancyRpartPlot(tree)
treepreds <- predict(tree, test)
mse(test$Sales, treepreds)
## [1] 4.201972
After fitting a decision tree to the Carseats data to predict Sales, using all the variables and specifying that the cp must be reduced by .001 per split, we see that the tree split on 5 different variables. ShelveLoc was the first variable used to split the observations and the split criterion was it being equal to Bad or Medium. The next variable the observations would split on is Price. Since ShelvLoc and Price are the first variables being split on, they are the most important variables.
The mean squared error of the model’s predictions on the test data was 4.35.
plotcp(tree)
mincp <- tree$cptable[which.min(tree$cptable[,"xerror"]),"CP"]
mincp
## [1] 0.001
pruned <- prune(tree,cp=mincp)
fancyRpartPlot(pruned, uniform=TRUE, main="Pruned Regression Tree")
set.seed(10)
treepreds_pruned <- predict(pruned, test)
mse(test$Sales, treepreds_pruned)
## [1] 4.201972
The cp which returned the lowest error was .0155. After using this value to prune the tree, the mse increased to 4.49.
set.seed(10)
bagging <- randomForest(Sales~.,data=train,mtry=10,importance =TRUE, replace=T)
bagpreds <- predict(bagging,test)
mse(test$Sales, bagpreds)
## [1] 2.670586
importance(bagging)
## %IncMSE IncNodePurity
## CompPrice 25.6547210 159.803130
## Income 5.2021517 80.391084
## Advertising 10.6528434 85.838989
## Population -0.7070379 59.069693
## Price 52.3004295 440.282918
## ShelveLoc 66.0087450 618.706593
## Age 17.2154030 172.598021
## Education -0.3923522 48.414313
## Urban 0.1287238 5.957668
## US 2.2485265 7.103097
The test mse achieved by bootstrap aggregating is 2.43 which is more accurate than the single decision tree predictions even after pruning. According to this method, the most important variables are Price and ShelveLoc since they show the biggest increase in MSE when excluded from the model.
set.seed(10)
rf <- randomForest(Sales~.,data=train,importance =TRUE, replace=T)
rfpreds <- predict(rf,test)
mse(test$Sales, rfpreds)
## [1] 2.621596
importance(rf)
## %IncMSE IncNodePurity
## CompPrice 13.26481017 150.17202
## Income 1.61023596 113.66265
## Advertising 8.86430855 141.93429
## Population -2.46551157 112.90284
## Price 36.96655365 386.13766
## ShelveLoc 40.73163985 432.11570
## Age 11.38728381 173.09796
## Education 0.58492021 69.02728
## Urban 0.05739635 14.08399
## US 2.36868626 16.87827
The mse of the random forest model was 2.83, which is worse than the bagging method. The variables whose exclusion increases the mse the most, signifying their importance, are Price and ShelveLoc.
This problem involves the OJ data set which is part of the ISLR package.
set.seed(1)
obs <- sample(1:nrow(OJ), 800)
train9 <- OJ[obs,]
test9 <- OJ[-obs,]
set.seed(10)
tree9 <- tree(Purchase~.,data=train9, method="class")
summary(tree9)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train9, method = "class")
## 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
The misclassification rate of the decision tree using all variables to predict Purchase is .1588. There are a total of 9 terminal nodes in the decision tree. The variables used to split the observations to make the predictions are LoyalCH, PriceDiff, SpecialCH, ListPriceDiff, and PctDiscMM.
tree9
## 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 ) *
The terminal node that makes the most sense is number 7 which predicts the purchase to be Citrus Hill if the customer brand loyalty for Citrus Hill for the observation was greater than .76 with a probability of .95.
plot(tree9)
text(tree9,pretty=0)
As we can see from the plotted tree, LoyalCH is the first variable split on making it the most important. It is then split on again in the following nodes. If the value for LoyalCH for the observation is greater than .50 and greater than .76 then the predicted purchase is for Citrus Hill, which makes sense. If it is not also greater than .76 but the value for ListPriceDiff is greater than .235 then the prediction is Citrus Hill. An observation with a value for ListPriceDiff less than .235 is then split again on PctDiscMM where if the percent discount for Minute Maid is less than .19 then the prediction is for Citrus Hill. If the value of LoyalCH is less than .28 for an observation, it will be predicted Minute Maid unless the price difference is greater than .05 and if it is not, it will be predicted Citrus Hill if there is a special on Citrus Hill.
set.seed(10)
dtpreds <- predict(tree9,test9, type="class")
caret::confusionMatrix(dtpreds, test9$Purchase)
## Confusion Matrix and Statistics
##
## Reference
## Prediction CH MM
## CH 160 38
## MM 8 64
##
## Accuracy : 0.8296
## 95% CI : (0.7794, 0.8725)
## No Information Rate : 0.6222
## P-Value [Acc > NIR] : 8.077e-14
##
## Kappa : 0.6154
##
## Mcnemar's Test P-Value : 1.904e-05
##
## Sensitivity : 0.9524
## Specificity : 0.6275
## Pos Pred Value : 0.8081
## Neg Pred Value : 0.8889
## Prevalence : 0.6222
## Detection Rate : 0.5926
## Detection Prevalence : 0.7333
## Balanced Accuracy : 0.7899
##
## 'Positive' Class : CH
##
mean(dtpreds != test9$Purchase)
## [1] 0.1703704
The misclassification rate of the decision tree on the test data is .17.
set.seed(10)
cv <- cv.tree(tree9, FUN=prune.misclass)
cv
## $size
## [1] 9 8 7 4 2 1
##
## $dev
## [1] 144 144 147 153 173 315
##
## $k
## [1] -Inf 0.000000 3.000000 4.333333 10.500000 151.000000
##
## $method
## [1] "misclass"
##
## attr(,"class")
## [1] "prune" "tree.sequence"
The optimal tree size according to the error rates given by the cv.tree function is 8.
plot(cv$size ,cv$dev, main="Cross-validated Classification Error Rate By Tree Size", type = "b")
The tree size with the lowest cross-validated classification error rate is 8.
set.seed(10)
prune <- prune.misclass(tree9,best=8)
plot(prune)
text(prune,pretty=0)
summary(prune)
##
## Classification tree:
## snip.tree(tree = tree9, nodes = 4L)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "SpecialCH" "ListPriceDiff"
## [5] "PctDiscMM"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7598 = 601.8 / 792
## Misclassification error rate: 0.1588 = 127 / 800
summary(tree9)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = train9, method = "class")
## 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
The misclassification error rate for both trees, pruned and unpruned is .1588 even though the unpruned tree has one more terminal node.
dtpreds <- predict(tree9,test9, type="class")
mean(dtpreds != test9$Purchase)
## [1] 0.1703704
ptpreds <- predict(prune,test9, type="class")
mean(ptpreds != test9$Purchase)
## [1] 0.1703704
Both the pruned and unpruned trees achieved a misclassification error rate of .17.