6

我有一个非常大的数据框,包含 790,000 行和 140 个预测变量。其中一些是相互密切相关的,并且在不同的尺度上。有了这个randomForest包,我可以只使用一小部分数据样本在每个核心上种植一个森林,使用foreach它们并将它们与combine()函数合并以获得一棵大树,如下所示:

rf.STR = foreach(ntree=rep(125, 8), .combine=combine, .multicombine=TRUE, .packages='randomForest') %dopar% {
  sample.idx = sample.int( nrow(dat), size=sample.size, replace=TRUE)
  randomForest(x=dat[sample.idx,-1, with=FALSE], 
               y=dat[sample.idx, retention], ntree=ntree)
  }

不同尺度的相关变量让我想使用party包中的条件随机森林,但是没有combine()用于 cforests 的方法,所以我不确定如何组合几个 cforest 对象来获得一个重要性图或一个预测。

有没有办法在较小的数据子集上训练一个大的 cforest,或者制作几个小的 cforest 并将它们组合成一个更大的条件森林模型?

4

1 回答 1

0

制作几个小的 cforests 并将它们组合成一个更大的条件森林模型。

library(snowfall)
library(party)
cforestmt<-function(formula, data = list(), subset = NULL, weights = NULL, controls = cforest_unbiased(), xtrafo = ptrafo, ytrafo = ptrafo, scores = NULL, threads=8) {

    if(controls@ntree<threads) {    # if there are less trees than threads single thread
        return(cforest(formula, data = data, subset=subset, weights=weights, controls=controls, xtrafo=xtrafo, ytrafo=ytrafo, scores=scores))
    }

    # round off threads
    fsize=controls@ntree/threads
    if(fsize-round(fsize)!=0) {
            fsize=ceiling(fsize)
            message("Rounding forest size to ",fsize*threads)
    }
    controls@ntree=as.integer(fsize)

    # run forests in parallel
    sfInit(parallel=T, cpus=threads, type="SOCK")
    sfClusterEval(library(party))
    sfExport('formula','data','subset','weights','controls','xtrafo','ytrafo','scores')
    fr<-sfClusterEval(cforest(formula, data = data, subset=subset, weights=weights, controls=controls, xtrafo=xtrafo, ytrafo=ytrafo, scores=scores))
    sfStop()

    # combine/append forest
    fr[[1]]@ensemble<-unlist(lapply(fr,function(y) {y@ensemble}),recursive=F)
    fr[[1]]@where<-unlist(lapply(fr,function(y) {y@where}),recursive=F)
    fr[[1]]@weights<-unlist(lapply(fr,function(y) {y@weights}),recursive=F)

    #first forest has result
    return(fr[[1]])
}
于 2016-11-15T09:48:30.470 回答