7.2

7.2. Friedman (1991) introduced several benchmark data sets create by sim-ulation. One of these simulations used the following nonlinear equation to create data: y = 10 sin(π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 simula- tion). The package mlbench contains a function called mlbench.friedman1 that simulates these data:

 set.seed(69)
 the_training_data <- mlbench.friedman1(200, sd = 1)
 ## here I convert the 'x' data from a matrix to a data frame

 the_training_data$x <- data.frame(the_training_data$x)
 
 featurePlot(the_training_data$x, the_training_data$y)

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

Tune several models on these data. For example:

the_knn_model <- train(x = the_training_data$x,
 y = the_training_data$y,
 method = "knn",

 preProc = c("center", "scale"),
 tuneLength = 10)
 the_knn_model
## 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.338964  0.5937080  2.643012
##    7  3.227689  0.6320365  2.573358
##    9  3.209593  0.6498177  2.561916
##   11  3.237488  0.6521713  2.567600
##   13  3.259841  0.6580970  2.583563
##   15  3.287206  0.6603461  2.610814
##   17  3.325692  0.6600715  2.644232
##   19  3.366152  0.6578260  2.668357
##   21  3.382426  0.6631588  2.681204
##   23  3.412506  0.6646297  2.698945
## 
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was k = 9.

200 samples 10 predictors

 my_knn_pred <- predict(the_knn_model, newdata = the_test_data$x)
## The function 'postResample' can be used to get the test set
 ## perforamnce values
 postResample(pred = my_knn_pred, obs = the_test_data$y)
##      RMSE  Rsquared       MAE 
## 3.2048215 0.6365428 2.5577229

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

the_NnetGrid <- expand.grid(.decay = c(0,0.01,.1),
                        .size = c(1:5),
                        .bag = FALSE)

my_nnetFit <- train(the_training_data$x, the_training_data$y,
                  method = 'avNNet',
                  tuneGrid = the_NnetGrid,
                  preProc = c('center','scale'),
                  linout = TRUE,
                  trace = FALSE,
                  MaxNWts = 5 * (ncol(the_training_data$x) + 1 + 5 + 1),
                  maxit = 100
  
)
## Warning: executing %dopar% sequentially: no parallel backend registered
head(my_nnetFit)
## $method
## [1] "avNNet"
## 
## $modelInfo
## $modelInfo$label
## [1] "Model Averaged Neural Network"
## 
## $modelInfo$library
## [1] "nnet"
## 
## $modelInfo$loop
## NULL
## 
## $modelInfo$type
## [1] "Classification" "Regression"    
## 
## $modelInfo$parameters
##   parameter   class         label
## 1      size numeric #Hidden Units
## 2     decay numeric  Weight Decay
## 3       bag logical       Bagging
## 
## $modelInfo$grid
## function (x, y, len = NULL, search = "grid") 
## {
##     if (search == "grid") {
##         out <- expand.grid(size = ((1:len) * 2) - 1, decay = c(0, 
##             10^seq(-1, -4, length = len - 1)), bag = FALSE)
##     }
##     else {
##         out <- data.frame(size = sample(1:20, size = len, replace = TRUE), 
##             decay = 10^runif(len, min = -5, 1), bag = sample(c(TRUE, 
##                 FALSE), size = len, replace = TRUE))
##     }
##     out
## }
## 
## $modelInfo$fit
## function (x, y, wts, param, lev, last, classProbs, ...) 
## {
##     dat <- if (is.data.frame(x)) 
##         x
##     else as.data.frame(x, stringsAsFactors = TRUE)
##     dat$.outcome <- y
##     if (!is.null(wts)) {
##         out <- caret::avNNet(.outcome ~ ., data = dat, weights = wts, 
##             size = param$size, decay = param$decay, bag = param$bag, 
##             ...)
##     }
##     else out <- caret::avNNet(.outcome ~ ., data = dat, size = param$size, 
##         decay = param$decay, bag = param$bag, ...)
##     out
## }
## <bytecode: 0x000000002d6c3588>
## 
## $modelInfo$predict
## function (modelFit, newdata, submodels = NULL) 
## {
##     if (modelFit$problemType == "Classification") {
##         out <- predict(modelFit, newdata, type = "class")
##     }
##     else {
##         out <- predict(modelFit, newdata, type = "raw")
##     }
##     out
## }
## <bytecode: 0x0000000032672dd0>
## 
## $modelInfo$prob
## function (modelFit, newdata, submodels = NULL) 
## {
##     out <- predict(modelFit, newdata, type = "prob")
##     if (ncol(as.data.frame(out, stringsAsFactors = TRUE)) == 
##         1) {
##         out <- cbind(out, 1 - out)
##         dimnames(out)[[2]] <- rev(modelFit$obsLevels)
##     }
##     out
## }
## 
## $modelInfo$predictors
## function (x, ...) 
## x$names
## 
## $modelInfo$levels
## function (x) 
## x$model[[1]]$lev
## 
## $modelInfo$tags
## [1] "Neural Network"       "Ensemble Model"       "Bagging"             
## [4] "L2 Regularization"    "Accepts Case Weights"
## 
## $modelInfo$sort
## function (x) 
## x[order(x$size, -x$decay), ]
## 
## 
## $modelType
## [1] "Regression"
## 
## $results
##    decay size   bag     RMSE  Rsquared      MAE    RMSESD RsquaredSD     MAESD
## 1   0.00    1 FALSE 2.734950 0.7221548 2.190429 0.2292043 0.05150203 0.2047083
## 6   0.01    1 FALSE 2.685862 0.7295287 2.148563 0.2095345 0.04518385 0.2092227
## 11  0.10    1 FALSE 2.643623 0.7385164 2.115627 0.2046461 0.04353749 0.2024413
## 2   0.00    2 FALSE 2.684861 0.7336816 2.140643 0.2230048 0.03830169 0.2304542
## 7   0.01    2 FALSE 2.719559 0.7252278 2.164269 0.2060117 0.04003420 0.1988219
## 12  0.10    2 FALSE 2.717002 0.7273955 2.164568 0.2244104 0.04268144 0.2034400
## 3   0.00    3 FALSE 2.492621 0.7659115 1.966317 0.2822683 0.05880471 0.2508426
## 8   0.01    3 FALSE 2.522907 0.7586639 1.990342 0.2459522 0.04962083 0.2032062
## 13  0.10    3 FALSE 2.450139 0.7739929 1.928744 0.2584331 0.04770934 0.2341050
## 4   0.00    4 FALSE 2.600930 0.7477077 2.050965 0.2829998 0.05245233 0.2467264
## 9   0.01    4 FALSE 2.459508 0.7725346 1.949066 0.2016858 0.03964930 0.1827564
## 14  0.10    4 FALSE 2.432236 0.7767320 1.923818 0.2758519 0.04509538 0.2222115
## 5   0.00    5 FALSE 2.820924 0.7138499 2.182193 0.4495618 0.08091788 0.2928048
## 10  0.01    5 FALSE 2.622058 0.7447363 2.097148 0.3453089 0.07060399 0.2941840
## 15  0.10    5 FALSE 2.464035 0.7706578 1.960231 0.1836948 0.03989368 0.1376989
## 
## $pred
## NULL
## 
## $bestTune
##    size decay   bag
## 14    4   0.1 FALSE
nnetPred <- predict(my_nnetFit, newdata = the_test_data$x)
postResample(pred = nnetPred, obs = the_test_data$y)
##      RMSE  Rsquared       MAE 
## 2.0700570 0.8322618 1.5808163
#creating tune grid
marsGrid <- expand.grid(.degree = 1:2, .nprune = 2:28)
set.seed(100)
my_mars_tune <- train(the_training_data$x, the_training_data$y,
                   method = 'earth',
                   tuneGrid = marsGrid,
                   trControl = trainControl(method = 'cv'))
## Loading required package: earth
## Warning: package 'earth' was built under R version 4.1.3
## Loading required package: Formula
## Loading required package: plotmo
## Warning: package 'plotmo' was built under R version 4.1.3
## Loading required package: plotrix
## Loading required package: TeachingDemos
## Warning: package 'TeachingDemos' was built under R version 4.1.3
my_mars_tune
## Multivariate Adaptive Regression Spline 
## 
## 200 samples
##  10 predictor
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 180, 180, 180, 180, 180, 180, ... 
## Resampling results across tuning parameters:
## 
##   degree  nprune  RMSE      Rsquared   MAE      
##   1        2      4.546153  0.2371108  3.7650388
##   1        3      3.449146  0.5602387  2.8369617
##   1        4      2.661550  0.7491487  2.1018291
##   1        5      2.573977  0.7696289  2.0481521
##   1        6      2.165591  0.8423158  1.7550170
##   1        7      1.711274  0.9030711  1.3574386
##   1        8      1.608414  0.9110593  1.2672889
##   1        9      1.502880  0.9220906  1.1953501
##   1       10      1.502028  0.9245361  1.1984265
##   1       11      1.526650  0.9212300  1.2144466
##   1       12      1.512234  0.9231616  1.2065561
##   1       13      1.526451  0.9213433  1.2140607
##   1       14      1.513523  0.9221166  1.2014020
##   1       15      1.527208  0.9219271  1.2158027
##   1       16      1.527208  0.9219271  1.2158027
##   1       17      1.527208  0.9219271  1.2158027
##   1       18      1.527208  0.9219271  1.2158027
##   1       19      1.527208  0.9219271  1.2158027
##   1       20      1.527208  0.9219271  1.2158027
##   1       21      1.527208  0.9219271  1.2158027
##   1       22      1.527208  0.9219271  1.2158027
##   1       23      1.527208  0.9219271  1.2158027
##   1       24      1.527208  0.9219271  1.2158027
##   1       25      1.527208  0.9219271  1.2158027
##   1       26      1.527208  0.9219271  1.2158027
##   1       27      1.527208  0.9219271  1.2158027
##   1       28      1.527208  0.9219271  1.2158027
##   2        2      4.546153  0.2371108  3.7650388
##   2        3      3.449146  0.5602387  2.8369617
##   2        4      2.661550  0.7491487  2.1018291
##   2        5      2.492776  0.7821021  1.9831227
##   2        6      2.218331  0.8356953  1.8133169
##   2        7      1.736775  0.9013611  1.3724252
##   2        8      1.709976  0.9030070  1.3529490
##   2        9      1.632551  0.9115453  1.2828881
##   2       10      1.340486  0.9411760  1.0761442
##   2       11      1.283564  0.9445710  1.0293865
##   2       12      1.195051  0.9521271  0.9648065
##   2       13      1.135711  0.9568221  0.9267564
##   2       14      1.130812  0.9562873  0.9286158
##   2       15      1.155828  0.9549238  0.9492484
##   2       16      1.192052  0.9512432  0.9697783
##   2       17      1.196939  0.9508646  0.9677769
##   2       18      1.196939  0.9508646  0.9677769
##   2       19      1.196939  0.9508646  0.9677769
##   2       20      1.196939  0.9508646  0.9677769
##   2       21      1.196939  0.9508646  0.9677769
##   2       22      1.196939  0.9508646  0.9677769
##   2       23      1.196939  0.9508646  0.9677769
##   2       24      1.196939  0.9508646  0.9677769
##   2       25      1.196939  0.9508646  0.9677769
##   2       26      1.196939  0.9508646  0.9677769
##   2       27      1.196939  0.9508646  0.9677769
##   2       28      1.196939  0.9508646  0.9677769
## 
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were nprune = 14 and degree = 2.
varImp(my_mars_tune)
## earth variable importance
## 
##    Overall
## X1  100.00
## X4   73.69
## X2   46.39
## X3   19.21
## X5    0.00
my_mars_pred <- predict(my_mars_tune, newdata = the_test_data$x)
postResample(pred = my_mars_pred, obs = the_test_data$y)
##      RMSE  Rsquared       MAE 
## 1.1853764 0.9446121 0.9438367
the_SVMR_tune <- train(the_training_data$x, the_training_data$y,
                   method = 'svmRadial',
                   preProc = c('center','scale'),
                   tuneLength = 14,
                   trControl = trainControl(method = 'cv'))

the_SVMR_tune
## Support Vector Machines with Radial Basis Function Kernel 
## 
## 200 samples
##  10 predictor
## 
## Pre-processing: centered (10), scaled (10) 
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 180, 180, 180, 180, 180, 180, ... 
## Resampling results across tuning parameters:
## 
##   C        RMSE      Rsquared   MAE     
##      0.25  2.749973  0.7772971  2.172545
##      0.50  2.457709  0.7963098  1.939591
##      1.00  2.235765  0.8221112  1.733289
##      2.00  2.045472  0.8465043  1.604971
##      4.00  1.895133  0.8651785  1.513396
##      8.00  1.897430  0.8627913  1.516612
##     16.00  1.908606  0.8608767  1.535736
##     32.00  1.908606  0.8608767  1.535736
##     64.00  1.908606  0.8608767  1.535736
##    128.00  1.908606  0.8608767  1.535736
##    256.00  1.908606  0.8608767  1.535736
##    512.00  1.908606  0.8608767  1.535736
##   1024.00  1.908606  0.8608767  1.535736
##   2048.00  1.908606  0.8608767  1.535736
## 
## Tuning parameter 'sigma' was held constant at a value of 0.06690564
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were sigma = 0.06690564 and C = 4.
my_SVM_pred <- predict(the_SVMR_tune, newdata = the_test_data$x)
postResample(pred = my_SVM_pred, obs = the_test_data$y)
##      RMSE  Rsquared       MAE 
## 2.1985635 0.8111998 1.7043010
my_knn_tune <- train(the_training_data$x, the_training_data$y,
                   method = 'knn',
                   preProc = c('center','scale'),
                   tuneGrid = data.frame(.k = 1:20),
                   trControl = trainControl(method = 'cv'))

my_knn_tune
## k-Nearest Neighbors 
## 
## 200 samples
##  10 predictor
## 
## Pre-processing: centered (10), scaled (10) 
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 180, 180, 180, 180, 180, 180, ... 
## Resampling results across tuning parameters:
## 
##   k   RMSE      Rsquared   MAE     
##    1  4.126201  0.4656251  3.292210
##    2  3.339381  0.6115992  2.680356
##    3  3.111090  0.6698550  2.487983
##    4  3.048647  0.6882174  2.413970
##    5  2.929483  0.7257043  2.343114
##    6  2.981470  0.7252113  2.377399
##    7  2.980867  0.7346279  2.364239
##    8  2.945931  0.7556189  2.330560
##    9  2.962563  0.7595212  2.327370
##   10  2.995640  0.7616218  2.335381
##   11  3.023577  0.7586904  2.358533
##   12  3.033196  0.7620611  2.358477
##   13  3.078707  0.7579581  2.389690
##   14  3.108492  0.7563926  2.413264
##   15  3.165608  0.7483678  2.476526
##   16  3.218547  0.7336794  2.534567
##   17  3.226190  0.7383504  2.534853
##   18  3.267865  0.7283689  2.565214
##   19  3.308487  0.7179080  2.594381
##   20  3.308323  0.7213690  2.598841
## 
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was k = 5.
my_knn_pred <- predict(my_knn_tune, newdata = the_test_data$x)
postResample(pred = my_knn_pred, obs = the_test_data$y)
##      RMSE  Rsquared       MAE 
## 3.2408846 0.5966595 2.5893265

We can see that our MARS model produces the greatest result. The Mars model only uses the informative predictors, X1-X5.

7.5

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

library(RANN)
library(AppliedPredictiveModeling)
## Warning: package 'AppliedPredictiveModeling' was built under R version 4.1.3
data(ChemicalManufacturingProcess)
(the_chem_imput <- preProcess(ChemicalManufacturingProcess[,-c(1)], method=c('knnImpute')))
## Created from 152 samples and 57 variables
## 
## Pre-processing:
##   - centered (57)
##   - ignored (0)
##   - 5 nearest neighbor imputation (57)
##   - scaled (57)
the_chem_mod <- predict(the_chem_imput, ChemicalManufacturingProcess[,-c(1)])
remove_cols <- nearZeroVar(the_chem_mod, names = TRUE, 
                           freqCut = 2, uniqueCut = 20)
all_cols <- colnames(the_chem_mod)
the_chem_mod <- the_chem_mod[ , setdiff(all_cols,remove_cols)]

my_train_row <- sort(sample(nrow(the_chem_mod), nrow(the_chem_mod)*.7))
my_train_x <- the_chem_mod[my_train_row,]
my_testSET_x <- the_chem_mod[-my_train_row,]
my_testSET_y <- ChemicalManufacturingProcess[my_train_row,1]
test_y_set <- ChemicalManufacturingProcess[-my_train_row,1]
  1. Which nonlinear regression model gives the optimal resampling and test set performance?

MARS

my_MARS_mod <- earth(x = my_train_x,
                  y = my_testSET_y)
my_MARS_mod
## Selected 14 of 22 terms, and 11 of 50 predictors
## Termination condition: RSq changed by less than 0.001 at 22 terms
## Importance: ManufacturingProcess32, ManufacturingProcess09, ...
## Number of terms at each degree of interaction: 1 13 (additive model)
## GCV 1.017632    RSS 76.24791    GRSq 0.6598796    RSq 0.7894014

SVM

my_SVM_mod <- train(x = my_train_x,
                  y = my_testSET_y,
                  method = "svmRadial",
                  preProc = c("center", "scale"),
                  tuneLength = 10,
                  trcontrol = trainControl(method = "cv"))
my_SVM_mod
## Support Vector Machines with Radial Basis Function Kernel 
## 
## 123 samples
##  50 predictor
## 
## Pre-processing: centered (50), scaled (50) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 123, 123, 123, 123, 123, 123, ... 
## Resampling results across tuning parameters:
## 
##   C       RMSE      Rsquared   MAE      
##     0.25  1.370144  0.4420109  1.1175270
##     0.50  1.303171  0.4694461  1.0569344
##     1.00  1.257901  0.4976300  1.0185670
##     2.00  1.218456  0.5268199  0.9858141
##     4.00  1.194018  0.5461582  0.9667939
##     8.00  1.183209  0.5528167  0.9592624
##    16.00  1.182635  0.5529198  0.9584900
##    32.00  1.182635  0.5529198  0.9584900
##    64.00  1.182635  0.5529198  0.9584900
##   128.00  1.182635  0.5529198  0.9584900
## 
## Tuning parameter 'sigma' was held constant at a value of 0.01690242
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were sigma = 0.01690242 and C = 16.
plot(my_MARS_mod, which = 1)

KNN

the_knn_model <- train(x = my_train_x,
                  y = my_testSET_y,
                  method = "knn",
                  preProc = c("center", "scale"),
                  tuneLength = 10)
the_knn_model
## k-Nearest Neighbors 
## 
## 123 samples
##  50 predictor
## 
## Pre-processing: centered (50), scaled (50) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 123, 123, 123, 123, 123, 123, ... 
## Resampling results across tuning parameters:
## 
##   k   RMSE      Rsquared   MAE     
##    5  1.403051  0.3649859  1.118401
##    7  1.385687  0.3829970  1.114186
##    9  1.390642  0.3755238  1.127027
##   11  1.372606  0.3989675  1.123948
##   13  1.385677  0.3900988  1.131468
##   15  1.396760  0.3846907  1.144324
##   17  1.411884  0.3736374  1.161561
##   19  1.412243  0.3760955  1.163317
##   21  1.416641  0.3750720  1.167144
##   23  1.423902  0.3706815  1.175266
## 
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was k = 11.

As we can see when viewing the R2 values, the MARS model is the best test set performance. You’ll notice that only 9 predictors are selected in this model.

  1. Which predictors are most important in the optimal nonlinear regres- sion 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?
evimp(my_MARS_mod)
##                        nsubsets   gcv    rss
## ManufacturingProcess32       13 100.0  100.0
## ManufacturingProcess09       12  65.6   70.6
## ManufacturingProcess13       11  37.2   49.5
## ManufacturingProcess42       10  35.3   46.6
## ManufacturingProcess01        9  30.7   42.2
## ManufacturingProcess38        8  28.8   39.3
## ManufacturingProcess33        7  25.0   35.5
## ManufacturingProcess44        5  24.7   31.1
## ManufacturingProcess05        3  18.2   23.2
## BiologicalMaterial03          2  10.3   16.9
## BiologicalMaterial01          1   9.0   12.5

If we look back at 6.3 our linear model from our results found Manufacturing Processes 20, 32, 6, 9, 13 and 36 as the most important. Three of these predictors are also present in our MARS model from at the top. Manufacturing processes are strongest on this list similar to that of our optimal linear model.

  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?
the_best_predi <- c("ManufacturingProcess32", "ManufacturingProcess09", "ManufacturingProcess13","ManufacturingProcess01", "ManufacturingProcess42","ManufacturingProcess43")
featurePlot(my_train_x[,the_best_predi], my_testSET_y)

Manufacturing processes 32 and 9 appear to have positive relationships with our predictor. Then you’ll notice that meanwhile Process 13 shows a similar negative relationship. Our relationships for Processes 1, 42 and 43 seem to be largely influenced by outliers in the data. However though removing these outliers before the modeling led to significant drops in the accuracy of the models. We can say that this suggests they are not necessarily erroneous data points.