【问题标题】:Optimizing nested foreach dopar in R在 R 中优化嵌套的 foreach dopar
【发布时间】:2016-12-26 20:09:59
【问题描述】:

我想了解以下代码的结构。想知道它是否需要以不同的方式组织以更快地执行。具体来说,我是否需要在嵌套循环中以不同的方式使用 foreachdopar。目前,内部循环是大部分工作(ddply 有 1-8 个细分变量,每个变量有 10-200 个级别),这就是我并行运行的。为简单起见,我省略了代码细节。

有什么想法吗?我的代码(如下所示)确实有效,但在 6 核、41gb 的机器上需要几个小时。数据集并没有那么大(

for(m in 1:length(Predictors)){  # has up to three elements in the vector

  # construct the dataframe based on the specified predictor
  # subset the original dataframe based on the breakdown variables, outcome, predictor and covariates

  for(l in 1:nrow(pairwisematrixReduced)){  # this has 1-6 rows;subset based on correct comparison groups

    # some code here

    cl <- makeCluster(detectCores())  
    registerDoParallel(cl) 

    for (i in 1:nrow(subsetting_table)){  # this table has about 50 rows

      # this uses the columns specified by k in the glm; the prior columns will be used as breakdown variables
      # up to 10 covariates
      result[[length(result) + 1]] <- foreach(k = 11:17, .packages=c('plyr','reshape2', 'fastmatch')) %dopar% {   

        ddply( 
          df,
          b,   # vector of breakdown variables
          function(x) { 

           # run a GLM and manipulate the output

          ,.parallel = TRUE) # close ddply
      } # close k loop -- set of covariates
    } # close i loop -- subsetting table
  } #close l -- group combinations
} # close m loop - this is the pairwise predictor matrix 

stopCluster(cl)
result <- unlist(result, recursive = FALSE)
tmp2<-do.call(rbind.fill, result)

【问题讨论】:

  • 我建议运行以下命令并阅读%dopar%%:% 之间的区别。 vignette("foreach")vignette("nested")
  • foreach 在 i 内
  • 我错过了foreach,但我建议阅读我上面提到的小插图。将foreachddply 编写为foreach 语句会更容易,其中一个使用%dopar,另一个使用%:%。小插图讨论了并行内循环与外循环的好处。您需要测试自己的代码,因为它依赖于数据,但它变得像在两个 foreach 之间交换 %dopar%%:% 一样简单。
  • 在创建 m * l 时,将 makeClusterregisterDoParallel 移到 for 循环之外,您也可能会看到速度提升足够了。

标签: r foreach plyr doparallel


【解决方案1】:

复制自vignette("nested")

3 使用 %:% 和 %dopar%

在并行化嵌套的 for 循环时,总是存在并行化哪个循环的问题。标准建议是……

您还使用foreach %dopar% 以及ddply.parallel=TRUE。使用六核处理器(可能是超线程)意味着foreach 块将启动 12 个环境,然后ddply 将在每个环境中启动 12 个环境,用于 144 个并发环境。 foreach 应更改为 %do% 以与并行运行内部循环的问题文本一致。或者为了更简洁,将两者都更改为 foreach 并在一个循环中使用 %dopar%,在另一个循环中使用 %:%

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 2018-07-13
    • 1970-01-01
    • 2020-09-04
    • 2019-09-27
    • 2018-04-06
    • 1970-01-01
    • 2016-08-02
    相关资源
    最近更新 更多