Do problems 7.2 and 7.5 in Kuhn and Johnson. There are only two but they have many parts. Please submit both a link to your Rpubs and the .rmd file.

#install.packages('tidyr')
library(tidyr)
library(earth)
## Loading required package: plotmo
## Loading required package: Formula
## Loading required package: plotrix
## Loading required package: TeachingDemos
library(AppliedPredictiveModeling)
library(caret)
## Loading required package: lattice
## Loading required package: ggplot2
library(missMDA)
library(DMwR)
## Loading required package: grid
library(ggplot2)   # plotting
library(vip)       # variable importance
## 
## Attaching package: 'vip'
## The following object is masked from 'package:utils':
## 
##     vi
library(pdp)       # variable relationships

library(mda)
## Loading required package: class
## Loaded mda 0.4-10

Q 7.2

Friedman (1991) introduced several benchmark data sets create by simulation. One of these simulations used the following nonlinear equation to create data: y = 10sin(??x1x2) + 20(x3 ???0.5)2 + 10x4 +5x5 + N(0,??2) where the x values are random variables uniformly distributed between [0, 1] (there are also 5 other non-informative variables also created in the simulation). The package mlbench contains a function called mlbench.friedman1 that simulates these data:

library(mlbench) 
set.seed(200) 
trainingData <- mlbench.friedman1(200, sd = 1) 
## We convert the 'x' data from a matrix to a data frame 
## One reason is that this will give the columns names.
trainingData$x <- data.frame(trainingData$x) 
## Look at the data using 
featurePlot(trainingData$x, trainingData$y) 

## or other methods. 
## This creates a list with a vector 'y' and a matrix 
## of predictors 'x'. Also simulate a large test set to 
## estimate the true error rate with good precision: 
testData <- mlbench.friedman1(5000, sd = 1) 
testData$x <- data.frame(testData$x) 

Tune several models on these data. For example:

 knnModel <- train(x = trainingData$x,  y = trainingData$y, method = "knn",
                    preProc = c("center", "scale"),  tuneLength = 10) 
 knnModel
## k-Nearest Neighbors 
## 
## 200 samples
##  10 predictor
## 
## Pre-processing: centered (10), scaled (10) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 200, 200, 200, 200, 200, 200, ... 
## Resampling results across tuning parameters:
## 
##   k   RMSE      Rsquared   MAE     
##    5  3.565620  0.4887976  2.886629
##    7  3.422420  0.5300524  2.752964
##    9  3.368072  0.5536927  2.715310
##   11  3.323010  0.5779056  2.669375
##   13  3.275835  0.6030846  2.628663
##   15  3.261864  0.6163510  2.621192
##   17  3.261973  0.6267032  2.616956
##   19  3.286299  0.6281075  2.640585
##   21  3.280950  0.6390386  2.643807
##   23  3.292397  0.6440392  2.656080
## 
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was k = 15.
knnPred <- predict(knnModel, newdata = testData$x)
## The function 'postResample' can be used to get the test set 
## perforamnce values 
postResample(pred = knnPred, obs = testData$y) 
##      RMSE  Rsquared       MAE 
## 3.1750657 0.6785946 2.5443169

Which models appear to give the best performance? Does MARS select the informative predictors (those named X1-X5)?

marsFit <- earth(trainingData$x, trainingData$y)
marsFit
## Selected 12 of 18 terms, and 6 of 10 predictors
## Termination condition: Reached nk 21
## Importance: X1, X4, X2, X5, X3, X6, X7-unused, X8-unused, X9-unused, ...
## Number of terms at each degree of interaction: 1 11 (additive model)
## GCV 2.540556    RSS 397.9654    GRSq 0.8968524    RSq 0.9183982
marsGrid <- expand.grid(.degree = 1:2, .nprune = 2:38) 
set.seed(100)
marsTuned <- train(trainingData$x,trainingData$y, method = "earth", 
                   # Explicitly declare the candidate models to test 
                   tuneGrid = marsGrid, 
                   trControl = trainControl(method = "cv"))

varImp(marsTuned)
## earth variable importance
## 
##     Overall
## X1   100.00
## X4    85.14
## X2    69.24
## X5    49.32
## X3    40.02
## X8     0.00
## X6     0.00
## X10    0.00
## X9     0.00
## X7     0.00

We can see the MARS model selected the important variables

marsPred <- predict(marsTuned, newdata = testData$x)
postResample(pred =marsPred, obs = testData$y) 
##      RMSE  Rsquared       MAE 
## 1.1492504 0.9471145 0.9158382

This shows that MARS is a better model for this dataset because the RMSE is lower

Exercise 6.3 describes data for a chemical manufacturing process. Use the same data imputation, data splitting, and pre-processing steps as before and train several nonlinear regression models. (a) Which nonlinear regression model gives the optimal resampling and test set performance?

data("ChemicalManufacturingProcess")

ChemicalManuf_df<-ChemicalManufacturingProcess
ChemicalManuf_df <- knnImputation(ChemicalManuf_df[, !names(ChemicalManuf_df) %in% "Yield"])
#anyNA(ChemicalManuf_df)
ChemicalManuf_df$Yield <-ChemicalManufacturingProcess$Yield
## 75% of the sample size
smp_size <- floor(0.75 * nrow(ChemicalManuf_df))

## set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(ChemicalManuf_df)), size = smp_size)

train <- ChemicalManuf_df[train_ind, ]
test <-ChemicalManuf_df[-train_ind, ]
solTrainXtrans <- train[, !names(train) %in% "Yield"]
solTrainY <- train[,  "Yield"]

solTestXtrans <- test[, !names(train) %in% "Yield"]
solTestY <- test[,  "Yield"]
ctrl <- trainControl(method = "cv", number = 10)

Traning Neural nets

corThresh <- .9
tooHigh <- findCorrelation(cor(train), corThresh) 
corrPred <- names(train)[tooHigh]
trainXfiltered <- train[, -tooHigh]
testXfiltered <- test[, -tooHigh] 

solTrainXtransfilter <- trainXfiltered[, !names(trainXfiltered) %in% "Yield"]

solTrainYfilter <- trainXfiltered[,  "Yield"]

solTestXtransfilter <- testXfiltered[, !names(testXfiltered) %in% "Yield"]
solTestYfilter <- testXfiltered[,  "Yield"]
nnetGrid <- expand.grid(.decay = c(0, 0.01, .1),  .size = c(1:10), .bag = FALSE) 
set.seed(100)
nnetTune <- train(solTrainXtransfilter, solTrainYfilter,  method = "avNNet",  tuneGrid = nnetGrid,  trControl = ctrl, 
preProc = c("center", "scale"),  linout = TRUE,  trace = FALSE,  MaxNWts = 10 * (ncol(trainXfiltered) + 1) + 10 + 1,  maxit = 500)
nnetTunePred <- predict(nnetTune, newdata = solTestXtransfilter)
postResample(pred =nnetTunePred, obs = solTestYfilter) 
##     RMSE Rsquared      MAE 
## 1.335478 0.544955 1.019307

training MARS

marsGrid <- expand.grid(.degree = 1:2, .nprune = 2:38) 
set.seed(100)
marsTuned <- train(solTrainXtransfilter, solTrainYfilter, method = "earth", 
                   # Explicitly declare the candidate models to test 
                   tuneGrid = marsGrid, 
                   trControl = trainControl(method = "cv"))

marsPred <- predict(marsTuned, newdata = solTestXtransfilter)
postResample(pred = marsPred, obs = solTestYfilter) 
##      RMSE  Rsquared       MAE 
## 1.1332147 0.6415958 0.8878846

Training SVM

svmRTuned <- train(solTrainXtransfilter, solTrainYfilter, 
                   method = "svmRadial", 
                   preProc = c("center", "scale"), 
                   tuneLength = 14, trControl = trainControl(method = "cv"))

svmRPred <- predict(svmRTuned, newdata = solTestXtransfilter)
postResample(pred =svmRPred, obs = solTestYfilter) 
##      RMSE  Rsquared       MAE 
## 1.1425908 0.6240253 0.9176460

Training with KNN

 knnTune <- train(solTrainXtransfilter, solTrainYfilter,  method = "knn", 
                  # Center and scaling will occur for new predictions too 
                  preProc = c("center", "scale"), 
                  tuneGrid = data.frame(.k = 1:20),  trControl = trainControl(method = "cv"))

 knnTunePred <- predict( knnTune, newdata = solTestXtransfilter)
postResample(pred = knnTunePred, obs = solTestYfilter) 
##      RMSE  Rsquared       MAE 
## 1.4547327 0.3858106 1.1291667
  1. Which nonlinear regression model gives the optimal resampling and test set performance?

Based on the RSME values MARS is best followed by SVM

  1. Which predictors are most important in the optimal nonlinear regression model? Do either the biological or process variables dominate the list? How do the top ten important predictors compare to the top ten predictors from the optimal linear model?
varImp(marsTuned)
## earth variable importance
## 
##   only 20 most important variables shown (out of 48)
## 
##                        Overall
## ManufacturingProcess32 100.000
## ManufacturingProcess13  56.852
## ManufacturingProcess09  39.216
## ManufacturingProcess33   6.988
## ManufacturingProcess19   0.000
## ManufacturingProcess26   0.000
## ManufacturingProcess07   0.000
## ManufacturingProcess23   0.000
## BiologicalMaterial01     0.000
## ManufacturingProcess28   0.000
## ManufacturingProcess21   0.000
## ManufacturingProcess37   0.000
## ManufacturingProcess17   0.000
## ManufacturingProcess30   0.000
## ManufacturingProcess03   0.000
## ManufacturingProcess12   0.000
## ManufacturingProcess22   0.000
## ManufacturingProcess41   0.000
## ManufacturingProcess08   0.000
## ManufacturingProcess36   0.000

We can see that the manufacturingProcess dominates the list, this is quite similar to the linear model however in this case it looks like the biological materials are of little importance

plot(marsTuned)

This shows that Product Degrese of 1 has the lowest RSME when the number of terms are less than 10

  1. Explore the relationships between the top predictors and the response for the predictors that are unique to the optimal nonlinear regression model. Do these plots reveal intuition about the biological or process predictors and their relationship with yield?
marsTuned <- train(solTrainXtrans, solTrainY, method = "earth", 
                   # Explicitly declare the candidate models to test 
                   tuneGrid = marsGrid, 
                   trControl = trainControl(method = "cv"))



p1 <- partial(marsTuned, pred.var = "ManufacturingProcess32", grid.resolution = 10) %>% autoplot()
p2 <- partial(marsTuned, pred.var = "ManufacturingProcess13", grid.resolution = 10) %>% autoplot()
p5 <- partial(marsTuned, pred.var = "BiologicalMaterial01", grid.resolution = 10) %>% autoplot()
p3 <- partial(marsTuned, pred.var = c("ManufacturingProcess32", "ManufacturingProcess13"), grid.resolution = 10) %>% 
  plotPartial(levelplot = FALSE, zlab = "yhat", drape = TRUE, colorkey = TRUE, screen = list(z = -20, x = -60))

gridExtra::grid.arrange(p1, p2, p3,p5, ncol = 4)

These plots truely show how the manufacturing process predicts have some strong relationship to the yield while the biological predictors are not really showing any significant relationship