【问题标题】:Using plyr ldply parallel with function within function使用 plyr ldply 与函数内的函数并行
【发布时间】:2021-02-25 18:06:26
【问题描述】:

我有一个具有多个 ID 的数据框,我正在尝试对不同的 ID 集执行特征提取。数据如下所示:

    id  x    y 
1 3812 60    7
2 3812 63  105
3 3812 65 1000
4 3812 69    8
5 3812 75   88
6 3812 78   13

其中 id 具有大约 200 个不同的值。所以我试图从 (x,y) 数据中提取特征,并且我想并行进行,因为对于某些数据集,按顺序进行可能需要大约 20 分钟左右。现在我正在使用 dplyr:

x = d %>% group_by(id) %>% do(data.frame(getFeatures(., func_args))

其中func_args 只是函数getFeaures 的附加函数输入。我正在尝试使用plyr::ldplyparallel=TRUE 来执行此操作,但是在getFeatures 中存在一个问题,我正在使用我编写的另一个函数。所以,当我尝试并行运行时,我得到一个错误:

Error in do.ply(i) : 
  task 1 failed - "could not find function "desparsify""
In addition: Warning messages:
1: <anonymous>: ... may be used in an incorrect context: ‘.fun(piece, ...)’
 
 Error in do.ply(i) : 
  task 1 failed - "could not find function "desparsify""

desparsify 是一个自定义函数,用于处理 (x,y) 数据(它有效地将零添加到数据集中不存在的 x 位置)。当我尝试使用包lsa 中的cosine 函数时,我遇到了类似的错误。在 R 中调用外部/非基本函数时,有没有办法使用并行处理?

【问题讨论】:

    标签: r parallel-processing plyr


    【解决方案1】:

    您没有展示如何设置 plyr 以进行并行化,但我想我可以猜到您在做什么。我也猜你在Windows上。这是一个很小的独立示例,说明了正在发生的事情:

    library(plyr)
    
    ## On Windows, doParallel::registerDoParallel(2) becomes:
    cl <- parallel::makeCluster(2)
    doParallel::registerDoParallel(cl)
    
    desparsify <- function(x) sqrt(x)
    y <- plyr::llply(1:3, function(x) desparsify(x), .parallel=TRUE)
    ## Error in do.ply(i) : 
    ##  task 1 failed - "could not find function "desparsify""
    

    如果您使用 doFuture 而不是 doParallel,则底层的未来框架将确保找到“desparsify”,例如

    library(plyr)
    
    doFuture::registerDoFuture()
    future::plan("multisession", workers = 2)
    
    desparsify <- function(x) sqrt(x)
    y <- plyr::llply(1:3, function(x) desparsify(x), .parallel=TRUE)
    str(y)
    ## List of 3
    ##  $ : num 1
    ##  $ : num 1.41
    ##  $ : num 1.73
    

    (免责声明:我是未来框架的作者)

    PS。请注意,plyr 是一个不再维护的旧包。您可能想研究 future.applyfurrrforeach 以及 doFuture 作为并行化的替代方案。

    【讨论】:

      【解决方案2】:

      有。查看 parApply 函数系列。我通常使用 parLapply 。

      您需要使用cl &lt;- makeCluster(number of cores) 设置核心数并将其与您的 id 向量(可能取决于您的函数如何识别每个 id 的条目)和您的函数一起传递给 parLapply 以生成一个列表,其中您的函数的输出并行应用于每个组。

      cl <- makeCluster(number of cores)
      ids=1:10               
      clusterExport(cl=cl,varlist=c('variable name','function name')) ## in case you need to export variable/functions
      
      result=parLapply(cl=cl,ids, your function)
      stopCluster(cl)
      
      

      【讨论】:

        猜你喜欢
        • 2011-12-07
        • 2019-07-24
        • 2021-05-05
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 2020-11-30
        • 2013-04-25
        • 2016-02-16
        相关资源
        最近更新 更多