install.packages(c(
"AppliedPredictiveModeling",
"caret",
"mlbench",
"randomForest",
"rpart",
"rpart.plot",
"gbm",
"Cubist"
))
## Installing packages into '/cloud/lib/x86_64-pc-linux-gnu-library/4.6'
## (as 'lib' is unspecified)
library(AppliedPredictiveModeling)
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
library(mlbench)
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:ggplot2':
##
## margin
library(rpart)
library(rpart.plot)
library(gbm)
## Loaded gbm 2.3.1
## This version of gbm is no longer under development. Consider transitioning to gbm3, https://github.com/gbm-developers/gbm3
library(Cubist)
set.seed(200)
simulated <- mlbench.friedman1(200, sd = 1)
friedman <- as.data.frame(simulated$x)
friedman$y <- simulated$y
set.seed(123)
rf_model <- randomForest(
y ~ .,
data = friedman,
ntree = 500,
importance = TRUE
)
varImpPlot(rf_model)
I created 200 simulated observations and fitted a random forest model. The first five predictors contain the useful information, while the remaining five are noise. The importance plot helps show whether the model can identify the useful predictors.
rf_importance <- importance(
rf_model,
type = 1
)
sort(rf_importance[, 1], decreasing = TRUE)
## V1 V4 V2 V5 V3 V6 V7 V10
## 40.058728 35.282980 34.328712 16.807669 7.554843 2.148327 0.508318 -1.819707
## V8 V9
## -1.899160 -2.402042
The random forest should give higher importance to the first five predictors because they are related to the outcome. The remaining predictors should generally have lower importance because they do not contribute to the simulated response.
set.seed(123)
friedman$duplicate1 <- friedman$V1 + rnorm(200) * 0.1
rf_correlated <- randomForest(
y ~ .,
data = friedman,
ntree = 1000,
importance = TRUE
)
varImpPlot(rf_correlated)
I added a new predictor that is strongly correlated with V1. This can change the importance scores because the two variables contain similar information. The model may divide their importance instead of giving all the importance to V1.
set.seed(123)
boost_model <- train(
y ~ .,
data = friedman,
method = "gbm",
trControl = trainControl(method = "cv", number = 5),
tuneLength = 3,
verbose = FALSE
)
set.seed(123)
cubist_model <- Cubist::cubist(
x = friedman[, setdiff(names(friedman), "y")],
y = friedman$y,
committees = 10
)
varImp(boost_model)
## gbm variable importance
##
## Overall
## V4 100.0000
## V2 75.8290
## V1 68.9071
## V5 40.9773
## duplicate1 27.6646
## V3 25.3020
## V6 3.1071
## V8 2.6062
## V7 1.4340
## V9 0.5791
## V10 0.0000
caret::varImp(cubist_model)
I compared variable importance using boosted trees and Cubist. In the Cubist model, V2 (54.0), V1 (53.5), and V4 (48.5) were the most important predictors. The correlated variable duplicate1 also received an importance score of 25.0. This shows that the models can assign different importance scores to predictors.
set.seed(123)
n <- 500
tree_data <- data.frame(
X1 = rnorm(n),
X2 = factor(sample(letters[1:3], n, replace = TRUE)),
X3 = factor(sample(letters[1:10], n, replace = TRUE)),
y = rnorm(n)
)
tree_model <- rpart(
y ~ .,
data = tree_data,
control = rpart.control(cp = 0.001)
)
tree_model$variable.importance
## X1 X3 X2
## 79.18895 41.51839 22.35454
rpart.plot(tree_model)
I created three random predictors and fitted a regression tree. The tree produced many splits even though the predictors were not related to the outcome. This shows that regression trees can find patterns in random data and may overfit when they are allowed to grow too large.
The importance plots differ because the models use different tuning settings. A larger learning rate and bagging fraction can cause the model to focus more on certain predictors, while smaller values may spread importance across more variables.
I would expect the model with the smaller learning rate to perform better on new data because it makes smaller adjustments and may reduce overfitting. However, cross-validation would be needed to confirm which model performs better.
Increasing interaction depth allows the model to capture more complex relationships between predictors. This can improve predictions, but it may also increase overfitting.
install.packages("RANN")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.6'
## (as 'lib' is unspecified)
library(RANN)
data(ChemicalManufacturingProcess)
cmp <- ChemicalManufacturingProcess
set.seed(123)
idx <- createDataPartition(
cmp$Yield,
p = 0.80,
list = FALSE
)
train_data <- cmp[idx, ]
test_data <- cmp[-idx, ]
x_train <- subset(train_data, select = -Yield)
x_test <- subset(test_data, select = -Yield)
pre <- preProcess(
x_train,
method = c("knnImpute", "center", "scale")
)
x_train <- predict(pre, x_train)
x_test <- predict(pre, x_test)
train_data <- data.frame(Yield = train_data$Yield, x_train)
test_data <- data.frame(Yield = test_data$Yield, x_test)
control <- trainControl(
method = "repeatedcv",
number = 10,
repeats = 5
)
remove <- nearZeroVar(train_data)
train_data <- train_data[, -remove]
test_data <- test_data[, names(train_data)]
set.seed(123)
tree_fit <- train(Yield ~ ., data = train_data,
method = "rpart", trControl = control,
tuneLength = 5)
## Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,
## : There were missing values in resampled performance measures.
rf_fit <- train(Yield ~ ., data = train_data,
method = "rf", trControl = control,
tuneLength = 3)
boost_fit <- train(Yield ~ ., data = train_data,
method = "gbm", trControl = control,
tuneLength = 3, verbose = FALSE)
cubist_fit <- Cubist::cubist(
x = subset(train_data, select = -Yield),
y = train_data$Yield,
committees = 10
)
models <- list(
Tree = tree_fit,
RF = rf_fit,
Boosting = boost_fit
)
cv_results <- data.frame(
Model = names(models),
CV_RMSE = sapply(models, function(x) min(x$results$RMSE, na.rm = TRUE))
)
test_results <- data.frame(
Model = c(names(models), "Cubist"),
Test_RMSE = c(
sapply(models, function(x)
RMSE(predict(x, test_data), test_data$Yield)),
RMSE(predict(cubist_fit, test_data), test_data$Yield)
)
)
cv_results
test_results
I compared four models for predicting manufacturing yield. Random Forest had the lowest cross-validation RMSE (1.1115) among the three models evaluated using repeated cross-validation. Cubist had the lowest test RMSE (1.0116), followed by Boosting (1.1220), Random Forest (1.2645), and the Regression Tree (1.6752). Based on the test results, Cubist performed best. However, Cubist was fitted separately and was not evaluated using the same cross-validation procedure as the other models.
cubist_importance <- caret::varImp(cubist_fit)
cubist_importance
par(mar = c(5, 12, 4, 2))
top10 <- head(
cubist_importance[order(-cubist_importance$Overall), , drop = FALSE],
10
)
barplot(
rev(top10$Overall),
names.arg = rev(rownames(top10)),
horiz = TRUE,
las = 1,
main = "Top 10 Cubist Predictors",
xlab = "Importance"
)
ManufacturingProcess32 was the most important predictor, followed by ManufacturingProcess09 and ManufacturingProcess17. These variables had the greatest importance in the Cubist model for predicting manufacturing yield.
rpart.plot(tree_fit$finalModel)
boxplot(
train_data$Yield ~ tree_fit$finalModel$where,
xlab = "Terminal Node",
ylab = "Manufacturing Yield",
main = "Yield by Terminal Node"
)
The regression tree first splits the data using ManufacturingProcess32. The boxplot shows differences in manufacturing yield across the five terminal nodes. Node 9 has the highest median yield, while node 3 has the lowest.