加快R中大型矩阵的一系列计算

时间:2019-03-19 19:57:16

标签: r performance math matrix

是否有任何建议以编程或数学方式加快R中的计算速度?我提供了一些生成的数据,这些数据与我正在使用的实际数据场景非常匹配。我还尝试使用了apply和parApply,并尝试将其转换为稀疏矩阵,因为它有很多0,但是到目前为止,这是我想出的最快方法。有什么建议可以使其更快吗?我需要进行10,000次计算。

与我的情况非常匹配的数据:

set.seed(7)
# same size matrix as my real data data puzzle
A <- matrix(rbeta((13163*13163),1,1), ncol = 13163, nrow = 13163)

# turn a bunch to 0 to more closely match that I have a lot of 0's in real data
A[A < 0.5] <- 0

# create binary matrix
z <- matrix(rbinom((13163*13163), 1, 0.25), ncol = 13163, nrow = 13163)

我发现Rfast :: rowsums给我最快的结果。

start1 <- Sys.time()
testA <- 1 - exp(Rfast::rowsums(log(1-A*z)))
stop1 <- Sys.time()
stop1 - start1

请原谅我笨拙的基准测试方法...

1 个答案:

答案 0 :(得分:2)

您可以摆脱exp()log()

testB <- 1 - Rfast::rowprods(1-A*z)

这快了八倍。

但是,当您将0和1之间的数字相乘时,最终到处都是0,因此输出向量都是1。

相关问题