r - 优化 R 中的嵌套 foreach dopar

标签 r foreach plyr doparallel

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

有什么想法吗?我的代码(如下所示)确实可以工作,但在 6 核、41GB 机器上需要几个小时。数据集不是那么大(< 20k 条记录)。

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)

最佳答案

复制自vignette("nested")

3 Using %:% with %dopar%

When parallelizing nested for loops, there is always a question of which loop to parallelize. The standard advice is...

您还使用了 foreach %dopar% 以及 ddply.parallel=TRUE。使用六核处理器(可能还有超线程)意味着 foreach block 将启动 12 个环境,然后 ddply 将在每个环境中启动 12 个环境,从而实现 144 个并发环境。 foreach 应更改为 %do% 以与并行运行内部循环的问题文本保持一致。或者为了使其更清晰,请将两者更改为 foreach 并在一个循环中使用 %dopar% ,在另一个循环中使用 %:%

关于r - 优化 R 中的嵌套 foreach dopar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41335842/

相关文章:

r - 获取数据框中的前 n 行?

r - 在我的包中使用例如 ddply 时,如何摆脱 R CMD 检查生成的注释?

r - 基于分类变量,在 R 中从数据框中子集 n 行

r - 在 R 中将时间转换为 'HMS"字符格式

r - Create_Matrix 'RTextTools' 包的并行计算

PHP - 循环管理复选框

java - Azure Web角色部署后回收

r - 跨多个类别进行分箱

java - 为什么 for-each 循环适用于数组? ( java )

r - 从数据框中提取具有最高值和最低值的行