2

我以为我找到了一种使用以下代码制作可重复foreach循环的方法doSNOW

library(foreach)
library(doSNOW)
library(parallel)
ncores <- 2
cl <- makeCluster(ncores)
registerDoSNOW(cl)

foreach(i=1:ncores) %dopar% {
  set.seed(i)
  rnorm(1)
}

stopCluster(cl)

因为我在 foreach 循环中使用了种子,所以我总是得到相同的结果(独立于计算机/操作系统),即

[[1]]
[1] -0.6264538

[[2]]
[1] -0.8969145

但是如果我使用 randomForest 函数,我会根据操作系统得到不同的结果:

library(foreach)
library(doSNOW)
library(parallel)
library(randomForest)
set.seed(123)
ncores <- 2
cl <- makeCluster(ncores)
registerDoSNOW(cl)
nr <- 1000
x <- matrix(runif(100000), nr)
y <- gl(4, nr/4)

trainX <- x[1:800,]
trainY <- y[1:800]

testX <- x[801:nrow(x),]
testY <- y[801:length(y)]

rf <- foreach(i=1:ncores, ntree=rep(100, ncores), .packages='randomForest', .combine=combine) %dopar% {
  set.seed(i)
  randomForest(trainX, trainY, ntree=ntree)
}
stopCluster(cl)

pred <- predict(rf, new=testX)

每台windows电脑(我试过2台windows电脑)

R version 3.0.1 (2013-05-16)
Platform: i386-w64-mingw32/i386 (32-bit)

给了我以下输出

table(pred)
 1  2  3  4 
60 68 72  0 

在 linux 计算机上运行相同的代码(我尝试了 2 台 linux 计算机)

R version 2.15.3 (2013-03-01)
Platform: x86_64-pc-linux-gnu (64-bit)

给了我以下输出

table(pred)
 1  2  3  4 
69 58 73  0 

我在 foreach 循环中使用了种子,所以我认为它应该给我相同的结果,但对于具有相同操作系统的计算机,它只给我相同的结果。为什么这只发生在 withrandomForest而不是 with rnorm?我可以做一些事情来doSNOW在 windows 和 linux 计算机之间获得相同的结果吗?我知道使用doRNG更好,但如果可能的话,我想用 获得相同的结果doSNOW......

4

0 回答 0