制作几个小的 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]])
}