library(mlbench)
library(AppliedPredictiveModeling)
library(caret)
library(kableExtra)
library(tidyverse)

Exercise 7.2

Friedman (1991) introduced several benchmark datasets created by simulation. One of these simulations used the following non-linear 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. The package mlbench contains a function called mlbench.friedman1 that simulates these data:

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:

kNN Model

set.seed(1022)
knn_model <- train(trainingData$x, trainingData$y,
                   method="knn", preProc = c("center", "scale"),
                   tuneLength = 10,
                   trControl = trainControl(method="cv"))

knn_model
## 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     
##    5  3.173759  0.6283665  2.591536
##    7  3.048162  0.6762389  2.500213
##    9  3.017291  0.7037945  2.467085
##   11  3.027974  0.7095901  2.468808
##   13  3.009832  0.7210308  2.433241
##   15  3.013201  0.7385897  2.436664
##   17  3.057830  0.7361354  2.469123
##   19  3.061648  0.7383189  2.477887
##   21  3.094299  0.7460803  2.511588
##   23  3.110940  0.7534826  2.541559
## 
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was k = 13.
print(paste0("The best tune for knn model is ", knn_model$bestTune))
## [1] "The best tune for knn model is 13"
# Prediction
knn_pred <- predict(knn_model, testData$x) 

# Performance using postResample
knn_rs <- postResample(knn_pred, testData$y)
knn_rs
##      RMSE  Rsquared       MAE 
## 3.1481557 0.6747755 2.5236041

RMSE was used to select the model based on performance and optimal value of k is 9. Using postResample, I also tested out the performance of the model on the test dataset is 3.11 which is slightly higher than optimal value’s RMSE but still very close to training model’s RMSE which is 3.05. The data was preprocessed with centering and scaling to make the data normal before training and testing process.

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

Now, I am going to create some more models using the same dataset to see the performance of other non-linear techniques. First, I am going to create a model on training data and then I will check its performance on evaluation dataset to see consistency among both datasets.

# SVM Model
set.seed(1022)
svm_model <- train(trainingData$x, trainingData$y,
                   method="svmRadial", preProc = c("center", "scale"),
                   tuneLength = 10,
                   trControl = trainControl(method="cv"))

svm_model
## 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.499238  0.8073027  2.011201
##     0.50  2.252688  0.8234714  1.807005
##     1.00  2.060796  0.8489803  1.632269
##     2.00  1.986108  0.8595599  1.571340
##     4.00  1.921934  0.8634881  1.532417
##     8.00  1.906471  0.8629760  1.527013
##    16.00  1.916319  0.8623742  1.542869
##    32.00  1.916158  0.8623776  1.543348
##    64.00  1.916158  0.8623776  1.543348
##   128.00  1.916158  0.8623776  1.543348
## 
## Tuning parameter 'sigma' was held constant at a value of 0.06047444
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were sigma = 0.06047444 and C = 8.
svm_model$bestTune
##        sigma C
## 6 0.06047444 8
# MARS
grid <- expand.grid(.degree = 1:2, .nprune = 2:38) 
mars_model = train(x = trainingData$x, 
                  y = trainingData$y, 
                  method = "earth", 
                  tuneGrid = grid, 
                  trControl = trainControl(method = "cv", 
                                           number = 10))
## Loading required package: earth
## Loading required package: Formula
## Loading required package: plotmo
## Loading required package: plotrix
## Loading required package: TeachingDemos
mars_model
## 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.452277  0.2207817  3.664973
##   1        3      3.674100  0.4548422  2.947023
##   1        4      2.581277  0.7507544  2.076075
##   1        5      2.309142  0.7933947  1.866451
##   1        6      2.230662  0.8065339  1.791503
##   1        7      1.734309  0.8832923  1.362380
##   1        8      1.661116  0.8907060  1.305004
##   1        9      1.650752  0.8879603  1.298088
##   1       10      1.618518  0.8920204  1.274664
##   1       11      1.584333  0.8949761  1.240652
##   1       12      1.585614  0.8935265  1.242030
##   1       13      1.604842  0.8911546  1.249035
##   1       14      1.609106  0.8903342  1.252403
##   1       15      1.609106  0.8903342  1.252403
##   1       16      1.609106  0.8903342  1.252403
##   1       17      1.609106  0.8903342  1.252403
##   1       18      1.609106  0.8903342  1.252403
##   1       19      1.609106  0.8903342  1.252403
##   1       20      1.609106  0.8903342  1.252403
##   1       21      1.609106  0.8903342  1.252403
##   1       22      1.609106  0.8903342  1.252403
##   1       23      1.609106  0.8903342  1.252403
##   1       24      1.609106  0.8903342  1.252403
##   1       25      1.609106  0.8903342  1.252403
##   1       26      1.609106  0.8903342  1.252403
##   1       27      1.609106  0.8903342  1.252403
##   1       28      1.609106  0.8903342  1.252403
##   1       29      1.609106  0.8903342  1.252403
##   1       30      1.609106  0.8903342  1.252403
##   1       31      1.609106  0.8903342  1.252403
##   1       32      1.609106  0.8903342  1.252403
##   1       33      1.609106  0.8903342  1.252403
##   1       34      1.609106  0.8903342  1.252403
##   1       35      1.609106  0.8903342  1.252403
##   1       36      1.609106  0.8903342  1.252403
##   1       37      1.609106  0.8903342  1.252403
##   1       38      1.609106  0.8903342  1.252403
##   2        2      4.452277  0.2207817  3.664973
##   2        3      3.674100  0.4548422  2.947023
##   2        4      2.581277  0.7507544  2.076075
##   2        5      2.383232  0.7759651  1.924988
##   2        6      2.270108  0.7983252  1.787789
##   2        7      1.746874  0.8795368  1.401529
##   2        8      1.641369  0.9004659  1.285754
##   2        9      1.489229  0.9163921  1.188211
##   2       10      1.477874  0.9222741  1.181550
##   2       11      1.397273  0.9280190  1.099243
##   2       12      1.377479  0.9299194  1.095010
##   2       13      1.351624  0.9310468  1.085818
##   2       14      1.319239  0.9334780  1.060512
##   2       15      1.280432  0.9365961  1.021266
##   2       16      1.283624  0.9372051  1.021235
##   2       17      1.299249  0.9353371  1.033555
##   2       18      1.297935  0.9353515  1.032271
##   2       19      1.297935  0.9353515  1.032271
##   2       20      1.297935  0.9353515  1.032271
##   2       21      1.297935  0.9353515  1.032271
##   2       22      1.297935  0.9353515  1.032271
##   2       23      1.297935  0.9353515  1.032271
##   2       24      1.297935  0.9353515  1.032271
##   2       25      1.297935  0.9353515  1.032271
##   2       26      1.297935  0.9353515  1.032271
##   2       27      1.297935  0.9353515  1.032271
##   2       28      1.297935  0.9353515  1.032271
##   2       29      1.297935  0.9353515  1.032271
##   2       30      1.297935  0.9353515  1.032271
##   2       31      1.297935  0.9353515  1.032271
##   2       32      1.297935  0.9353515  1.032271
##   2       33      1.297935  0.9353515  1.032271
##   2       34      1.297935  0.9353515  1.032271
##   2       35      1.297935  0.9353515  1.032271
##   2       36      1.297935  0.9353515  1.032271
##   2       37      1.297935  0.9353515  1.032271
##   2       38      1.297935  0.9353515  1.032271
## 
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were nprune = 15 and degree = 2.
mars_model$bestTune
##    nprune degree
## 51     15      2
set.seed(2003)
# NEURAL NETWORK
neural_grid <- expand.grid(.decay=c(0, 0.01, 0.1, 0.5, 0.9),
                        .size=c(1, 10, 15, 20),
                        .bag=FALSE)

neuralnet_model <- train(x = trainingData$x,
                   y = trainingData$y,
                   method = "avNNet",
                   tuneGrid = neural_grid,
                   preProc = c("center", "scale"),
                   trace=FALSE,
                   linout=TRUE,
                   maxit=500)
## Warning: executing %dopar% sequentially: no parallel backend registered
neuralnet_model
## Model Averaged Neural Network 
## 
## 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:
## 
##   decay  size  RMSE      Rsquared   MAE     
##   0.00    1    2.580094  0.7262377  2.036771
##   0.00   10    2.845852  0.6854213  2.224146
##   0.00   15    2.714280  0.7065816  2.173395
##   0.00   20    2.649439  0.7179040  2.096968
##   0.01    1    2.556306  0.7342057  2.001798
##   0.01   10    2.726078  0.7070341  2.153211
##   0.01   15    2.452101  0.7572746  1.939110
##   0.01   20    2.310577  0.7823350  1.825238
##   0.10    1    2.553928  0.7339911  1.996684
##   0.10   10    2.569403  0.7343516  2.043793
##   0.10   15    2.246317  0.7927875  1.780743
##   0.10   20    2.219793  0.7981377  1.734306
##   0.50    1    2.588248  0.7262760  2.032363
##   0.50   10    2.345030  0.7735504  1.854954
##   0.50   15    2.221907  0.7976969  1.754026
##   0.50   20    2.212676  0.7995400  1.741924
##   0.90    1    2.613745  0.7204892  2.054595
##   0.90   10    2.315529  0.7792950  1.829150
##   0.90   15    2.197773  0.8013546  1.730315
##   0.90   20    2.187873  0.8035823  1.717961
## 
## Tuning parameter 'bag' was held constant at a value of FALSE
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were size = 20, decay = 0.9 and bag = FALSE.
neuralnet_model$bestTune
##    size decay   bag
## 20   20   0.9 FALSE

The final values used for Support Vector Machines for sigma is 0.064 and for C is 8 which RMSE value of 1.87 for training dataset. Now let’s evaluate it on test dataset. The final optimal values of nrpune and degree are 14 and 2 respectively for MARS model with the RMSE value of 1.20. THe best values for the model were throug using size of 20 and decay value of 0.9 which got the RMSE value of 2.18.

# Prediction
svm_pred <- predict(svm_model, testData$x)
mars_pred <- predict(mars_model, testData$x)
neuralnet_pred <- predict(neuralnet_model, testData$x)

# Performance of test data
svm_rs <- postResample(svm_pred, testData$y)
mars_rs <- postResample(mars_pred, testData$y)
neural_rs <- postResample(neuralnet_pred, testData$y)

all <- data.frame(rbind(knn_rs, svm_rs, mars_rs, neural_rs))
all %>% kable() %>% kable_styling()
RMSE Rsquared MAE
knn_rs 3.148156 0.6747755 2.523604
svm_rs 2.044533 0.8305739 1.550716
mars_rs 1.158995 0.9460418 0.925023
neural_rs 1.950621 0.8473327 1.483476

According to the values of RMSE, it seems that MARS model performed as its value is 1.17 and it is lower than the closest which is Neural Network’s model. I would choose MARS model based on it’s performance of RMSE.

Does MARS model picked the most imformative variables, X1 - X5

varImp(mars_model)
## earth variable importance
## 
##    Overall
## X1  100.00
## X4   75.24
## X2   48.73
## X5   15.52
## X3    0.00

Yes MARS model seems to pick the most informative variables (X1 - X5) with X5 the most important and X3 the least important among them

Exercise 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 non-linear regression models.

I had used multiple approaches in previous homework but here I am going to use preProcess for data processing and impute the missing values using bagImpute method to make it easier.

# Chemical dataset 
data("ChemicalManufacturingProcess")

# Preprocessing
chemical_imp <- preProcess(ChemicalManufacturingProcess[, -c(1)], method='bagImpute')

# Replacing
cmp <- predict(chemical_imp, ChemicalManufacturingProcess[, -c(1)])

# Checking for missing values
print(paste0("Total missing values are ", sum(is.na(cmp)), " after imputation"))
## [1] "Total missing values are 0 after imputation"
# Splitting the data into training and test datasets 
set.seed(300)
trainRow <- createDataPartition(ChemicalManufacturingProcess$Yield, p=0.8, list=FALSE)
train_X <- cmp[trainRow, ]
train_y <- ChemicalManufacturingProcess$Yield[trainRow]
test_X <- cmp[-trainRow, ]
test_y <- ChemicalManufacturingProcess$Yield[-trainRow]

kNN Model

set.seed(44)
knn_model <- train(x = train_X,
                  y = train_y,
                  method = "knn",
                  preProc = c("center", "scale"),
                  tuneLength = 10)

knn_model
## k-Nearest Neighbors 
## 
## 144 samples
##  57 predictor
## 
## Pre-processing: centered (57), scaled (57) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 144, 144, 144, 144, 144, 144, ... 
## Resampling results across tuning parameters:
## 
##   k   RMSE      Rsquared   MAE     
##    5  1.527911  0.3678610  1.187884
##    7  1.519585  0.3709523  1.203161
##    9  1.518325  0.3757026  1.207144
##   11  1.523818  0.3721955  1.215264
##   13  1.525789  0.3741249  1.221943
##   15  1.522011  0.3778194  1.224925
##   17  1.537326  0.3643882  1.236908
##   19  1.543869  0.3626676  1.244601
##   21  1.547676  0.3644617  1.247946
##   23  1.555157  0.3630633  1.254564
## 
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was k = 9.

The best model was derived with k value of 9 which gave RMSE of 1.44 as compared with the others.

MARS Model

grid_m <- expand.grid(.degree=1:2,
                        .nprune=2:10)
set.seed(1)
mars_model <- train(x = train_X,
                   y = train_y,
                   method = "earth",
                   tuneGrid = grid_m,
                   preProc = c("center", "scale"))

mars_model
## Multivariate Adaptive Regression Spline 
## 
## 144 samples
##  57 predictor
## 
## Pre-processing: centered (57), scaled (57) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 144, 144, 144, 144, 144, 144, ... 
## Resampling results across tuning parameters:
## 
##   degree  nprune  RMSE      Rsquared   MAE     
##   1        2      1.548426  0.3742101  1.205164
##   1        3      1.386261  0.4966968  1.090097
##   1        4      1.450635  0.4823316  1.104495
##   1        5      1.502578  0.4671243  1.112661
##   1        6      1.510882  0.4653294  1.123315
##   1        7      1.571690  0.4493483  1.149113
##   1        8      1.577054  0.4464274  1.154007
##   1        9      1.612938  0.4401431  1.185302
##   1       10      1.894327  0.4052218  1.251186
##   2        2      1.556893  0.3643403  1.212608
##   2        3      1.446495  0.4440674  1.142629
##   2        4      1.454170  0.4603020  1.134729
##   2        5      1.510655  0.4464401  1.159007
##   2        6      1.537862  0.4489997  1.168162
##   2        7      1.541855  0.4484965  1.151117
##   2        8      1.582445  0.4444166  1.164982
##   2        9      1.603902  0.4503004  1.180033
##   2       10      1.711123  0.4375254  1.204653
## 
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were nprune = 3 and degree = 1.

THe optimal values used for model were 4 for nprune and 1 for degree which gave RMSE value of 1.243. Seems like so far, MARS is performing slightly better than knn model.

SVM Model

set.seed(1)
svm_model <- train(x = train_X,
                        y = train_y,
                        method = "svmRadial",
                        tuneLength=10,
                        preProc = c("center", "scale"))
svm_model
## Support Vector Machines with Radial Basis Function Kernel 
## 
## 144 samples
##  57 predictor
## 
## Pre-processing: centered (57), scaled (57) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 144, 144, 144, 144, 144, 144, ... 
## Resampling results across tuning parameters:
## 
##   C       RMSE      Rsquared   MAE     
##     0.25  1.532038  0.4293934  1.220092
##     0.50  1.439895  0.4704321  1.131423
##     1.00  1.369086  0.5127028  1.068689
##     2.00  1.325070  0.5380060  1.028641
##     4.00  1.319076  0.5392843  1.019229
##     8.00  1.318641  0.5372721  1.018491
##    16.00  1.318070  0.5367568  1.018883
##    32.00  1.317942  0.5368591  1.018755
##    64.00  1.317942  0.5368591  1.018755
##   128.00  1.317942  0.5368591  1.018755
## 
## Tuning parameter 'sigma' was held constant at a value of 0.01197259
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were sigma = 0.01197259 and C = 32.

The best values for sigma is 0.01544 and C is 16 which gave RMSE of 1.23 which is even more better than MARS model’s performance results.

(a)

Which non-linear regression model gives the optimal resampling and test set performance?

Now let’s predict the predictors based on test datasets using all 3 models to see their performance on test dataset. It seems like SVM model is performing better on training dataset so far.

# Predicting
svm_pred <- predict(svm_model, test_X)
mars_pred <- predict(mars_model, test_X)
knn_pred <- predict(knn_model, test_X)

# Performance of test data
svm_rs <- postResample(svm_pred, test_y)
mars_rs <- postResample(mars_pred, test_y)
knn_rs <- postResample(knn_pred, test_y)

all_p <- data.frame(rbind(svm_rs, mars_rs, knn_rs))
all_p %>% kable() %>% kable_styling()
RMSE Rsquared MAE
svm_rs 0.8612864 0.7443962 0.7073954
mars_rs 1.1284219 0.5578690 0.8941468
knn_rs 1.1728039 0.5426135 0.8916701

As I was expecting, it seems like the results are consistent and SVM performed well on test set too as compared with knn model and MARS model. I would choose SVM Model in this exercise as the results were consistent in terms of performance both on training and test datasets.

(b)

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?

First I will check the important predictors using varImp function to see the top 10 important predictors using SVM model

varImp(svm_model)
## loess r-squared variable importance
## 
##   only 20 most important variables shown (out of 57)
## 
##                        Overall
## ManufacturingProcess32  100.00
## ManufacturingProcess13   87.13
## BiologicalMaterial06     83.80
## BiologicalMaterial03     75.25
## ManufacturingProcess36   71.54
## ManufacturingProcess17   67.96
## BiologicalMaterial02     66.39
## ManufacturingProcess09   65.20
## BiologicalMaterial12     62.23
## ManufacturingProcess31   59.04
## ManufacturingProcess33   53.85
## ManufacturingProcess06   52.87
## BiologicalMaterial04     48.45
## BiologicalMaterial01     43.46
## ManufacturingProcess29   41.46
## BiologicalMaterial11     40.17
## BiologicalMaterial08     38.33
## ManufacturingProcess11   37.45
## ManufacturingProcess30   35.45
## ManufacturingProcess12   25.89

As previously I said I chose SVM model based on its consistency in terms of performance, result shows that neither ManufacturingProcess dominates the list nor BiologicalMaterial. Although ManufacturingProcess32 is the most important predictor but next important predictor is BiologicalMaterial06. I won’t say anyone is dominating the list but the above are the top 10 predictors according to SVM Model. For the sake of comparison, I will check it on MARS model as it was slightly better than knn model.

varImp(mars_model)
## earth variable importance
## 
##                        Overall
## ManufacturingProcess32     100
## ManufacturingProcess09       0

According to MARS mode, there are only 3 variables that have importance. ManufacturingProcess32 is still a leading predictor but in this model ManufacturingProcess is dominating the list. At this point, it’s ideal to check for other criteria to avoid any under fitting or over fitting. For now I will choose SVM Model.

(c)

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?

plot(varImp(svm_model), top =10)

ManufacturingProcess32 and BiologicalMaterial06 are the top predictors leading by ManufacturingProcess13 and ManufacturingProcess36 and have strongest relationship with the target variable as per the SVM Model.