gpt4 book ai didi

python - R 中的矩阵乘法速度与 Python 中的一样快?

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:12 24 4
gpt4 key购买 nike

与 python 相比,我在 R 中遇到的矩阵乘法要慢得多。这适用于大型矩阵。例如(在 python 中):

import numpy as np

A = np.random.rand(4112, 23050).astype('float32')
B = np.random.rand(23050, 2500).astype('float32')

%timeit np.dot(A, B)

1 loops, best of 3: 1.09 s per loop

这是 R 中的等价乘法(花费将近 10 倍的时间):

A <- matrix(rnorm(4112*23050), ncol = 23050)
B <- matrix(rnorm(23050*2500), ncol = 2500)

system.time(A %*% B)

user system elapsed
72.032 1.048 9.444

我如何才能在 R 中实现与 python 标准相媲美的矩阵乘法速度?

我已经尝试过的:

1) 部分差异似乎是 python 支持 float32,而 R 仅使用数字,类似于(与?)float64。例如,与上面相同的 python 命令,除了 float64 需要两倍的时间(但仍然比 R 慢 5 倍):

import numpy as np

A = np.random.rand(4112, 23050).astype('float64')
B = np.random.rand(23050, 2500).astype('float64')

%timeit np.dot(A, B)
1 loops, best of 3: 2.24 s per loop

2)我正在为 R 使用 openBLAS 线性代数后端。

3) RcppEigen 详见对 this SO 的回答(请参阅 test.cpp 文件的链接)。乘法在“用户”时间大约快两倍,但在更关键的运行时间内慢 3 倍,因为它只使用 8 个线程中的一个。

library(Rcpp)
sourceCpp("test.cpp")

A <- matrix(rnorm(4112*23050), nrow = 4112)
B <- matrix(rnorm(23050*2500), ncol = 2500)

system.time(res <- eigenMatMult(A, B))
user system elapsed
29.436 0.056 29.551

最佳答案

我将 MROpythonanacondaMKL BLAS 一起使用。以下是相同数据生成过程的结果,即 np.random.rand ('float64') 或 rnorm 和相同的维度 (< em>10 次重复的平均值和标准差):

python :

np.dot(A, B) # 1.3616 s (sd = 0.1776)

R:

Bt = t(B)
a = A %*% B # 2.0285 s (sd = 0.1897)
acp = tcrossprod(A, Bt) # 1.3098 s (sd = 0.1206)
identical(acp, a) # TRUE

关于python - R 中的矩阵乘法速度与 Python 中的一样快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38642521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com