The following assignment will explore exercises 7.2 and 7.5 from Kuhn and Johnson’s book: Applied Predictive Modeling.
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(\pi x_1 x_2) + 20(x_3-0.5)^2 + 10x_4 + 5x_5 + N (0, \sigma^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)library(caret)
Loading required package: ggplot2
Loading required package: lattice
library(AppliedPredictiveModeling)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)featurePlot(trainingData$x, trainingData$y)
## 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)
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.466085 0.5121775 2.816838
7 3.349428 0.5452823 2.727410
9 3.264276 0.5785990 2.660026
11 3.214216 0.6024244 2.603767
13 3.196510 0.6176570 2.591935
15 3.184173 0.6305506 2.577482
17 3.183130 0.6425367 2.567787
19 3.198752 0.6483184 2.592683
21 3.188993 0.6611428 2.588787
23 3.200458 0.6638353 2.604529
RMSE was used to select the optimal model using the smallest value.
The final value used for the model was k = 17.
knnPred <-predict(knnModel, newdata = testData$x)## The function 'postResample' can be used to get the test set## perforamnce valuespostResample(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)?
library(nnet)library(earth)
Loading required package: Formula
Loading required package: plotmo
Loading required package: plotrix
library(e1071) 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
# Define training controlctrl <-trainControl(method ="cv", number =10)
The MARS model provides the best performance for this data, as it it had the lowest RMSE (1.813) and explains the most variance (around 87%). Also, it has the smallest average error (1.391) compared to SVM or neural networks.
summary(marsModel$finalModel)
Call: earth(x=data.frame[200,10], y=c(18.46,16.1,17...), keepxy=TRUE, degree=1,
nprune=13)
coefficients
(Intercept) 18.451984
h(0.621722-X1) -11.074396
h(0.601063-X2) -10.744225
h(X3-0.281766) 20.607853
h(0.447442-X3) 17.880232
h(X3-0.447442) -23.282007
h(X3-0.636458) 15.150350
h(0.734892-X4) -10.027487
h(X4-0.734892) 9.092045
h(0.850094-X5) -4.723407
h(X5-0.850094) 10.832932
h(X6-0.361791) -1.956821
Selected 12 of 18 terms, and 6 of 10 predictors (nprune=13)
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
We can see that the MARS model correctly selected all 5 informative variables: X1 through X5. It also included X6 (a noise variable), although only weakly, as shown by its small coefficient and low importance. The model also ignored the completely non-informative variables: X7 to X10
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.
data(ChemicalManufacturingProcess)
cmp <-data.frame(ChemicalManufacturingProcess)
library(RANN)# Impute missing values preProc <-preProcess(cmp, method ="knnImpute") # or "medianImpute"# Applying the preprocessing to fill in missing valuescmp_imputed <-predict(preProc, newdata = cmp)# Checking if any NAs remainsum(is.na(cmp_imputed))
[1] 0
# Use the imputed data from earlierdf <- cmp_imputed# Remove near-zero variance predictorsnzv <-nearZeroVar(df)df <- df[, -nzv]# Splitting data into training and testingset.seed(48)split_index <-createDataPartition(df$Yield, p =0.8, list =FALSE)train_data <- df[split_index, ]test_data <- df[-split_index, ]
# Define training control (10-fold CV)ctrl <-trainControl(method ="cv", number =10)
# Set up predictors and outcomex_train <- train_data[, setdiff(names(train_data), "Yield")]y_train <- train_data$Yieldx_test <- test_data[, setdiff(names(test_data), "Yield")]y_test <- test_data$Yield
RMSE Rsquared MAE
KNN 0.585 0.516 0.464
NeuralNet 0.835 0.403 0.570
SVM 0.527 0.588 0.417
MARS 0.745 0.407 0.603
SVM seems to handle the underlying patterns in the data most effectively, evidenced by the lowest RMSE (0.527) and highest variance explained (around 58%), possibly because of nonlinear interactions or complex decision boundaries. Its worth mentioning that KNN did decently (especially better than Neural Networks and MARS), but likely suffered from sensitivity to high-dimensional space.
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?
7 out of 10 are process-related variables, while 3 are biological. Process variables dominate in the SVM model, making up 70% of the top 10 predictors. This might indicate that process control factors (suchas equipment settings, temperature, timing) are more influential in determining chemical yield than the biological materials used.
# Predict the PLS setpls_pred <-predict(pls_model, newdata = test_data)
# variable importance for PLS modelimportance <-varImp(pls_model, scale =TRUE)
Attaching package: 'pls'
The following object is masked from 'package:caret':
R2
The following object is masked from 'package:stats':
loadings
pls_data <- importance$importancepls_data$Variable <-rownames(pls_data)# Get top 10 by importancetop_pls <- pls_data[order(-pls_data$Overall), ][1:10, ]# Plot using ggplot2ggplot(top_pls, aes(x =reorder(Variable, Overall), y = Overall)) +geom_point(size =3) +coord_flip() +labs(title ="Top 10 Variable Importance: PLS Model",x ="Variable",y ="Importance") +theme_minimal() +theme(plot.title =element_text(hjust =0.5, face ="bold"))
6 variables are shared across both models, which is a strong indicators of consistent importance. SVM picks up a few unique predictors (Process31, Bio12, Bio03).
Both models agree that process-related predictors are more important for yield outcomes.
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?
We have already established that the following predictors are unique to the SVM model:
ManufacturingProcess31
BiologicalMaterial12
BiologicalMaterial03
# We'll combine predictors and response for easy plottingsvm_top_vars <-c("ManufacturingProcess31", "BiologicalMaterial12", "BiologicalMaterial03", "Yield")plot_data <- train_data[, svm_top_vars]# Then we'll plot each predictor vs. Yieldfor (var innames(plot_data)[-which(names(plot_data) =="Yield")]) { p <-ggplot(plot_data, aes_string(x = var, y ="Yield")) +geom_point(alpha =0.4) +geom_smooth(method ="loess", se =FALSE, color ="blue") +labs(title =paste("Yield vs", var),x = var,y ="Yield") +theme_minimal()print(p)}
Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
ℹ Please use tidy evaluation idioms with `aes()`.
ℹ See also `vignette("ggplot2-in-packages")` for more information.
`geom_smooth()` using formula = 'y ~ x'
`geom_smooth()` using formula = 'y ~ x'
`geom_smooth()` using formula = 'y ~ x'
ManufacturingProcess31:This variable may represent a process control parameter (such as feed rate, temperature set point) that has an optimal low range, but causes yield to decline sharply if it’s pushed too far. This U-shape would not be captured by a linear model like PLS, which likely explains why SVM picked it up as important.
BiologicalMatieral12: This biological variable may have an effect that is threshold-dependent, as it starts to contribute positively to yield up to a point, but too much of it lowers yield again. For chemical processes this can be related to saturation or inhibitory biological effects
BiologicalMaterial03: Shows another example of a nonlinear influence. There’s a sweet spot for this input, but beyond that, its impact on yield diminishes or becomes negative. This subtle curvature would again be missed by a purely linear model.