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.
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
library(nnet)
library(earth)
## Loading required package: Formula
## Loading required package: plotmo
## Loading required package: plotrix
library(kernlab)
##
## Attaching package: 'kernlab'
## The following object is masked from 'package:ggplot2':
##
## alpha
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
Friedman (1991) introduced several benchmark data sets create by simulation. One of these simulations used the following nonlinear equation to create data: y = 10sin(3.14x1x2)+ 20(x 3 - 0.5)2 +10x4 +5x5 +N(0,(tetha)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:
## KNN model - K-Nearest Neighbors
knnModel <- train(
x = trainingData$x,
y = trainingData$y,
method = "knn",
preProc = c("center", "scale"),
tuneLength = 10 # this will try 10 different values of the closest neighbor using the cross validation
)
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.2040595 0.6819919 2.5683461
Which models appear to give the best performance? Does MARS select the informative predictors (those named X1–X5)?
## MARS - Multivariate Adaptive Regression Splines
marsModel = train(x = trainingData$x,
y = trainingData$y,
method = "earth", # mars model
tuneLength = 10)
# we are using the mars model here to predict our data
marsPred = predict(marsModel, newdata = testData$x)
# postResample gives us the performace metric
postResample(pred = marsPred, obs = testData$y)
## RMSE Rsquared MAE
## 1.776575 0.872700 1.358367
varImp(marsModel)
## earth variable importance
##
## Overall
## X1 100.00
## X4 82.78
## X2 64.18
## X5 40.21
## X3 28.14
## X6 0.00
# Support Vector Machines Model
svmModel = train(x = trainingData$x,
y = trainingData$y,
method = "svmRadial", # the svm methond using the radial function (it draws curves to fit the data)
preProc = c("center", "scale"),
tuneLength = 10)
svmPred = predict(svmModel, newdata = testData$x)
postResample(pred = svmPred, obs = testData$y)
## RMSE Rsquared MAE
## 2.0792960 0.8247794 1.5796158
Which models appear to give the best performance? Does MARS select the informative predictors (those named X1–X5)?
According to the models the MARS model outperforms the other models as the lowest RMSE and high R^2 suggest the data fits the predictor variables in the most accurate matter in the test set. Observing the MARS model with the varImP function, the MARS model focusing on the X1,X4, and X2 as the variables they play the most role, with X5 and X3 have a more moderate weight assigned to them. X6 seems to lack importance to the model. The MARS model goal is to focus on the real predictors and ignore irrelevant ones, this help capture the non linear and linear relationship in the Friedman equation.
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(AppliedPredictiveModeling)
data(ChemicalManufacturingProcess)
dim(ChemicalManufacturingProcess)
## [1] 176 58
# Filling out missing values with imputation method
# we are pre processing the data with the k to nearest neighbour to fill out missing values
preprocessed_data = preProcess(ChemicalManufacturingProcess, method = "knnImpute") # this uses the k to nearst neightbour approach to impuate the data
# predict fuction will appy the KNN to the new data
imputed_data = predict(preprocessed_data, newdata = ChemicalManufacturingProcess)
sum(is.na(imputed_data))
## [1] 0
dim(imputed_data)
## [1] 176 58
set.seed(909)
#### Spliting the data into a training and a test set
# Yield is the response variable that we want to predict
# we use the default 80/20 split
split_index = createDataPartition(imputed_data$Yield, p = 0.8, list = FALSE)
train_imputed = imputed_data[split_index, ]
test_imputed = imputed_data[-split_index, ]
# Using 10 cross fold validation
training_ctrl2 = trainControl(method = "cv", number = 10)
## KNN Model frist
# set seed to replicate the finding
set.seed(867)
knn_model1 = train(
Yield ~ .,
data = train_imputed,
method = "knn",
trControl = training_ctrl2,
preProcess = c("center", "scale"),
tuneLength = 10
)
knn_model1
## k-Nearest Neighbors
##
## 144 samples
## 57 predictor
##
## Pre-processing: centered (57), scaled (57)
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 130, 128, 130, 130, 131, 129, ...
## Resampling results across tuning parameters:
##
## k RMSE Rsquared MAE
## 5 0.6772870 0.5517055 0.5375756
## 7 0.6901350 0.5447538 0.5576005
## 9 0.6806098 0.5678120 0.5491848
## 11 0.6795760 0.5853885 0.5470108
## 13 0.6930942 0.5751850 0.5621648
## 15 0.6969838 0.5876396 0.5645496
## 17 0.6969125 0.5967771 0.5588695
## 19 0.7129047 0.5877830 0.5684541
## 21 0.7185113 0.5947846 0.5723757
## 23 0.7402162 0.5500163 0.5950171
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was k = 5.
# Predicting using the test
knn_pred1 = predict(knn_model1, newdata = test_imputed)
knn_perf1 = postResample(pred = knn_pred1, obs = test_imputed$Yield)
knn_perf1
## RMSE Rsquared MAE
## 0.7710947 0.4782773 0.6434329
## Support Vector Machine Model
set.seed(867)
svm_model1 = train(
Yield ~ .,
data = train_imputed,
method = "svmRadial",
preProcess = c("center", "scale"),
trControl = training_ctrl2,
tuneLength = 10
)
svm_model1
## Support Vector Machines with Radial Basis Function Kernel
##
## 144 samples
## 57 predictor
##
## Pre-processing: centered (57), scaled (57)
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 130, 128, 130, 130, 131, 129, ...
## Resampling results across tuning parameters:
##
## C RMSE Rsquared MAE
## 0.25 0.7196941 0.5766603 0.5794814
## 0.50 0.6526657 0.6142038 0.5223810
## 1.00 0.6057115 0.6415172 0.4804502
## 2.00 0.5894589 0.6554019 0.4687012
## 4.00 0.5745009 0.6694707 0.4526938
## 8.00 0.5764204 0.6675196 0.4534981
## 16.00 0.5768791 0.6663558 0.4530071
## 32.00 0.5768791 0.6663558 0.4530071
## 64.00 0.5768791 0.6663558 0.4530071
## 128.00 0.5768791 0.6663558 0.4530071
##
## Tuning parameter 'sigma' was held constant at a value of 0.01348959
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were sigma = 0.01348959 and C = 4.
## Predicting using the test
svm_pred1 = predict(svm_model1, newdata = test_imputed)
svm_perf1 = postResample(pred = svm_pred1, obs = test_imputed$Yield)
svm_perf1
## RMSE Rsquared MAE
## 0.6791558 0.5939206 0.5591919
## MARS Model
set.seed(867)
mars_model1 = train(
Yield ~ .,
data = train_imputed,
method = "earth",
trControl = training_ctrl2,
tuneLength = 10
)
mars_model1
## Multivariate Adaptive Regression Spline
##
## 144 samples
## 57 predictor
##
## No pre-processing
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 130, 128, 130, 130, 131, 129, ...
## Resampling results across tuning parameters:
##
## nprune RMSE Rsquared MAE
## 2 0.7516170 0.4439400 0.5869173
## 3 0.6983608 0.5232011 0.5479149
## 5 0.6910085 0.5866238 0.5298736
## 7 0.6411011 0.6413363 0.4905415
## 8 0.6247817 0.6315669 0.4847252
## 10 0.6258235 0.6427898 0.4860471
## 12 0.6297862 0.6451166 0.4746899
## 13 0.6276911 0.6499796 0.4749349
## 15 0.6179746 0.6636888 0.4721940
## 17 0.6239996 0.6622178 0.4717624
##
## Tuning parameter 'degree' was held constant at a value of 1
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were nprune = 15 and degree = 1.
mars_pred1 = predict(mars_model1, newdata = test_imputed)
mars_perf1 = postResample(pred = mars_pred1, obs = test_imputed$Yield)
mars_perf1
## RMSE Rsquared MAE
## 0.7036671 0.5625963 0.5507725
The Root Mean Square Error is useful in helping us find how the close the predicted value is with the observed value, a low RSME indicted a good fit to data. The support vector machine, is the model with the lowest RSME of 0.68. The R square shows us the variation in response variable which is “Yield”, as it relates to explaining the x variable or predictor variable. When we have high r squared it means “yield” can explain changes in the data, and if r square closer to 1 it explains the data more. The SVM model has the highest r squared of 0.59, which explained the most variance in the data. The SVM model has the best performance as it optimal for having low RSME and high r squared
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?
varImp(svm_model1)
## loess r-squared variable importance
##
## only 20 most important variables shown (out of 57)
##
## Overall
## ManufacturingProcess32 100.00
## ManufacturingProcess13 96.87
## BiologicalMaterial06 94.60
## BiologicalMaterial03 89.36
## ManufacturingProcess09 84.60
## ManufacturingProcess36 79.90
## ManufacturingProcess17 77.46
## BiologicalMaterial12 77.01
## BiologicalMaterial02 75.16
## ManufacturingProcess31 69.11
## ManufacturingProcess06 60.42
## BiologicalMaterial04 54.04
## BiologicalMaterial08 51.97
## BiologicalMaterial11 49.86
## ManufacturingProcess11 49.69
## BiologicalMaterial01 45.39
## ManufacturingProcess33 44.10
## ManufacturingProcess29 40.28
## BiologicalMaterial09 38.34
## ManufacturingProcess30 35.98
Looking at the SVM model, the top ten predictors have six process variables and four process the biological variables. The six process variables are Manufacturing Process32, 13, 09, 36, 17, and 31. The biological variables are Biological Material 06, 03, 12, and 02.
If we try a linear model
set.seed(867)
lm_model = train(
Yield ~ ., # linear model method
data = train_imputed,
method = "lm",
trControl = training_ctrl2
)
varImp(lm_model)
## lm variable importance
##
## only 20 most important variables shown (out of 56)
##
## Overall
## ManufacturingProcess32 100.00
## ManufacturingProcess33 65.28
## ManufacturingProcess28 51.47
## ManufacturingProcess37 46.95
## ManufacturingProcess45 46.90
## ManufacturingProcess04 46.71
## ManufacturingProcess01 46.03
## ManufacturingProcess09 45.35
## ManufacturingProcess43 44.16
## ManufacturingProcess07 41.07
## ManufacturingProcess29 39.91
## BiologicalMaterial08 39.25
## BiologicalMaterial07 38.58
## ManufacturingProcess38 38.53
## ManufacturingProcess20 34.17
## ManufacturingProcess03 33.43
## BiologicalMaterial02 33.43
## ManufacturingProcess18 33.42
## BiologicalMaterial10 29.60
## ManufacturingProcess17 27.71
Looking at the linear model, we can observe all top ten predictors are process variables. Both models do agree the Manufacturing Process32 plays role in determining the yield. However, the SVM model has more biological variables, which means that it take into account the non linear relationships between the biological and process variables. The linear model seems to be only relying the process variables. If the linear model is only relying on process variables it will be adding up the only these variable, meaning like additive model. This model will not capture any complex relationships between the process and biological variables. The SVM can set different kernel in different planes using the degree to capture more complex relationship between the process and biological variables. (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?
# making a list of the 6 process variables and 4 biological variables from the SVM model
process_variables = c("ManufacturingProcess32", "ManufacturingProcess13", "ManufacturingProcess09",
"ManufacturingProcess36", "ManufacturingProcess17", "ManufacturingProcess31")
bio_variables = c("BiologicalMaterial06", "BiologicalMaterial03", "BiologicalMaterial12", "BiologicalMaterial02")
import_variables = c(process_variables,bio_variables )
# make the x and y data to plot using our feature plot
train_x = train_imputed %>% select(all_of(import_variables))
train_y = train_imputed$Yield
# Feature plot function
featurePlot(x = train_x, y = train_y)
Observing our plots, the Manufacturing Process32 variable being the most important variable is shown to have highest positive correlation among the biological and processor variable. As the variable importance begins to decrease the strength of the correlation also diminishes. However, the biological predictors are stronger positive relationship with the response variable “Yield”, compared to the process predictor variables.