我正在使用caret
包来调优随机森林使用ranger
的(RF)模型。因为在ranger
包中我不能调整树的数量,所以我使用caret
包。找到最佳树数量的度量是R平方。我测试的树的范围是从500到3000,步长为500(500,1000,1500,...,3000)。
问题是,R平方对于每个树数都是相同的(见下面的附图):
我不认为这是正确的,所以我认为我的代码有问题,为什么我得到的是相同的R平方?
代码如下:
library(caret)
library(ranger)
# Load the data
block.data <- read.csv("path/block.data.csv")
eq1 = ntl ~ .
# Define the cross-validation method for hyperparameter tuning
control <- trainControl(method = "cv", number = 10, savePredictions = FALSE,
search = 'grid', allowParallel = TRUE)
# default model
rf_default = train(eq1,
data = block.data,
method = "ranger",
metric = "Rsquared",
trControl = control)
print(rf_default)
# Define the grid of hyperparameters to be tuned
tuneGrid <- expand.grid(mtry = c(2, 3, 4, 5, 6, 7), # number of predictor variables to sample at each split
splitrule = c("variance", "extratrees"), # splitting rule
min.node.size = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) # minimum size of terminal nodes
# Train the model with hyperparameter tuning using caret
set.seed(234)
rf_model <- train(eq1, # formula for the response and predictors
data = block.data,
method = "ranger",
trControl = control,
tuneGrid = tuneGrid)
rf_model$bestTune
tuneGrid <- expand.grid(mtry = rf_model$bestTune$mtry,
splitrule = rf_model$bestTune$splitrule,
min.node.size = rf_model$bestTune$min.node.size)
store_maxtrees <- list()
for (ntree in c(500, 1000, 1500, 2000, 2500, 3000)) {
set.seed(345)
rf_maxtrees <- train(eq1,
data = block.data,
method = "ranger",
metric = "Rsquared",
tuneGrid = tuneGrid,
trControl = control,
ntree = ntree)
key <- toString(ntree)
store_maxtrees[[key]] <- rf_maxtrees
}
results_tree <- resamples(store_maxtrees)
summary(results_tree)
1条答案
按热度按时间2w2cym1i1#
在
for
循环中,我必须将ntree
更改为num.tree
,如下所示: