tuneRF与随机森林的caret调优的比较

问题描述 投票:0回答:1

我试图使用随机森林包中包含的tuneRF工具来调整一个随机森林模型,我也在使用caret包来调整我的模型。问题是,我在调优得到mtry,而且每种方法得到的结果都不一样。问题是我怎么知道哪种方法是最好的,基于什么?我不清楚我是否应该期待相似或不同的结果。

tuneRF:用这种方法我得到最好的mtry是3

t <- tuneRF(train[,-12], train[,12],
        stepFactor = 0.5,
        plot = TRUE,
        ntreeTry = 100,
        trace = TRUE,
        improve = 0.05)

caret: 用这种方法,我总是得到最好的mtry是所有变量,在这种情况下6

control <- trainControl(method="cv", number=5)
tunegrid <- expand.grid(.mtry=c(2:6))
set.seed(2)
custom <- train(CRTOT_03~., data=train, method="rf", metric="rmse", 
                tuneGrid=tunegrid, ntree = 100, trControl=control)
r random-forest r-caret hyperparameters
1个回答
0
投票

有几个不同的地方,对于每个mtry参数,tuneRF在整个数据集上拟合一个模型,你会得到每个拟合的OOB误差,然后tuneRF取最低的OOB误差。对于mtry的每个值,你有一个分数(或RMSE值),这将随着不同的运行而改变。

在caret中,你实际上是在做交叉验证,所以在模型中根本没有使用折叠的测试数据。虽然原则上应该和OOB类似,但你应该意识到其中的差异。

对误差有比较好的评估可能是运行tuneRF几轮,我们可以用cv在caret。

library(randomForest)
library(mlbench)
data(BostonHousing)
train <- BostonHousing

tuneRF_res = lapply(1:10,function(i){

tr = tuneRF(train[,-14], train[,14],mtryStart=2,step=0.9,ntreeTry = 100,trace = TRUE,improve=1e-5)
tr = data.frame(tr)
tr$RMSE = sqrt(tr[,2])
tr
})

tuneRF_res = do.call(rbind,tuneRF_res)

control <- trainControl(method="cv", number=10,returnResamp="all")
tunegrid <- expand.grid(.mtry=c(2:7))
caret_res <- train(medv ~., data=train, method="rf", metric="RMSE", 
                tuneGrid=tunegrid, ntree = 100, trControl=control)

library(ggplot2)
df = rbind(
data.frame(tuneRF_res[,c("mtry","RMSE")],test="tuneRF"),
data.frame(caret_res$resample[,c("mtry","RMSE")],test="caret")
)
df = df[df$mtry!=1,]

ggplot(df,aes(x=mtry,y=RMSE,col=test))+
stat_summary(fun.data=mean_se,geom="errorbar",width=0.2) +
stat_summary(fun=mean,geom="line") + facet_wrap(~test)

enter image description here

你可以看到趋势是差不多的. 我的建议是用tuneRF快速检查要训练的mtrys范围,然后用caret,交叉验证来正确评估这个。

© www.soinside.com 2019 - 2024. All rights reserved.