并行化应用到 parRapply
Parallelization Apply to parRapply
我的数据集是:
ll <- matrix(c(5, 6, 60, 60), ncol=2)
然后我使用库 "sp" 中的函数 spDistsN1 来获得距离矩阵 申请:
apply(ll, 1, function(x) spDistsN1(as.matrix(ll), x, longlat = T))
但我想通过并行化来实现,因此:
library(parallel)
ncore <- detectCores()
cl <- makeCluster(ncore)
clusterEvalQ(cl = cl, expr = c(library(sp)))
parRapply(cl = cl, x = ll, FUN = function(x) spDistsN1(as.matrix(ll), x,
longlat = T))
它显示以下错误:
checkForRemoteErrors(val) 错误:
4个节点产生错误;第一个错误:找不到对象 'll'
我该如何解决?
您需要将所有变量导出给工作人员。参见 ?parallel::clusterExport
。
使用 parallel 的 parApply()
或 parRapply()
更简单的替代方法是使用 future.apply 包的 future_apply()
(免责声明:我是作者),因为全局变量自动导出 - 无需担心 parallel::clusterExport()
等。只需像使用 apply()
一样使用它,例如
library(sp)
library(future.apply)
plan(multiprocess) ## parallelize on local machine
ll <- matrix(c(5, 6, 60, 60), ncol = 2)
## Sequentially
y0 <- apply(ll, 1, function(x) A(ll, x, longlat = TRUE))
print(y0)
# [,1] [,2]
# [1,] 0.00000 55.79918
# [2,] 55.79918 0.00000
## In parallel
y1 <- future_apply(ll, 1, function(x) spDistsN1(ll, x, longlat = TRUE))
print(y1)
# [,1] [,2]
# [1,] 0.00000 55.79918
# [2,] 55.79918 0.00000
print(identical(y1, y0))
# [1] TRUE
您可能还会发现博客 post future.apply - Parallelize Any Base R Apply Function 有帮助。
我的数据集是:
ll <- matrix(c(5, 6, 60, 60), ncol=2)
然后我使用库 "sp" 中的函数 spDistsN1 来获得距离矩阵 申请:
apply(ll, 1, function(x) spDistsN1(as.matrix(ll), x, longlat = T))
但我想通过并行化来实现,因此:
library(parallel)
ncore <- detectCores()
cl <- makeCluster(ncore)
clusterEvalQ(cl = cl, expr = c(library(sp)))
parRapply(cl = cl, x = ll, FUN = function(x) spDistsN1(as.matrix(ll), x,
longlat = T))
它显示以下错误:
checkForRemoteErrors(val) 错误: 4个节点产生错误;第一个错误:找不到对象 'll'
我该如何解决?
您需要将所有变量导出给工作人员。参见 ?parallel::clusterExport
。
使用 parallel 的 parApply()
或 parRapply()
更简单的替代方法是使用 future.apply 包的 future_apply()
(免责声明:我是作者),因为全局变量自动导出 - 无需担心 parallel::clusterExport()
等。只需像使用 apply()
一样使用它,例如
library(sp)
library(future.apply)
plan(multiprocess) ## parallelize on local machine
ll <- matrix(c(5, 6, 60, 60), ncol = 2)
## Sequentially
y0 <- apply(ll, 1, function(x) A(ll, x, longlat = TRUE))
print(y0)
# [,1] [,2]
# [1,] 0.00000 55.79918
# [2,] 55.79918 0.00000
## In parallel
y1 <- future_apply(ll, 1, function(x) spDistsN1(ll, x, longlat = TRUE))
print(y1)
# [,1] [,2]
# [1,] 0.00000 55.79918
# [2,] 55.79918 0.00000
print(identical(y1, y0))
# [1] TRUE
您可能还会发现博客 post future.apply - Parallelize Any Base R Apply Function 有帮助。