Quiz 1

For this quiz we will be using several R packages. R package versions change over time, the right answers have been checked using the following versions of the packages.

If you aren’t using these versions of the packages, your answers may not exactly match the right answer, but hopefully should be close.

Load the vowel.train and vowel.test data sets:

library(ElemStatLearn)
data(vowel.train)
data(vowel.test)

Set the variable y to be a factor variable in both the training and test set. Then set the seed to 33833. Fit (1) a random forest predictor relating the factor variable y to the remaining variables and (2) a boosted predictor using the “gbm” method. Fit these both with the train() command in the caret package.

What are the accuracies for the two approaches on the test data set? What is the accuracy among the test set samples where the two methods agree?

Answer: RF Accuracy = 0.6082, GBM Accuracy = 0.5152, Agreement Accuracy = 0.6361

set.seed(33833)
dim(vowel.train)
## [1] 528  11
head(vowel.train)
##   y    x.1   x.2    x.3   x.4    x.5   x.6    x.7    x.8    x.9   x.10
## 1 1 -3.639 0.418 -0.670 1.779 -0.168 1.627 -0.388  0.529 -0.874 -0.814
## 2 2 -3.327 0.496 -0.694 1.365 -0.265 1.933 -0.363  0.510 -0.621 -0.488
## 3 3 -2.120 0.894 -1.576 0.147 -0.707 1.559 -0.579  0.676 -0.809 -0.049
## 4 4 -2.287 1.809 -1.498 1.012 -1.053 1.060 -0.567  0.235 -0.091 -0.795
## 5 5 -2.598 1.938 -0.846 1.062 -1.633 0.764  0.394 -0.150  0.277 -0.396
## 6 6 -2.852 1.914 -0.755 0.825 -1.588 0.855  0.217 -0.246  0.238 -0.365
## To avoid "Error: `data` and `reference` should be factors with the same levels"
vowel.train$y <- as.factor(vowel.train$y)
vowel.test$y <- as.factor(vowel.test$y)

library(caret)
modRF <- train(y~., method="rf", data=vowel.train)
predRF <- predict(modRF, vowel.test)
confusionMatrix(vowel.test$y, predRF)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  1  2  3  4  5  6  7  8  9 10 11
##         1  30 12  0  0  0  0  0  0  0  0  0
##         2   0 24 14  0  0  0  0  0  4  0  0
##         3   0  3 34  1  0  2  0  0  0  0  2
##         4   0  0  3 29  0  9  0  0  0  0  1
##         5   0  0  0  1 18 19  3  0  0  0  1
##         6   0  0  1  0  7 25  0  0  0  0  9
##         7   0  2  0  0  9  2 27  0  1  1  0
##         8   0  0  0  0  0  0  7 29  6  0  0
##         9   0  2  0  0  0  0  5  6 23  2  4
##         10  4 15  0  0  0  0  0  1  2 20  0
##         11  0  1  2  2  0  7  3  0 13  0 14
## 
## Overall Statistics
##                                           
##                Accuracy : 0.5909          
##                  95% CI : (0.5445, 0.6361)
##     No Information Rate : 0.1385          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.55            
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: 1 Class: 2 Class: 3 Class: 4 Class: 5 Class: 6
## Sensitivity           0.88235  0.40678  0.62963  0.87879  0.52941  0.39062
## Specificity           0.97196  0.95533  0.98039  0.96970  0.94393  0.95729
## Pos Pred Value        0.71429  0.57143  0.80952  0.69048  0.42857  0.59524
## Neg Pred Value        0.99048  0.91667  0.95238  0.99048  0.96190  0.90714
## Prevalence            0.07359  0.12771  0.11688  0.07143  0.07359  0.13853
## Detection Rate        0.06494  0.05195  0.07359  0.06277  0.03896  0.05411
## Detection Prevalence  0.09091  0.09091  0.09091  0.09091  0.09091  0.09091
## Balanced Accuracy     0.92716  0.68106  0.80501  0.92424  0.73667  0.67396
##                      Class: 7 Class: 8 Class: 9 Class: 10 Class: 11
## Sensitivity           0.60000  0.80556  0.46939   0.86957   0.45161
## Specificity           0.96403  0.96948  0.95400   0.94989   0.93503
## Pos Pred Value        0.64286  0.69048  0.54762   0.47619   0.33333
## Neg Pred Value        0.95714  0.98333  0.93810   0.99286   0.95952
## Prevalence            0.09740  0.07792  0.10606   0.04978   0.06710
## Detection Rate        0.05844  0.06277  0.04978   0.04329   0.03030
## Detection Prevalence  0.09091  0.09091  0.09091   0.09091   0.09091
## Balanced Accuracy     0.78201  0.88752  0.71169   0.90973   0.69332
##Accuracy : 0.5974
modRF <- train(y~., method="rf", data=vowel.train, prox=TRUE)
predRF <- predict(modRF, vowel.test)
confusionMatrix(vowel.test$y, predRF)$overall["Accuracy"]
##  Accuracy 
## 0.5995671
##Accuracy : 0.5974 
library(randomForest)
modRF <- randomForest(y ~ ., data=vowel.train)
predRF <- predict(modRF, vowel.test)
confusionMatrix(vowel.test$y, predRF)$overall["Accuracy"] 
##  Accuracy 
## 0.5930736
##Accuracy : 0.5325 
modGBM <- train(y~., method="gbm", data=vowel.train, verbose=FALSE)
predGBM <- predict(modGBM, vowel.test)
confusionMatrix(vowel.test$y, predGBM)$overall["Accuracy"] 
##  Accuracy 
## 0.5194805
##Accuracy : 0.633
agreed <- predRF == predGBM
confusionMatrix(vowel.test$y[agreed], predRF[agreed])$overall["Accuracy"] 
##  Accuracy 
## 0.6139818

Quiz 2

Load the Alzheimer’s data using the following commands

library(caret)
library(gbm)
set.seed(3433)
library(AppliedPredictiveModeling)
data(AlzheimerDisease)
adData = data.frame(diagnosis,predictors)
inTrain = createDataPartition(adData$diagnosis, p = 3/4)[[1]]
training = adData[ inTrain,]
testing = adData[-inTrain,]

Set the seed to 62433 and predict diagnosis with all the other variables using a random forest (“rf”), boosted trees (“gbm”) and linear discriminant analysis (“lda”) model. Stack the predictions together using random forests (“rf”). What is the resulting accuracy on the test set? Is it better or worse than each of the individual predictions?

set.seed(62433)
## Random Forrest
modRF <- train(diagnosis~., method="rf", data=training, prox=TRUE)
predRF <- predict(modRF, testing)
confusionMatrix(testing$diagnosis, predRF)$overall["Accuracy"] ##0.7926829
##  Accuracy 
## 0.7926829
## Boosted Trees
modGBM <- train(diagnosis~., method="gbm", data=training)
predGBM <- predict(modGBM, testing)
confusionMatrix(testing$diagnosis, predGBM)$overall["Accuracy"] ##0.7804878
##  Accuracy 
## 0.7804878
## Linear Discriminant Analysis
modLDA <- train(diagnosis~., method="lda", data=training)
predLDA <- predict(modLDA, testing)
confusionMatrix(testing$diagnosis, predLDA)$overall["Accuracy"] ##0.7682927
##  Accuracy 
## 0.7682927
## Together with RF
training2 <- data.frame(predRF, predGBM, predLDA, diagnosis=testing$diagnosis)
modRF2 <- train(diagnosis~., method="rf", data=training2, prox=TRUE)
## note: only 2 unique complexity parameters in default grid. Truncating the grid to 2 .
pred <- predict(modRF2, testing)
confusionMatrix(testing$diagnosis, pred)$overall["Accuracy"] ##0.8170732
## Accuracy 
## 0.804878

Quiz 3

Load the concrete data with the commands:

set.seed(3523)
library(AppliedPredictiveModeling)
data(concrete)
inTrain = createDataPartition(concrete$CompressiveStrength, p = 3/4)[[1]]
training = concrete[ inTrain,]
testing = concrete[-inTrain,]

Set the seed to 233 and fit a lasso model to predict Compressive Strength. Which variable is the last coefficient to be set to zero as the penalty increases? (Hint: it may be useful to look up ?plot.enet).

Answer: cement

set.seed(233)
names(concrete)
## [1] "Cement"              "BlastFurnaceSlag"    "FlyAsh"             
## [4] "Water"               "Superplasticizer"    "CoarseAggregate"    
## [7] "FineAggregate"       "Age"                 "CompressiveStrength"
library(elasticnet)
modFit <- train(CompressiveStrength~., data=training, method="lasso")
plot.enet(modFit$finalModel, xvar="penalty", use.color=TRUE)

Quiz 4

Load the data on the number of visitors to the instructors blog from here:

https://d396qusza40orc.cloudfront.net/predmachlearn/gaData.csv

Using the commands:

library(lubridate) # For year() function below
dat = read.csv("D:/R/data/gaData.csv")
training = dat[year(dat$date) < 2012,]
testing = dat[(year(dat$date)) > 2011,]

Fit a model using the bats() function in the forecast package to the training time series. Then forecast this model for the remaining time points. For how many of the testing points is the true value within the 95% prediction interval bounds?

Answer: 96%

dim(training)
## [1] 365   3
head(training)
##   X       date visitsTumblr
## 1 1 2011-01-01            0
## 2 2 2011-01-02            0
## 3 3 2011-01-03            0
## 4 4 2011-01-04            0
## 5 5 2011-01-05            0
## 6 6 2011-01-06            0
library(forecast)
tsl = ts(training$visitsTumblr)
modFit <- bats(tsl)
fcast <- forecast(modFit, h=nrow(testing), level=95)
plot(fcast)

sum((testing$visitsTumblr > fcast$lower) & (testing$visitsTumblr < fcast$upper))/nrow(testing)
## [1] 0.9617021

Quiz 5

Load the concrete data with the commands:

set.seed(3523)
library(AppliedPredictiveModeling)
data(concrete)
library(caret)
inTrain = createDataPartition(concrete$CompressiveStrength, p = 3/4)[[1]]
training = concrete[ inTrain,]
testing = concrete[-inTrain,]

Set the seed to 325 and fit a support vector machine using the e1071 package to predict Compressive Strength using the default settings. Predict on the testing set. What is the RMSE?

Answer: 6.72

set.seed(325)
names(concrete)
## [1] "Cement"              "BlastFurnaceSlag"    "FlyAsh"             
## [4] "Water"               "Superplasticizer"    "CoarseAggregate"    
## [7] "FineAggregate"       "Age"                 "CompressiveStrength"
library(e1071)
modFit <- svm(CompressiveStrength~., data=training)
summary(modFit)
## 
## Call:
## svm(formula = CompressiveStrength ~ ., data = training)
## 
## 
## Parameters:
##    SVM-Type:  eps-regression 
##  SVM-Kernel:  radial 
##        cost:  1 
##       gamma:  0.125 
##     epsilon:  0.1 
## 
## 
## Number of Support Vectors:  569
pred <- predict(modFit, testing)
sqrt(mean((pred - testing$CompressiveStrength)^2)) ## RMSE = Root Mean Square Deviation
## [1] 6.715009