R:使用带有插入符和 tuneGrid 参数的护林员

R: using ranger with caret, tuneGrid argument

我正在使用 caret package to analyse Random Forest models built using ranger。我不知道如何使用 tuneGrid 参数调用训练函数来调整模型参数。

我想我调用 tuneGrid 参数是错误的,但无法弄清楚为什么它是错误的。任何帮助将不胜感激。

data(iris)

library(ranger)
model_ranger <- ranger(Species ~ ., data = iris, num.trees = 500, mtry = 4,
                       importance = 'impurity')


library(caret)

# my tuneGrid object:
tgrid <- expand.grid(
  num.trees = c(200, 500, 1000),
  mtry = 2:4
)

model_caret <- train(Species  ~ ., data = iris,
                     method = "ranger",
                     trControl = trainControl(method="cv", number = 5, verboseIter = T, classProbs = T),
                     tuneGrid = tgrid,
                     importance = 'impurity'
)

以下是插入符号中 ranger 的语法:

library(caret)

在调整参数之前添加 .

tgrid <- expand.grid(
  .mtry = 2:4,
  .splitrule = "gini",
  .min.node.size = c(10, 20)
)

插入符只支持这三个,不支持树的数量。在训练中,您可以指定 num.trees 和重要性:

model_caret <- train(Species  ~ ., data = iris,
                     method = "ranger",
                     trControl = trainControl(method="cv", number = 5, verboseIter = T, classProbs = T),
                     tuneGrid = tgrid,
                     num.trees = 100,
                     importance = "permutation")

获得变量重要性:

varImp(model_caret)

#output
             Overall
Petal.Length 100.0000
Petal.Width   84.4298
Sepal.Length   0.9855
Sepal.Width    0.0000

要检查这是否可行,请将树数设置为 1000+ - 拟合速度会慢得多。更改后 importance = "impurity":

#output:

             Overall
Petal.Length  100.00
Petal.Width    81.67
Sepal.Length   16.19
Sepal.Width     0.00

如果它不起作用,我建议安装来自 CRAN 的最新 ranger 和来自 git hub:

的插入符号
devtools::install_github('topepo/caret/pkg/caret')

要训练树的数量,您可以使用 lapply 和由 createMultiFoldscreateFolds 创建的固定折叠。

编辑:虽然上面的示例适用于插入符包版本 6.0-84,但使用不带点的超参数名称也适用。

tgrid <- expand.grid(
  mtry = 2:4,
  splitrule = "gini",
  min.node.size = c(10, 20)
)