LFMG-Lab-8

Author

Luis Munoz Grass

Non-Linear Regression

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)

Tune several models on these data. For example:

library(caret)
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.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 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)?

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 control
ctrl <- trainControl(method = "cv", number = 10)

Neural Network Model

set.seed(200)
nnetModel <- train(x = trainingData$x,
                   y = trainingData$y,
                   method = "nnet",
                   preProc = c("center", "scale"),
                   linout = TRUE,
                   trace = FALSE,
                   tuneLength = 5,
                   trControl = ctrl)
nnetPred <- predict(nnetModel, newdata = testData$x)
postResample(pred = nnetPred, obs = testData$y)
     RMSE  Rsquared       MAE 
2.2259232 0.8053693 1.6883152 

SVM

set.seed(200)
svmModel <- train(x = trainingData$x,
                  y = trainingData$y,
                  method = "svmRadial",
                  preProc = c("center", "scale"),
                  tuneLength = 10,
                  trControl = ctrl)
# Predict and evaluate
svmPred <- predict(svmModel, newdata = testData$x)
postResample(pred = svmPred, obs = testData$y)
     RMSE  Rsquared       MAE 
2.0541197 0.8290353 1.5586411 

MARS Model

set.seed(200)
marsModel <- train(x = trainingData$x,
                   y = trainingData$y,
                   method = "earth",
                   tuneLength = 10,
                   trControl = ctrl)

# Predict and evaluate
marsPred <- predict(marsModel, newdata = testData$x)
postResample(pred = marsPred, obs = testData$y)
     RMSE  Rsquared       MAE 
1.8136467 0.8677298 1.3911836 

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 values
cmp_imputed <- predict(preProc, newdata = cmp)

# Checking if any NAs remain
sum(is.na(cmp_imputed))
[1] 0
# Use the imputed data from earlier
df <- cmp_imputed

# Remove near-zero variance predictors
nzv <- nearZeroVar(df)
df <- df[, -nzv]

# Splitting data into training and testing
set.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 outcome
x_train <- train_data[, setdiff(names(train_data), "Yield")]
y_train <- train_data$Yield

x_test <- test_data[, setdiff(names(test_data), "Yield")]
y_test <- test_data$Yield

KNN Model

set.seed(48)
knn_model <- train(
  x = x_train, y = y_train,
  method = "knn",
  preProcess = c("center", "scale"),
  tuneLength = 10,
  trControl = ctrl
)
knn_pred <- predict(knn_model, newdata = x_test)

Neural Network

set.seed(48)
nnet_model <- train(
  x = x_train, y = y_train,
  method = "nnet",
  preProcess = c("center", "scale"),
  linout = TRUE,
  trace = FALSE,
  tuneLength = 5,
  trControl = ctrl
)
nnet_pred <- predict(nnet_model, newdata = x_test)

SVM

set.seed(48)
svm_model <- train(
  x = x_train, y = y_train,
  method = "svmRadial",
  preProcess = c("center", "scale"),
  tuneLength = 10,
  trControl = ctrl
)
svm_pred <- predict(svm_model, newdata = x_test)

MARS

set.seed(48)
mars_model <- train(
  x = x_train, y = y_train,
  method = "earth",
  tuneLength = 10,
  trControl = ctrl
)
mars_pred <- predict(mars_model, newdata = x_test)

a)

Which nonlinear regression model gives the optimal resampling and test set performance?

results <- rbind(
  KNN = postResample(knn_pred, y_test),
  NeuralNet = postResample(nnet_pred, y_test),
  SVM = postResample(svm_pred, y_test),
  MARS = postResample(mars_pred, y_test)
)

print(round(results, 3))
           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?

SVM Predictors

# variable importance for SVM model
svm_varimp <- varImp(svm_model, scale = TRUE)
svm_data <- svm_varimp$importance
svm_data$Variable <- rownames(svm_data)
top_svm <- svm_data[order(-svm_data$Overall), ][1:10, ]

# Plot with ggplot2
ggplot(top_svm, aes(x = reorder(Variable, Overall), y = Overall)) +
  geom_point() +
  coord_flip() +
  labs(title = "Top 10 Variable Importance: SVM Model",
       x = "Variable",
       y = "Importance") +
  theme_minimal()

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.

PLS Predictors

# Train PLS model
pls_model <- train(
  Yield ~ .,
  data = train_data,
  method = "pls",
  preProcess = c("center", "scale"),
  tuneLength = 25,
  trControl = trainControl(method = "cv", number = 10)
)
# Predict the PLS set
pls_pred <- predict(pls_model, newdata = test_data)
# variable importance for PLS model
importance <- 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$importance
pls_data$Variable <- rownames(pls_data)

# Get top 10 by importance
top_pls <- pls_data[order(-pls_data$Overall), ][1:10, ]

# Plot using ggplot2
ggplot(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 plotting
svm_top_vars <- c("ManufacturingProcess31", "BiologicalMaterial12", "BiologicalMaterial03", "Yield")
plot_data <- train_data[, svm_top_vars]

# Then we'll plot each predictor vs. Yield
for (var in names(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.