gpt4 book ai didi

R optimParallel - 找不到函数

转载 作者:行者123 更新时间:2023-12-03 03:24:51 24 4
gpt4 key购买 nike

我试图了解 optimParallel 如何处理嵌入式函数:

fn1 <- function(x){x^2-x+1}
fn2 <- function(x){fn1(x)} # effectively fn1

cl <- parallel::makeCluster(parallel::detectCores()-1)
parallel::setDefaultCluster(cl = cl)

optimParallel::optimParallel(par = 0, fn = fn1) # Worked
optimParallel::optimParallel(par = 0, fn = fn2) # Not working

parallel::setDefaultCluster(cl=NULL)
parallel::stopCluster(cl)

为什么第二个不起作用?错误消息是

Error in checkForRemoteErrors(val) : 
3 nodes produced errors; first error: could not find function "fn1"

如何解决?

最佳答案

此问题特定于所使用的集群类型:

如果FORK集群是在函数定义之后创建的,那么它就可以工作。FORK 集群仅适用于类似 Linux 的系统:

library(optimParallel)
fn1 <- function(x) x^2-x+1
fn2 <- function(x) fn1(x)
cl <- makeCluster(detectCores()-1, type="FORK")
setDefaultCluster(cl=cl)
optimParallel(par=0, fn=fn2)[[1]]
## [1] 0.5

对于其他集群类型,可以将 fn1 作为参数添加到 fn2 并将其作为 ... 参数添加到 optimParallel ():

fn1 <- function(x) x^2-x+1 
fn2 <- function(x, fn1) fn1(x)
cl <- makeCluster(detectCores()-1)
setDefaultCluster(cl=cl)
optimParallel(par=0, fn=fn2, fn1=fn1)[[1]]
## [1] 0.5

或者,可以将 fn1 导出到集群中的所有 R 进程:

fn1 <- function(x) x^2-x+1 
fn2 <- function(x) fn1(x)
cl <- makeCluster(detectCores()-1)
setDefaultCluster(cl=cl)
clusterExport(cl, "fn1")
optimParallel(par=0, fn=fn2)[[1]]
## [1] 0.5

关于R optimParallel - 找不到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58601196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com