自动调整随机森林

  • 本文关键字:森林 随机 调整 r
  • 更新时间 :
  • 英文 :


我想自动调整随机森林模型,因为我的变量会实时变化。我正在使用iris数据集。

我的代码是

jk = iris
library(randomForest)
library(caret)
fgl.res <- tuneRF(lm[,-5], lm[,5], stepFactor=1.5)
o/p:
mtry = 2  OOB error = 5.33% 
Searching left ...
Searching right ...
mtry = 3    OOB error = 4% 
0.25 0.05 
mtry = 4    OOB error = 5.33% 
-0.3333333 0.05 

上面我希望fgl.res代码中它会自动选择Species列索引,即数据集中的 5 iris并插入fgl.res代码中。

然后使用第一行fgl.res输出(o/p)并取值"mtry = 2 OOB error = 5.33% "并在随机森林代码中使用它,即将值分配给mtryoob.error,如下所示:

mod2<-randomForest(Species~., data=lm, ntree=50, mtry=2, oob.error=0.0533)

我已经尝试了很多方法,但没有解决如何从输出自动将值插入代码fgl.res

我不知道

我是否正确理解了你的问题,但你可能会使用这种方法。
当您使用tuneRF时,您必须选择具有最低OOB误差的mtry。我使用invisible(capture.output(...))功能在进入tuneRF功能后隐藏控制台中显示的任何输出。

例:

# load library
library(randomForest)
library(caret)
# data
data_iris = iris
# repeat the analysis
set.seed(4543)
# tuneRF 
invisible(capture.output(fgl.res <- tuneRF(x = data_iris[,-5], y= 
data_iris[,5], stepFactor=1.5)))
# choose the best mtry based on the lowest OOB error
best_mtry <- fgl.res[fgl.res[, 2] == min(fgl.res[, 2]), 1]
# choose the lowest OOB error
best_oob  <- fgl.res[fgl.res[, 2] == min(fgl.res[, 2]), 2]
# caluclate RF
mod2<-randomForest(Species~., data=data_iris, ntree=50, mtry=best_mtry,
oob.error=best_oob)

当您只想提取第一行 fgl.res 输出并获取 mtry 和 OOB 错误的值时,您必须使用:

# choose the best mtry based on the lowest OOB error
best_mtry <- fgl.res[1, 1]
# choose the lowest OOB error
best_oob  <- fgl.res[1, 2]

我知道您在 10 个月前发布了这个问题,但也许这种方法对其他用户有用。

最新更新