【发布时间】:2019-10-30 18:12:27
【问题描述】:
我目前在 R 中使用 parallel 包,我正在尝试通过设置种子来使工作可重现。
但是,如果您在创建集群之前设置种子并并行执行您想要的任务,出于某种原因,它不会使其可重现。我想我需要在制作集群时为每个核心设置种子。
我在这里做了一个小例子来说明我的问题:
library(parallel)
# function to generate 2 uniform random numbers
runif_parallel <- function() {
# make cluster of two cores
cl <- parallel::makeCluster(2)
# sample uniform random numbers
samples <- parallel::parLapplyLB(cl, X = 1:2, fun = function(i) runif(1))
# close cluster
parallel::stopCluster(cl)
return(unlist(samples))
}
set.seed(41)
test1 <- runif_parallel()
set.seed(41)
test2 <- runif_parallel()
# they should be the same since they have the same seed
identical(test1, test2)
在此示例中,test1 和 test2 应该相同,因为它们具有相同的种子,但它们返回不同的结果。
请问我哪里出错了?
请注意,我编写此示例的方式必须模仿我现在的使用方式 - 可能有更简洁的方法可以并行生成两个随机统一数。
【问题讨论】:
-
在函数(i)中设置种子
标签: r parallel-processing