是否有可能使滚动randomForest可重复?

时间:2017-09-14 07:34:05

标签: r for-loop random-forest

我有以下randomForest循环:

require(randomForest)
require(xts)
require(quantmod)
getSymbols("MSFT", from = '2017-01-01', to = '2017-09-13', src = "yahoo")
rets <- diff(log(Ad(MSFT))); rets[is.na(rets)]=0
rets1 <- ifelse(rets>0,"up","dn")
Lag1 <- lag(rets,1);Lag1[is.na(Lag1)]=0;Lag1 <- ifelse(Lag1>0,"up","dn")
Lag2 <- lag(rets,2);Lag2[is.na(Lag2)]=0;Lag2 <- ifelse(Lag2>0,"up","dn")
Lag3 <- lag(rets,3);Lag3[is.na(Lag3)]=0;Lag3 <- ifelse(Lag3>0,"up","dn")
preds <- rets* 0
win=20

for(i in win:(NROW(rets)-1)){
    RFDataf <- data.frame(factor(Lag1),factor(Lag2),factor(Lag3))
    fit <- try(randomForest(RFDataf[(i-win+1):i,], factor(as.character(rets1[(i-win+1):i])), ntree=1000, mtry=round(sqrt(NCOL(RFDataf)),0)))
    if(class(fit) != "try-error"){
        fit0 <- fit
        preds[(i+1)] <- predict(fit, RFDataf[(i+1),])
    }else{
        if(exists("fit0")){
            preds[(i+1)] <- predict(fit0, RFDataf[(i+1),])}else{next}
        }
    }
}

我仔细阅读了这些内容:

https://stats.stackexchange.com/questions/120446/different-results-from-several-passes-of-random-forest-on-same-dataset

https://github.com/mlr-org/mlr/issues/938

据我所知,如果在R函数中使用其他语言,set.seed()将无效。

我还有一个循环问题。

如果我使用的函数没有外语但循环中的r,我怎样才能保留再现性?

有没有办法让set.seed()在循环中工作?任何替代解决方案?

0 个答案:

没有答案