R语言 微调随机森林模型的超参数:树数

zlhcx6iw  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(267)

我正在使用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)
2w2cym1i

2w2cym1i1#

for循环中,我必须将ntree更改为num.tree,如下所示:

for (num.tree in c(500, 1000, 1500, 2000, 2500, 3000)) {
set.seed(345)
rf_maxtrees <- caret::train(eq1,
data = block.data,
method = "ranger",
metric = "Rsquared",
tuneGrid = tuneGrid,
trControl = control,
num.tree = num.tree)
key <- toString(num.tree)
store_maxtrees[[key]] <- rf_maxtrees
}

相关问题