R中高效的行矩阵运算

Efficient row wise matrix operation in R

我有 2 个矩阵 M1、M2。对于 M1 中的每一行,我想找到 M1 中该行与 M2 中每一行的乘积的最大值。

我尝试了以下实现,它产生了我想要的结果。

set.seed(1)
st_time = Sys.time()
M1 = matrix(runif(1000*10), nrow=1000, ncol=10)
M2 = matrix(runif(10000*10), nrow=10000, ncol=10)

score = apply(M1, 1, function(x){
  w = M2 %*% diag(x)
  row_max = apply(w, 1, max)
  return(row_max)
})
required_output = t(score)
Sys.time() - st_time

这在我的机器上需要 16 秒。有没有更快的实现? 谢谢!

运行 并行提供更轻松的速度。在我的机器上,串行版本是 15 秒,并行版本不到 4 秒。

加载包

# Comes with R
library(parallel)

# Make the cluster 
# 8 cores, see detectCores() 
cl = makeCluster(8)

然后我们需要显式导出M2

clusterExport(cl, "M2")

和运行正常

score_par = function() {
  parApply(cl, M1, 1, function(x){
    w = M2 %*% diag(x)
    row_max = apply(w, 1, max)
    return(row_max)
  })
}
system.time(score_par())

使用 for 循环让我的速度大大提高

set.seed(1)
M1 = matrix(runif(1000*10), nrow=1000, ncol=10)
M2 = matrix(runif(10000*10), nrow=10000, ncol=10)

st_time = Sys.time()

tm = t(M2)
out = matrix(0, nr=nrow(M1), nc=nrow(M2))

for(i in 1:nrow(M1)){
  out[i, ] = matrixStats::colMaxs(M1[i, ]* tm)
}

Sys.time() - st_time
#Time difference of 1.835793 secs # was ~28secs with yours on my laptop


all.equal(required_output, out)