#Chapter 8 Excercises ##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

p = seq(0, 1, 0.01)
gini = p * (1 - p) * 2
entropy = -(p * log(p) + (1 - p) * log(1 - p))
class.err = 1 - pmax(p, 1 - p)
matplot(p, cbind(gini, entropy, class.err), col = c("blue", "yellow", "red"))

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

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

(b) Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?

MSE=4.15

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

Pruning does increase the test mse

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

MSE=2.58

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

MSE=2.87

library(ISLR)
## Warning: package 'ISLR' was built under R version 3.6.3
library(tree)
attach(Carseats)

#a
train = sample(dim(Carseats)[1], dim(Carseats)[1]/2)
Carseats.train = Carseats[train, ]
Carseats.test = Carseats[-train, ]
#b
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"   "Price"       "Income"      "Age"         "US"         
## [6] "CompPrice"   "Advertising" "Education"  
## Number of terminal nodes:  19 
## Residual mean deviance:  2.066 = 374 / 181 
## Distribution of residuals:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -4.15000 -0.98470 -0.09649  0.00000  1.08500  3.94700
plot(tree.carseats)
text(tree.carseats, pretty = 0)

pred.carseats = predict(tree.carseats, Carseats.test)
mean((Carseats.test$Sales - pred.carseats)^2)
## [1] 4.856001
#c
cv.carseats = cv.tree(tree.carseats, FUN = prune.tree)
par(mfrow = c(1, 2))
plot(cv.carseats$size, cv.carseats$dev, type = "b")
plot(cv.carseats$k, cv.carseats$dev, type = "b")

pruned.carseats = prune.tree(tree.carseats, best = 9)
par(mfrow = c(1, 1))
plot(pruned.carseats)
text(pruned.carseats, pretty = 0)

pred.pruned = predict(pruned.carseats, Carseats.test)
mean((Carseats.test$Sales - pred.pruned)^2)
## [1] 5.128288
#d
library(randomForest)
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
bag.carseats = randomForest(Sales ~ ., data = Carseats.train, mtry = 10, ntree = 500, importance = T)
bag.pred = predict(bag.carseats, Carseats.test)
mean((Carseats.test$Sales - bag.pred)^2)
## [1] 2.749849
importance(bag.carseats)
##                %IncMSE IncNodePurity
## CompPrice   12.8359480     96.428371
## Income      14.9855997    125.371489
## Advertising 12.3036056    104.449996
## Population   1.1834179     56.149668
## Price       49.7044297    473.928705
## ShelveLoc   58.3684987    466.482589
## Age         18.5688579    138.987433
## Education   -0.5051797     53.060795
## Urban        0.2409256      5.042336
## US           3.0143045     10.219389
#e
rf.carseats = randomForest(Sales ~ ., data = Carseats.train, mtry = 5, ntree = 500, importance = T)
rf.pred = predict(rf.carseats, Carseats.test)
mean((Carseats.test$Sales - rf.pred)^2)
## [1] 2.932975
importance(rf.carseats)
##                 %IncMSE IncNodePurity
## CompPrice   12.29170163    109.561603
## Income       9.65124556    137.610766
## Advertising 10.54743712    121.635917
## Population  -0.05312127     74.644027
## Price       41.75383431    413.021534
## ShelveLoc   49.19028163    421.432977
## Age         14.07819444    151.443093
## Education    1.28228844     61.701607
## Urban        0.04296581      8.399897
## US           2.54386660     13.452251