packages <- c(
  "AppliedPredictiveModeling",
  "caret",
  "mlbench",
  "earth",
  "kernlab",
  "kknn",
  "RANN",
  "ggplot2",
  "dplyr"
)

install.packages(
  setdiff(packages, rownames(installed.packages()))
)

library(AppliedPredictiveModeling)
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
library(mlbench)
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(kknn)
## 
## Attaching package: 'kknn'
## The following object is masked from 'package:caret':
## 
##     contr.dummy
library(ggplot2)
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

Exercise 7.2

A

set.seed(200)

trainingData <- mlbench.friedman1(200, sd = 1)
trainingData$x <- as.data.frame(trainingData$x)

testData <- mlbench.friedman1(5000, sd = 1)
testData$x <- as.data.frame(testData$x)

featurePlot(
  trainingData$x,
  trainingData$y,
  plot = "scatter"
)

The scatterplots show that the first five predictors have relationships with the outcome, while the last five appear to have little or no relationship. This is expected because the Friedman dataset was created using only the first five predictors.

B

control <- trainControl(
  method = "repeatedcv",
  number = 5,
  repeats = 3
)

set.seed(123)

friedman_mars <- train(
  x = trainingData$x,
  y = trainingData$y,
  method = "earth",
  tuneLength = 5,
  trControl = control
)

set.seed(123)

friedman_knn <- train(
  x = trainingData$x,
  y = trainingData$y,
  method = "knn",
  preProcess = c("center", "scale"),
  tuneLength = 10,
  trControl = control
)

set.seed(123)

friedman_svm <- train(
  x = trainingData$x,
  y = trainingData$y,
  method = "svmRadial",
  preProcess = c("center", "scale"),
  tuneLength = 5,
  trControl = control
)
friedman_models <- resamples(list(
  MARS = friedman_mars,
  KNN = friedman_knn,
  SVM = friedman_svm
))

summary(friedman_models)$statistics$RMSE
##          Min.  1st Qu.   Median     Mean  3rd Qu.     Max. NA's
## MARS 1.377469 1.524672 1.644721 1.661165 1.799173 2.107808    0
## KNN  2.718261 2.933165 3.101548 3.051393 3.133863 3.273898    0
## SVM  1.722964 1.851022 1.996630 1.974683 2.094757 2.281351    0
friedman_results <- data.frame(
  Model = c("MARS", "KNN", "SVM"),
  RMSE = c(
    postResample(predict(friedman_mars, testData$x), testData$y)["RMSE"],
    postResample(predict(friedman_knn, testData$x), testData$y)["RMSE"],
    postResample(predict(friedman_svm, testData$x), testData$y)["RMSE"]
  )
)

friedman_results |>
  arrange(RMSE)

I compared MARS, KNN, and SVM using repeated cross-validation. MARS performed best, with a test RMSE of 1.8136, followed by SVM at 2.0639 and KNN at 3.1223. Since MARS had the lowest RMSE, it provided the most accurate predictions for this dataset.

C

friedman_importance <- varImp(
  friedman_mars,
  scale = FALSE
)

friedman_importance
## earth variable importance
## 
##    Overall
## V1  100.00
## V4   84.22
## V2   67.22
## V5   45.44
## V3   34.63
## V6   11.90
plot(friedman_importance, top = 10)

The MARS model identified V1 as the most important predictor, followed by V4, V2, V5, and V3. These are the five variables used to generate the outcome in the Friedman dataset. V6 had very little importance, while the remaining variables were not selected. This shows that MARS was able to identify the important predictors.

7.5

A

data(ChemicalManufacturingProcess)

cmp_y <- ChemicalManufacturingProcess$Yield
cmp_x <- ChemicalManufacturingProcess |>
  select(-Yield)

set.seed(123)

cmp_index <- createDataPartition(
  cmp_y,
  p = 0.80,
  list = FALSE
)

cmp_train_x <- cmp_x[cmp_index, ]
cmp_test_x <- cmp_x[-cmp_index, ]

cmp_train_y <- cmp_y[cmp_index]
cmp_test_y <- cmp_y[-cmp_index]

nzv <- nearZeroVar(cmp_train_x)

if (length(nzv) > 0) {
  cmp_train_x <- cmp_train_x[, -nzv, drop = FALSE]
  cmp_test_x <- cmp_test_x[, -nzv, drop = FALSE]
}
set.seed(123)

cmp_mars <- train(
  x = cmp_train_x,
  y = cmp_train_y,
  method = "earth",
  preProcess = c("knnImpute", "center", "scale"),
  tuneLength = 5,
  trControl = control
)

set.seed(123)

cmp_knn <- train(
  x = cmp_train_x,
  y = cmp_train_y,
  method = "knn",
  preProcess = c("knnImpute", "center", "scale"),
  tuneLength = 10,
  trControl = control
)

set.seed(123)

cmp_svm <- train(
  x = cmp_train_x,
  y = cmp_train_y,
  method = "svmRadial",
  preProcess = c("knnImpute", "center", "scale"),
  tuneLength = 5,
  trControl = control
)
cmp_models <- resamples(list(
  MARS = cmp_mars,
  KNN = cmp_knn,
  SVM = cmp_svm
))

summary(cmp_models)$statistics$RMSE
##           Min.  1st Qu.   Median     Mean  3rd Qu.     Max. NA's
## MARS 0.8414598 1.184410 1.363186 1.335897 1.593057 1.740216    0
## KNN  0.9364518 1.194098 1.298750 1.307219 1.474446 1.635665    0
## SVM  0.9237716 1.031164 1.131665 1.208896 1.306997 1.724421    0
cmp_results <- data.frame(
  Model = c("MARS", "KNN", "SVM"),
  RMSE = c(
    postResample(predict(cmp_mars, cmp_test_x), cmp_test_y)["RMSE"],
    postResample(predict(cmp_knn, cmp_test_x), cmp_test_y)["RMSE"],
    postResample(predict(cmp_svm, cmp_test_x), cmp_test_y)["RMSE"]
  )
)

cmp_results |>
  arrange(RMSE)

I compared MARS, SVM, and KNN using cross-validation and a test dataset. SVM had the lowest average cross-validation RMSE, but MARS performed best on the test data with an RMSE of 1.1610. SVM followed with 1.1980, and KNN had the highest test RMSE at 1.4388.

B

cmp_model_list <- list(
  MARS = cmp_mars,
  KNN = cmp_knn,
  SVM = cmp_svm
)

best_name <- cmp_results$Model[
  which.min(cmp_results$RMSE)
]

best_model <- cmp_model_list[[best_name]]

best_name
## [1] "MARS"
best_importance <- varImp(
  best_model,
  scale = FALSE
)

nonlinear_top10 <- best_importance$importance |>
  arrange(desc(Overall)) |>
  head(10)

nonlinear_top10
plot(best_importance, top = 5)

nonlinear_names <- rownames(best_importance$importance)[
  order(best_importance$importance$Overall, decreasing = TRUE)
]

nonlinear_names <- head(nonlinear_names, 10)

nonlinear_names
## [1] "ManufacturingProcess32" "ManufacturingProcess17" "ManufacturingProcess13"
## [4] "ManufacturingProcess02" "ManufacturingProcess39"
set.seed(123)

cmp_pls <- train(
  x = cmp_train_x,
  y = cmp_train_y,
  method = "pls",
  preProcess = c("knnImpute", "center", "scale"),
  tuneLength = 10,
  trControl = control
)

pls_importance <- varImp(
  cmp_pls,
  scale = FALSE
)$importance
## 
## Attaching package: 'pls'
## The following object is masked from 'package:caret':
## 
##     R2
## The following object is masked from 'package:stats':
## 
##     loadings
linear_names <- rownames(pls_importance)[
  order(
    pls_importance$Overall,
    decreasing = TRUE
  )[1:10]
]

data.frame(
  Nonlinear = c(nonlinear_names, rep(NA_character_, 5)),
  Linear_PLS = linear_names
)
intersect(nonlinear_names, linear_names)
## [1] "ManufacturingProcess32" "ManufacturingProcess17" "ManufacturingProcess13"

The MARS model identified ManufacturingProcess32 as the most important predictor, followed by ManufacturingProcess17, ManufacturingProcess13, ManufacturingProcess02, and ManufacturingProcess39. These variables had the greatest importance in predicting manufacturing yield.

C

unique_predictors <- setdiff(
  nonlinear_names,
  linear_names
)

unique_predictors
## [1] "ManufacturingProcess02" "ManufacturingProcess39"
top_vars <- c(
  "ManufacturingProcess32",
  "ManufacturingProcess17",
  "ManufacturingProcess13",
  "ManufacturingProcess02",
  "ManufacturingProcess39"
)

for (v in top_vars) {
  plot_data <- data.frame(
    Predictor = cmp_x[[v]],
    Yield = cmp_y
  )

  print(
    ggplot(plot_data, aes(x = Predictor, y = Yield)) +
      geom_point() +
      geom_smooth(method = "loess", se = FALSE) +
      labs(
        title = paste("Yield vs", v),
        x = v,
        y = "Manufacturing Yield"
      )
  )
}
## `geom_smooth()` using formula = 'y ~ x'

## `geom_smooth()` using formula = 'y ~ x'

## `geom_smooth()` using formula = 'y ~ x'

## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 3 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 3 rows containing missing values or values outside the scale range
## (`geom_point()`).

## `geom_smooth()` using formula = 'y ~ x'

ManufacturingProcess02 and ManufacturingProcess39 were important in the nonlinear model but were not among the top ten predictors in the linear PLS model. Their plots show curved relationships with yield, suggesting that the effects of these variables may not be linear. These patterns could help identify manufacturing conditions associated with better yield, although further testing would be needed.