3. Consider the Gini index, classi???cation error, and entropy in a simple classi???cation setting with two classes. Create a single plot that displays each of these quantities as a function of ^ pm1. Thexaxis should display ^ pm1, ranging from 0 to 1, and the y-axis should display the value of the Gini index, classi???cation error, and entropy.
p = seq(0,1,0.01)
gini.index = 2*p*(1-p)
class.error = 1 - pmax(p,1-p)
crozz.entropy = -(p*log(p)+(1-p)*log(1-p))
matplot(p,cbind(gini.index,class.error,crozz.entropy),col = c("red","blue","green"))

8. In the lab, a classi???cation 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.
library(ISLR)
## Warning: package 'ISLR' was built under R version 3.5.3
train = sample(1:nrow(Carseats),nrow(Carseats)*.5)
Carseats.train = Carseats[train,]
Carseats.test = Carseats[-train,]
- Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
library(tree)
## Warning: package 'tree' was built under R version 3.5.3
tree.carseats = tree(Sales~., data = Carseats.train)
summary(tree.carseats)
##
## Regression tree:
## tree(formula = Sales ~ ., data = Carseats.train)
## Variables actually used in tree construction:
## [1] "ShelveLoc" "Advertising" "Price" "Income" "Population"
## [6] "CompPrice" "Age"
## Number of terminal nodes: 19
## Residual mean deviance: 2.01 = 363.7 / 181
## Distribution of residuals:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -3.909000 -0.841400 0.003429 0.000000 0.891600 3.435000
plot(tree.carseats)
text(tree.carseats, pretty = 0)

yhat = predict(tree.carseats, newdata = Carseats.test)
mean((yhat - Carseats.test$Sales)^2)
## [1] 4.92279
- Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
cv.carseats = cv.tree(tree.carseats)
plot(cv.carseats$size,cv.carseats$dev, type = "b")
tree.min = which.min(cv.carseats$dev)
points(tree.min,cv.carseats$dev[tree.min],col = "blue",cex = 2, pch = 20)

NOw we are going to prune the trees! Using 6 nodes!
prune.carseats = prune.tree(tree.carseats, best = 6)
plot(prune.carseats)
text(prune.carseats, pretty = 0)

yhat = predict(prune.carseats,newdata = Carseats.test)
mean((yhat - Carseats.test$Sales)^2)
## [1] 6.168926
- 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.
library(randomForest)
## Warning: package 'randomForest' was built under R version 3.5.3
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
bag.carsets = randomForest(Sales~., data = Carseats.train, mtry = 10, ntree = 500, importance = T)
yhat.bag = predict(bag.carsets, newdata = Carseats.test)
mean((yhat.bag- Carseats.test$Sales)^2)
## [1] 2.941845
importance(bag.carsets)
## %IncMSE IncNodePurity
## CompPrice 22.9085548 133.584003
## Income 5.3809401 62.206948
## Advertising 21.1117383 151.009843
## Population -1.7982398 46.495407
## Price 53.6800972 432.646402
## ShelveLoc 56.8768759 426.526531
## Age 18.9751078 141.738873
## Education 4.3489712 34.132353
## Urban 1.8548603 10.668073
## US 0.2832301 4.674055
- 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 e???ect of m, the number of variables considered at each split, on the error rate obtained.
rf.carseats = randomForest(Sales~., data = Carseats.train,mtry=3, ntree = 500, importance = T)
yhat.rf = predict(rf.carseats, newdata= Carseats.test)
mean((yhat.rf-Carseats$Sales)^2)
## [1] 10.44886
importance(rf.carseats)
## %IncMSE IncNodePurity
## CompPrice 14.1705959 122.99525
## Income 0.8767293 98.20590
## Advertising 15.2091275 151.37014
## Population -1.6924209 94.60929
## Price 30.8692814 325.29589
## ShelveLoc 32.8378083 295.82954
## Age 11.9264851 158.67527
## Education 3.9926672 68.85465
## Urban 4.1206263 35.55612
## US 3.9658248 19.71439
It wod appear that advertising ,sHelvel,Price, and age play an important roll in prodicting .
9. This problem involves the OJ data set which is part of the ISLR package.
- Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
library(ISLR)
library(tree)
set.seed(1)
train<-sample(1:nrow(OJ),800)
OJ.training<-OJ[train,]
OJ.testing<-OJ[-train,]
- 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?
tree.oj<-tree(Purchase~., data = OJ.training)
summary(tree.oj )
##
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.training)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "SpecialCH" "ListPriceDiff"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7305 = 578.6 / 792
## Misclassification error rate: 0.165 = 132 / 800
The Training error is .165%
- 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.
tree.oj
## node), split, n, deviance, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 1064.00 CH ( 0.61750 0.38250 )
## 2) LoyalCH < 0.508643 350 409.30 MM ( 0.27143 0.72857 )
## 4) LoyalCH < 0.264232 166 122.10 MM ( 0.12048 0.87952 )
## 8) LoyalCH < 0.0356415 57 10.07 MM ( 0.01754 0.98246 ) *
## 9) LoyalCH > 0.0356415 109 100.90 MM ( 0.17431 0.82569 ) *
## 5) LoyalCH > 0.264232 184 248.80 MM ( 0.40761 0.59239 )
## 10) PriceDiff < 0.195 83 91.66 MM ( 0.24096 0.75904 )
## 20) SpecialCH < 0.5 70 60.89 MM ( 0.15714 0.84286 ) *
## 21) SpecialCH > 0.5 13 16.05 CH ( 0.69231 0.30769 ) *
## 11) PriceDiff > 0.195 101 139.20 CH ( 0.54455 0.45545 ) *
## 3) LoyalCH > 0.508643 450 318.10 CH ( 0.88667 0.11333 )
## 6) LoyalCH < 0.764572 172 188.90 CH ( 0.76163 0.23837 )
## 12) ListPriceDiff < 0.235 70 95.61 CH ( 0.57143 0.42857 ) *
## 13) ListPriceDiff > 0.235 102 69.76 CH ( 0.89216 0.10784 ) *
## 7) LoyalCH > 0.764572 278 86.14 CH ( 0.96403 0.03597 ) *
If we look at 10 we see that Price Difference is differed if below .195, and the number of observations is 83.
- Create a plot of the tree, and interpret the results. Now we will plot the tree
plot(tree.oj)
text(tree.oj, 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?
tree.pred<-predict(tree.oj,OJ.testing,type = "class")
table(tree.pred,OJ.testing$Purchase)
##
## tree.pred CH MM
## CH 147 49
## MM 12 62
Our error rate is
(12+49)/(12+49+147+62)
## [1] 0.2259259
- Apply the cv.tree() function to the training set in order to determine the optimal tree size.
cv.oj<-cv.tree(tree.oj,FUN = prune.misclass)
cv.oj
## $size
## [1] 8 5 2 1
##
## $dev
## [1] 156 156 156 306
##
## $k
## [1] -Inf 0.000000 4.666667 160.000000
##
## $method
## [1] "misclass"
##
## attr(,"class")
## [1] "prune" "tree.sequence"
- Produce a plot with tree size on the x-axis and cross-validated classi???cation error rate on the y-axis.
plot(cv.oj$size,cv.oj$dev, type = "b", xlab = "Size", ylab = "Dev")

- Which tree size corresponds to the lowest cross-validated classi???cation error rate?
Our optimal Tree would have 5 nodes it appears by the graph to have the lowest CLassification error.
- 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 ???ve terminal nodes.
prune.oj = prune.misclass(tree.oj,best = 5)
plot(prune.oj)
text(prune.oj, pretty= 0)

- Compare the training error rates between the pruned and unpruned trees. Which is higher?
Now we will compaire both trees
summary(tree.oj)
##
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.training)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "SpecialCH" "ListPriceDiff"
## Number of terminal nodes: 8
## Residual mean deviance: 0.7305 = 578.6 / 792
## Misclassification error rate: 0.165 = 132 / 800
summary(prune.oj)
##
## Classification tree:
## snip.tree(tree = tree.oj, nodes = 3:4)
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff" "SpecialCH"
## Number of terminal nodes: 5
## Residual mean deviance: 0.8256 = 656.4 / 795
## Misclassification error rate: 0.165 = 132 / 800
- Compare the test error rates between the pruned and unpruned trees. Which is higher?
prune.pred<-predict(prune.oj,OJ.testing,type = "class")
table(prune.pred,OJ.testing$Purchase)
##
## prune.pred CH MM
## CH 147 49
## MM 12 62
print("Thus we get the same error rate")
## [1] "Thus we get the same error rate"
(12+49)/(12+49+147+62)
## [1] 0.2259259