Friedman (1991) introduced several benchmark data sets create by simulation. One of these simulations used the following nonlinear equation to create data:
y=10sin(pix1x2) 20(x3-0.5)^2 10x4 5x5 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)
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:
set.seed(200)
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.654912 0.4779838 2.958475
## 7 3.529432 0.5118581 2.861742
## 9 3.446330 0.5425096 2.780756
## 11 3.378049 0.5723793 2.719410
## 13 3.332339 0.5953773 2.692863
## 15 3.309235 0.6111389 2.663046
## 17 3.317408 0.6201421 2.678898
## 19 3.311667 0.6333800 2.682098
## 21 3.316340 0.6407537 2.688887
## 23 3.326040 0.6491480 2.705915
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was k = 15.
ggplot(knnModel)
## 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.
## ℹ The deprecated feature was likely used in the caret package.
## Please report the issue at <https://github.com/topepo/caret/issues>.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
knnPred <- predict(knnModel, newdata = testData$x)
KNN <- postResample(pred = knnPred, obs = testData$y)
set.seed(200)
svmModel <- train(
x = trainingData$x,
y = trainingData$y,
method = "svmRadial",
preProcess = c("center", "scale"),
tuneLength = 10
)
svmModel
## Support Vector Machines with Radial Basis Function Kernel
##
## 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:
##
## C RMSE Rsquared MAE
## 0.25 2.635010 0.7685188 2.074977
## 0.50 2.423373 0.7839086 1.902162
## 1.00 2.284137 0.8001534 1.791779
## 2.00 2.196624 0.8126474 1.713560
## 4.00 2.143035 0.8209820 1.668024
## 8.00 2.119159 0.8246308 1.649388
## 16.00 2.117440 0.8248675 1.648570
## 32.00 2.117440 0.8248675 1.648570
## 64.00 2.117440 0.8248675 1.648570
## 128.00 2.117440 0.8248675 1.648570
##
## Tuning parameter 'sigma' was held constant at a value of 0.06299324
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were sigma = 0.06299324 and C = 16.
ggplot(svmModel)
svmPred <- predict(svmModel, newdata = testData$x)
SVM <- postResample(pred = svmPred, obs = testData$y)
set.seed(200)
marsGrid <- expand.grid(.degree = 1:2, .nprune = 2:15)
marsModel <- train(
x = trainingData$x,
y = trainingData$y,
method = "earth",
tuneGrid = marsGrid,
preProcess = c("center", "scale"),
trControl = trainControl(method = "repeatedcv", repeats = 5)
)
## Loading required package: earth
## Loading required package: Formula
## Loading required package: plotmo
## Loading required package: plotrix
marsModel
## Multivariate Adaptive Regression Spline
##
## 200 samples
## 10 predictor
##
## Pre-processing: centered (10), scaled (10)
## Resampling: Cross-Validated (10 fold, repeated 5 times)
## Summary of sample sizes: 180, 180, 180, 180, 180, 180, ...
## Resampling results across tuning parameters:
##
## degree nprune RMSE Rsquared MAE
## 1 2 4.386168 0.2412407 3.6346127
## 1 3 3.621483 0.4742386 2.9231886
## 1 4 2.595717 0.7297442 2.0796496
## 1 5 2.307259 0.7837985 1.8608089
## 1 6 2.266285 0.7932822 1.8080255
## 1 7 1.754388 0.8732428 1.3866966
## 1 8 1.704233 0.8796386 1.3397570
## 1 9 1.675474 0.8839704 1.3197799
## 1 10 1.676810 0.8839600 1.3176441
## 1 11 1.632768 0.8899677 1.2806226
## 1 12 1.608233 0.8933035 1.2612971
## 1 13 1.613222 0.8918455 1.2611245
## 1 14 1.617342 0.8914827 1.2661040
## 1 15 1.617399 0.8915040 1.2662071
## 2 2 4.409482 0.2317472 3.6671745
## 2 3 3.682748 0.4579520 2.9824702
## 2 4 2.639245 0.7168153 2.1195303
## 2 5 2.341532 0.7724607 1.8841376
## 2 6 2.278522 0.7872883 1.8001196
## 2 7 1.842893 0.8539659 1.4592226
## 2 8 1.697449 0.8799535 1.3142895
## 2 9 1.498504 0.9033193 1.1815401
## 2 10 1.459988 0.9092009 1.1634970
## 2 11 1.369342 0.9197769 1.0879287
## 2 12 1.323521 0.9265262 1.0464027
## 2 13 1.293398 0.9305220 1.0291551
## 2 14 1.260235 0.9350752 1.0040485
## 2 15 1.239833 0.9374279 0.9855537
##
## 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.
ggplot(marsModel)
marsPred <- predict(marsModel, newdata = testData$x)
MARS <- postResample(pred = marsPred, obs = testData$y)
set.seed(200)
rfModel <- train(
x = trainingData$x,
y = trainingData$y,
method = "rf",
tuneLength = 10,
importance = TRUE
)
## note: only 9 unique complexity parameters in default grid. Truncating the grid to 9 .
rfModel
## Random Forest
##
## 200 samples
## 10 predictor
##
## No pre-processing
## Resampling: Bootstrapped (25 reps)
## Summary of sample sizes: 200, 200, 200, 200, 200, 200, ...
## Resampling results across tuning parameters:
##
## mtry RMSE Rsquared MAE
## 2 3.019430 0.7816820 2.479291
## 3 2.819551 0.7819803 2.315196
## 4 2.732388 0.7736957 2.249866
## 5 2.671948 0.7693939 2.199314
## 6 2.660917 0.7603397 2.184271
## 7 2.664042 0.7517429 2.185740
## 8 2.665587 0.7462882 2.186260
## 9 2.675176 0.7403295 2.194417
## 10 2.688783 0.7340197 2.204558
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was mtry = 6.
ggplot(rfModel)
rfPred <- predict(rfModel, newdata = testData$x)
RF <- postResample(pred = rfPred, obs = testData$y)
I tuned several nonlinear regression models and evaluated their predictive performance using resampling to assess model stability and generalization.
For simpler models such as KNN, SVM and RF, I used the tuneLength argument in the train() function since these algorithms have relatively few tuning parameters.
For MARS, I used a tuning grid together with a trainControl setup instead of tuneLength because MARS has multiple interacting parameters that benefit from finer control. Using a defined grid made it easier to explore combinations of degree and pruning terms and get more stable RMSE estimates across cross-validation folds.
The MARS model performed best overall, with RMSE = ~1.19 and Rsquared = ~0.94, followed by SVM and Random Forest.
models_summary <- rbind(KNN, SVM, MARS, RF)
rownames(models_summary) <- c("KNN", "SVM", "MARS","RF")
cat("Model Performance Comparison:\n")
## Model Performance Comparison:
print(round(models_summary, 4))
## RMSE Rsquared MAE
## KNN 3.1751 0.6786 2.5443
## SVM 2.0737 0.8257 1.5752
## MARS 1.1909 0.9429 0.9497
## RF 2.4332 0.7998 1.9262
# Variable Importance for MARS
set.seed(200)
mars_var_imp <- varImp(marsModel)
print(mars_var_imp)
## earth variable importance
##
## Overall
## X1 100.00
## X4 75.31
## X2 48.86
## X5 15.61
## X3 0.00
mars_model_importance <- varImp(marsModel)$importance %>%
as.data.frame() %>%
rownames_to_column("Variable") %>%
arrange(desc(Overall)) %>%
mutate(importance = row_number())
Among the five nonlinear regression models, the MARS model clearly achieved the best performance, with the lowest RMSE (1.1909) and highest Rsquared (0.9429). This indicates it explained the greatest proportion of variance in the data and made the most accurate predictions.
The variable importance results show that MARS identified X1, X4, X2, and X5 as the most informative predictors, while X3 had an importance of 0. This suggests that the model effectively captured the key predictors influencing the response while excluding a less relevant variable.
Overall, the MARS model outperformed all other models in predictive accuracy and also correctly selected the main informative predictors (X1–X5).
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.
Which nonlinear regression model gives the optimal resampling and test set performance?
# Load data
data("ChemicalManufacturingProcess")
str("ChemicalManufacturingProcess")
## chr "ChemicalManufacturingProcess"
# Separate predictors and response
processPredictors <- ChemicalManufacturingProcess[, -1] # all columns except Yield
yield <- ChemicalManufacturingProcess$Yield
# Check
dim(processPredictors)
## [1] 176 57
sum(is.na(processPredictors))
## [1] 106
# Impute missing values and standardize predictors
preProc <- preProcess(processPredictors,
method = c("knnImpute", "center", "scale"))
# Apply the transformation
imputedPredictors <- predict(preProc, processPredictors)
# Verify that no missing values remain
sum(is.na(imputedPredictors))
## [1] 0
set.seed(2000)
trainIndex <- createDataPartition(yield, p = 0.8, list = FALSE)
trainX <- imputedPredictors[trainIndex, ]
trainY <- yield[trainIndex]
testX <- imputedPredictors[-trainIndex, ]
testY <- yield[-trainIndex]
# Define cross-validation
ctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 5)
# MARS
library(earth)
set.seed(2000)
marsFit <- train(trainX, trainY, method = "earth", trControl = ctrl)
# KNN
set.seed(2000)
knnFit <- train(trainX, trainY, method = "knn",
preProcess = c("center", "scale"),
trControl = ctrl)
## Warning in preProcess.default(thresh = 0.95, k = 5, freqCut = 19, uniqueCut =
## 10, : These variables have zero variances: BiologicalMaterial07
## Warning in preProcess.default(thresh = 0.95, k = 5, freqCut = 19, uniqueCut =
## 10, : These variables have zero variances: BiologicalMaterial07
## Warning in preProcess.default(thresh = 0.95, k = 5, freqCut = 19, uniqueCut =
## 10, : These variables have zero variances: BiologicalMaterial07
# Random Forest
library(randomForest)
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
## The following object is masked from 'package:dplyr':
##
## combine
## The following object is masked from 'package:ggplot2':
##
## margin
set.seed(2000)
rfFit <- train(trainX, trainY, method = "rf", trControl = ctrl)
# Compare resampling results
resamps <- resamples(list(MARS = marsFit,
KNN = knnFit,
RF = rfFit))
summary(resamps)
##
## Call:
## summary.resamples(object = resamps)
##
## Models: MARS, KNN, RF
## Number of resamples: 50
##
## MAE
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## MARS 0.5986831 0.8171785 0.9995295 0.9967852 1.119407 1.902612 0
## KNN 0.7888889 0.9739286 1.1091852 1.1328587 1.302171 1.596889 0
## RF 0.5668599 0.8025428 0.9285218 0.9142093 1.053140 1.305803 0
##
## RMSE
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## MARS 0.7432571 1.012591 1.263066 1.242825 1.368191 2.176877 0
## KNN 0.9666759 1.182341 1.382650 1.388157 1.609641 1.864860 0
## RF 0.6725201 1.050317 1.185986 1.179044 1.366901 1.623708 0
##
## Rsquared
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## MARS 0.2240504 0.4889713 0.6154467 0.6085037 0.7405383 0.9062231 0
## KNN 0.1550206 0.4050182 0.5012166 0.4970515 0.5828894 0.8259773 0
## RF 0.3481359 0.5460054 0.6578766 0.6478692 0.7367284 0.9203432 0
bwplot(resamps)
marsPred <- predict(marsFit, newdata = testX)
knnPred <- predict(knnFit, newdata = testX)
rfPred <- predict(rfFit, newdata = testX)
postResample(marsPred, testY)
## RMSE Rsquared MAE
## 1.0414824 0.6120788 0.8095469
postResample(knnPred, testY)
## RMSE Rsquared MAE
## 0.9715412 0.6744127 0.8379514
postResample(rfPred, testY)
## RMSE Rsquared MAE
## 0.8881514 0.7309577 0.6898286
I trained MARS, KNN, and Random Forest models using repeated cross-validation to compare nonlinear regression performance.
Among the nonlinear regression models (MARS, KNN, and Random Forest), the Random Forest model came out on top. It had the lowest RMSE and highest R-squared in both cross-validation and test results, showing it made the most accurate and reliable yield predictions for the chemical manufacturing process.
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?
rfImp <- varImp(rfFit, scale = TRUE)
rfImp
## rf variable importance
##
## only 20 most important variables shown (out of 57)
##
## Overall
## ManufacturingProcess32 100.000
## ManufacturingProcess13 16.397
## ManufacturingProcess17 16.184
## BiologicalMaterial03 15.026
## BiologicalMaterial12 14.445
## ManufacturingProcess09 11.822
## BiologicalMaterial06 11.004
## ManufacturingProcess31 9.745
## ManufacturingProcess36 9.564
## BiologicalMaterial11 7.660
## ManufacturingProcess06 6.947
## BiologicalMaterial05 6.485
## ManufacturingProcess28 5.434
## BiologicalMaterial08 5.325
## BiologicalMaterial02 5.162
## ManufacturingProcess18 4.884
## BiologicalMaterial09 4.869
## ManufacturingProcess11 4.615
## BiologicalMaterial04 4.141
## ManufacturingProcess21 3.578
# Visualize top 10
plot(rfImp, top = 10)
The Random Forest model ranked ManufacturingProcess32, Process13, and Process17 as the top predictors, with process variables clearly dominating overall. A few biological factors (like BiologicalMaterial02 and 06) also contributed but had smaller effects. Compared to the previous model, the same key process variables remained important, showing consistent influence on yield, but Random Forest emphasized their nonlinear impact more strongly.
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?
# Add yield back to preprocessed training data
data_plot <- data.frame(Yield = trainY, trainX)
# Updated top predictors based on the latest importance plot
top_predictors <- c(
"ManufacturingProcess32", "ManufacturingProcess13",
"ManufacturingProcess17", "BiologicalMaterial03",
"BiologicalMaterial12", "ManufacturingProcess09",
"BiologicalMaterial06", "ManufacturingProcess31",
"ManufacturingProcess36", "BiologicalMaterial11"
)
# Plot yield vs each top predictor
for (var in top_predictors) {
print(
ggplot(data_plot, aes_string(x = var, y = "Yield")) +
geom_point(alpha = 0.6, color = "steelblue") +
geom_smooth(method = "loess", color = "darkred", se = FALSE, linewidth = 1) +
labs(title = paste("Yield vs", var),
x = var,
y = "Product Yield") +
theme_minimal() +
theme(plot.title = element_text(face = "bold", size = 12))
)
}
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
The plots show nonlinear patterns between the top predictors and product yield. For example, ManufacturingProcess32 shows a strong positive trend with yield before leveling off, suggesting that increasing this process factor boosts performance up to a point. On the other hand, Process13 and Process17 display negative/curved relationships, where yield declines as their values increase.
The biological variables (like BiologicalMaterial03, 06, and 12) have gentler slopes and smaller fluctuations, indicating weaker but still noticeable influence. Overall, the process variables dominate the yield behavior, showing stronger and more complex nonlinear effects compared to the biological ones.