【发布时间】:2022-01-21 14:43:00
【问题描述】:
我使用foreach() 循环并行生成随机数组。但是我在所有并行过程中都得到了相同的结果。如何在每个并行进程中添加随机性,使每个进程彼此不同?
library(doFuture)
library(foreach)
# Parallel programming
registerDoFuture()
plan(multicore, workers = 3)
res = foreach(iter = 1:3) %dopar%
{
# generate random array
x = runif(n = 5)
}
所有并行生成的数组都是一样的
> res
[[1]]
[1] 0.55882648 0.73863525 0.51284839 0.01454722 0.08909375
[[2]]
[1] 0.55882648 0.73863525 0.51284839 0.01454722 0.08909375
[[3]]
[1] 0.55882648 0.73863525 0.51284839 0.01454722 0.08909375
【问题讨论】:
-
必须与
set.seed中的RNGkind相关。例如对我来说,它工作正常。可以试试改成set.seed(1, kind = "L'Ecuyer-CMRG") -
有一个警告说
1: UNRELIABLE VALUE: One of the foreach() iterations (‘doFuture-1’) unexpectedly generated random numbers without declaring so. There is a risk that those random numbers are not statistically sound and the overall results might be invalid. To fix this, use '%dorng%' from the 'doRNG' package instead of '%dopar%'. This ensures that proper, parallel-safe random numbers are produced via the L'Ecuyer-CMRG method. -
对于协议:
plan的第一次运行我收到了警告...Forked processing ('multicore') is not supported when running R from RStudio...。所以我在控制台中尝试了原始代码,它运行良好。
标签: r foreach parallel.foreach