首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >R中的快速并行二分距离计算

R中的快速并行二分距离计算
EN

Stack Overflow用户
提问于 2020-10-21 13:43:07
回答 1查看 281关注 0票数 7

有并行Rcpp后端的R中的二分距离的最快计算是什么?

parallelDist是一个很好的包,它有cpp后端和多线程支持,但不支持二分距离计算(据我所知)。

利用parallelDist() 进行二部距离矩阵的计算。除了计算m1:m2外,还包括计算m1:m1和m2:m2 --效率很低。

代码语言:javascript
运行
复制
library(parallelDist)

bipartiteDist <- function(matrix1,matrix2){
  matrix12 <- rbind(matrix1,matrix2)
  d <- parallelDist(matrix12)
  d <- as.matrix(d)[(1:nrow(matrix1)),((nrow(matrix1)+1):(nrow(matrix1)*2))]
  d
}

matrix1 <- abs(matrix(rnorm(1000),10,100000))
matrix2 <- abs(matrix(rnorm(1000),10,100000))

dist <- bipartiteDist(matrix1, matrix2)

当超过3个核心可用时,这种方法比pDist或纯R实现更快。

pdist对于计算二分距离是完美的,但不支持多线程。

并行化二分距离计算的快速实现吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-27 16:55:11

wordspace dist.matrix()函数支持二部距离的并行计算。

wordspace parallelDist Benchmarking

代码语言:javascript
运行
复制
matrix1 <- abs(matrix(rnorm(1000),100,100000))
matrix2 <- abs(matrix(rnorm(1000),100,100000))

library(rbenchmark)
library(parallelDist)
library(wordspace)

bipartiteDist_parallelDist <- function(matrix1,matrix2){
  matrix12 <- rbind(matrix1,matrix2)
  d <- parallelDist(matrix12, method = "euclidean")
  d <- as.matrix(d)[(1:nrow(matrix1)),((nrow(matrix1)+1):(nrow(matrix1)*2))]
  d
}

bipartiteDist_wordspace <- function(matrix1,matrix2){
  wordspace.openmp(threads = wordspace.openmp()$max)
  dist.matrix(matrix1,matrix2, byrow = TRUE, method = "euclidean", convert = FALSE)
}

benchmark("parallelDist" = {
            bd1 <- bipartiteDist_parallelDist(matrix1,matrix2)
          },
          "wordspace" = {
            bd2 <- bipartiteDist_wordspace(matrix1,matrix2)
          },
          replications = 1,
          columns = c("test", "replications", "elapsed",
                      "relative", "user.self", "sys.self"))

plot(bd1,bd2) # yes, both methods give near-identical results

基准结果:

代码语言:javascript
运行
复制
          test replications elapsed relative user.self sys.self
1 parallelDist            1   2.120   12.184   126.145    0.523
2    wordspace            1   0.174    1.000     3.749    0.252

我用了80根线。

--进一步提高速度的框架

wordspace的作者承认强调低内存负载而不是速度,因此增加速度增益是可能的(来源)。

例如,这里是欧几里得距离的一般框架:

代码语言:javascript
运行
复制
bipartiteDist3 <- function(matrix1,matrix2){
  m1tm2 <- tcrossprod(matrix1,matrix2)
  sq1 <- rowSums(matrix1^2)
  sq2 <- rowSums(matrix2^2)
  out0 <- outer(sq1, sq2, "+") - 2 * m1tm2
  sqrt(out0)
}

我对为稀疏矩阵优化的并行化解非常感兴趣。据我所知,wordspace并不能优化稀疏性。例如,有一些可并行的稀疏矩阵实现,它们分别是tcrossprod、rowSums和外部函数等价物。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64464885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档