# 3. Consider the Gini index, classification error, and cross-entropy in a simple 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. 



# 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.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("blue", "red", "green"))

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

library(ISLR)
set.seed(1)
train <- sample(1:nrow(Carseats), nrow(Carseats) / 2)
Carseats.train <- Carseats[train, ]
Carseats.test <- Carseats[-train, ]


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

library(tree)
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"       "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)

yhat <- predict(tree.carseats, newdata = Carseats.test)
mean((yhat - Carseats.test$Sales)^2)
## [1] 4.922039
    ### Test MSE of 4.38

# (c) 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 = "red", cex = 2, pch = 20)

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

yhat <- predict(prune.carseats, newdata = Carseats.test)
mean((yhat - Carseats.test$Sales)^2)
## [1] 5.113254
    ### THe mse changed from 4.922 to 5.113

# (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(MASS)
# 9. This problem involves the OJ data set which is part of the ISLR package.


# (a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(11)
train <- sample(1:nrow(OJ), 800)
OJ.train <- OJ[train, ]
OJ.test <- OJ[-train, ]


# (b) 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.train)
summary(tree.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "SalePriceMM"   "SpecialCH"     "PriceDiff"    
## [5] "ListPriceDiff"
## Number of terminal nodes:  10 
## Residual mean deviance:  0.6981 = 551.5 / 790 
## Misclassification error rate: 0.1438 = 115 / 800
    ### Training error rate is 0.1438 and the terminal nodes is 10

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

  tree.oj
## node), split, n, deviance, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 800 1070.00 CH ( 0.61000 0.39000 )  
##    2) LoyalCH < 0.48285 294  308.10 MM ( 0.21769 0.78231 )  
##      4) LoyalCH < 0.0608385 64   10.30 MM ( 0.01562 0.98438 ) *
##      5) LoyalCH > 0.0608385 230  270.10 MM ( 0.27391 0.72609 )  
##       10) SalePriceMM < 2.04 128  120.60 MM ( 0.17969 0.82031 )  
##         20) SpecialCH < 0.5 109   79.67 MM ( 0.11927 0.88073 ) *
##         21) SpecialCH > 0.5 19   26.29 CH ( 0.52632 0.47368 ) *
##       11) SalePriceMM > 2.04 102  136.60 MM ( 0.39216 0.60784 )  
##         22) LoyalCH < 0.336012 59   66.90 MM ( 0.25424 0.74576 ) *
##         23) LoyalCH > 0.336012 43   58.47 CH ( 0.58140 0.41860 ) *
##    3) LoyalCH > 0.48285 506  448.40 CH ( 0.83794 0.16206 )  
##      6) LoyalCH < 0.740621 219  272.90 CH ( 0.68493 0.31507 )  
##       12) PriceDiff < -0.165 34   34.57 MM ( 0.20588 0.79412 ) *
##       13) PriceDiff > -0.165 185  198.20 CH ( 0.77297 0.22703 )  
##         26) ListPriceDiff < 0.135 29   39.89 MM ( 0.44828 0.55172 ) *
##         27) ListPriceDiff > 0.135 156  140.60 CH ( 0.83333 0.16667 ) *
##      7) LoyalCH > 0.740621 287  105.90 CH ( 0.95470 0.04530 )  
##       14) PriceDiff < 0.31 190   94.82 CH ( 0.93158 0.06842 ) *
##       15) PriceDiff > 0.31 97    0.00 CH ( 1.00000 0.00000 ) *
        ### I chose terminal 4 LoyalCH, it is a terminal because of the asteriks. has a split criterion of < .0608 and 64 observations with a 10.30 MM deviation in branch MM. 


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

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

     ### the tree shows that LoyalCH might be an important indicator in relation to purchase. 

# (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?


tree.pred <- predict(tree.oj, OJ.test, type = "class")
table(tree.pred, OJ.test$Purchase)
##          
## tree.pred  CH  MM
##        CH 131  29
##        MM  34  76
      ### .2333333 is the test error rate.

# (f) 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] 10  9  8  5  4  2  1
## 
## $dev
## [1] 146 146 148 148 150 163 312
## 
## $k
## [1]       -Inf   0.000000   1.000000   2.333333   3.000000  10.000000 166.000000
## 
## $method
## [1] "misclass"
## 
## attr(,"class")
## [1] "prune"         "tree.sequence"
# (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", xlab = "Tree size", ylab = "Deviance")

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

      ### looks like number 9



# (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.
prune.oj <- prune.misclass(tree.oj, best = 9)
plot(prune.oj)
text(prune.oj, pretty = 0)

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

summary(tree.oj)
## 
## Classification tree:
## tree(formula = Purchase ~ ., data = OJ.train)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "SalePriceMM"   "SpecialCH"     "PriceDiff"    
## [5] "ListPriceDiff"
## Number of terminal nodes:  10 
## Residual mean deviance:  0.6981 = 551.5 / 790 
## Misclassification error rate: 0.1438 = 115 / 800
summary(prune.oj)
## 
## Classification tree:
## snip.tree(tree = tree.oj, nodes = 7L)
## Variables actually used in tree construction:
## [1] "LoyalCH"       "SalePriceMM"   "SpecialCH"     "PriceDiff"    
## [5] "ListPriceDiff"
## Number of terminal nodes:  9 
## Residual mean deviance:  0.7112 = 562.5 / 791 
## Misclassification error rate: 0.1438 = 115 / 800
      ### The misclassification error rate is teh same between both the pruned and unpruned trees. 

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

prune.pred <- predict(prune.oj, OJ.test, type = "class")
table(prune.pred, OJ.test$Purchase)
##           
## prune.pred  CH  MM
##         CH 131  29
##         MM  34  76
      ### the prunning process did not change the test error rate. it remained the same as before .23333333