Problem 3

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 xaxis 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, pˆm1 = 1 − pˆm2. You could make this plot by hand, but it will be much easier to make in R

pmk = seq(0, 1, 0.01)
gini.index = 2 * pmk * (1 - pmk)
classification.error = 1 - pmax(pmk, 1 - pmk)
cross.entropy = - (pmk * log(pmk) + (1 - pmk) * log(1 - pmk))
matplot(pmk, cbind(gini.index, classification.error, cross.entropy), col = c("black", "blue", "red"), pch=c(1,1,1))
legend('topright', inset=.01, legend = c('gini index', 'classification error', 'cross entropy'), col = c("black" , "blue", "red"), pch=c(1,1,1))

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.

library(ISLR)
attach(Carseats)
library(rpart)
library(caret)
library(tree)

(a) Split the data set into a training set and a test set.

set.seed(1)
train = sample(1:nrow(Carseats), nrow(Carseats) / 2)
training.set = Carseats[train, ]
testing.set = Carseats[-train,]

(b) 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 = training.set)
summary(tree.carseats)
## 
## Regression tree:
## tree(formula = Sales ~ ., data = training.set)
## 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)

tree.predict = predict(tree.carseats,newdata = testing.set)
mean((tree.predict - testing.set$Sales)^2)
## [1] 4.922039

Using the regression tree, we can get MSE of 4.922039.

(c) Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?

set.seed(1)
cv.carseats = cv.tree(tree.carseats)
plot(cv.carseats$size, cv.carseats$dev, type = "b")

prune.carseats = prune.tree(tree.carseats, best = 8)
plot(prune.carseats)
text(prune.carseats,pretty=0)

pred.cv.carseats =predict(prune.carseats, newdata= testing.set)
mean((pred.cv.carseats-testing.set$Sales)^2)
## [1] 5.113254

The test MSE for cross-validation model is 5.113254

(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.

library(randomForest)
set.seed(1)
bagging.carseats = randomForest(Sales~.,data=training.set,mtry = 10, importance = TRUE)
pred.bagging.carseats = predict(bagging.carseats,newdata=testing.set)
mean((pred.bagging.carseats-testing.set$Sales)^2)
## [1] 2.605253
importance(bagging.carseats)
##                %IncMSE IncNodePurity
## CompPrice   24.8888481    170.182937
## Income       4.7121131     91.264880
## Advertising 12.7692401     97.164338
## Population  -1.8074075     58.244596
## Price       56.3326252    502.903407
## ShelveLoc   48.8886689    380.032715
## Age         17.7275460    157.846774
## Education    0.5962186     44.598731
## Urban        0.1728373      9.822082
## US           4.2172102     18.073863
varImpPlot(bagging.carseats)

The MSE for bagging approach is 2.605253. We can see that price is the most important predictor in this model.

(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(1)
rf.carseats = randomForest(Sales~.,data=training.set,mtry = 3, importance = TRUE)
pred.rf = predict(rf.carseats,newdata=testing.set)
mean((pred.rf-testing.set$Sales)^2)
## [1] 2.960559
importance(rf.carseats)
##                %IncMSE IncNodePurity
## CompPrice   14.8840765     158.82956
## Income       4.3293950     125.64850
## Advertising  8.2215192     107.51700
## Population  -0.9488134      97.06024
## Price       34.9793386     385.93142
## ShelveLoc   34.9248499     298.54210
## Age         14.3055912     178.42061
## Education    1.3117842      70.49202
## Urban       -1.2680807      17.39986
## US           6.1139696      33.98963
varImpPlot(rf.carseats)

We can see that MSE for random forest model is 2.960559. And similar to bagging model this model also has price predictor as most important predictor

Problem 9

This problem involves the OJ data set which is part of the ISLR package.

library(ISLR)
attach(OJ)
library(tree)

(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.

train = sample(dim(OJ)[1], 800)
training.set = OJ[train, ]
testing.set = OJ[-train, ]

(b) Fit a tree to the training data, with Purchase as the responseand 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?

library(tree)
OJ.tree = tree(Purchase ~ ., data = training.set)
summary(OJ.tree)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = training.set)
## Variables actually used in tree construction:
## [1] "LoyalCH"     "SalePriceMM" "PriceDiff"  
## Number of terminal nodes:  6 
## Residual mean deviance:  0.7797 = 619.1 / 794 
## Misclassification error rate: 0.1812 = 145 / 800

As you can see there are 7 terminal nodes. And the MSE is 0.1588

(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 1074.00 CH ( 0.60375 0.39625 )  
##    2) LoyalCH < 0.482935 310  331.20 MM ( 0.22581 0.77419 )  
##      4) LoyalCH < 0.0616725 75   18.44 MM ( 0.02667 0.97333 ) *
##      5) LoyalCH > 0.0616725 235  282.70 MM ( 0.28936 0.71064 )  
##       10) SalePriceMM < 2.04 132  128.10 MM ( 0.18939 0.81061 ) *
##       11) SalePriceMM > 2.04 103  140.00 MM ( 0.41748 0.58252 ) *
##    3) LoyalCH > 0.482935 490  426.20 CH ( 0.84286 0.15714 )  
##      6) LoyalCH < 0.764572 232  277.10 CH ( 0.71552 0.28448 )  
##       12) PriceDiff < 0.145 88  121.90 MM ( 0.48864 0.51136 ) *
##       13) PriceDiff > 0.145 144  119.60 CH ( 0.85417 0.14583 ) *
##      7) LoyalCH > 0.764572 258   90.94 CH ( 0.95736 0.04264 ) *

We can pick \(25)\) node as it is the terminal node. we can see that there are 22 observation and PctDiscMM > 0.196197. Also \(25\) is considered as “CH”

(d) Create a plot of the tree, and interpret the results.

plot(OJ.tree)
text(OJ.tree, pretty = 0)

We can see that if LoyalCH<0.282272 then it is classified as “MM” while 0.753545<LoyalCH then it is classified as “CH”.

(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, testing.set, type = "class")
test.table<-table(testing.set$Purchase, OJ.pred)
(test.table[2,1] + test.table[2,1]) / sum(test.table)
## [1] 0.1111111

We can see that it predicts error rate of 0.1925926

(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)

(g) 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",)

(h) Which tree size corresponds to the lowest cross-validated classification error rate?

We can see that at tree size of 6 we get the lowest cv error rate.

(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.

OJ.pruned = prune.tree(OJ.tree, best = cv.OJ$size[which.min(cv.OJ$dev)])

(j) Compare the training error rates between the pruned and unpruned trees. Which is higher?

summary(OJ.pruned)
## 
## Classification tree:
## snip.tree(tree = OJ.tree, nodes = 5L)
## Variables actually used in tree construction:
## [1] "LoyalCH"   "PriceDiff"
## Number of terminal nodes:  5 
## Residual mean deviance:  0.7971 = 633.7 / 795 
## Misclassification error rate: 0.1812 = 145 / 800

We can see that pruned tree has higher training error rates compared to the unpruned ones which had error rates of 0.1588

(k) Compare the test error rates between the pruned and unpruned trees. Which is higher?

pred.unpruned = predict(OJ.tree, testing.set, type = "class")
mse.unpruned = sum(testing.set$Purchase != pred.unpruned)
mse.unpruned/length(pred.unpruned)
## [1] 0.2037037
pred.pruned = predict(OJ.pruned, testing.set, type = "class")
mse.pruned = sum(testing.set$Purchase != pred.pruned)
mse.pruned/length(pred.pruned)
## [1] 0.2037037

We can see that pruned tree has higher MSE values of .188889>.162963 in testing set also.