Python * 运算会比 np.matmul 效率高吗?

2019-03-25 10:16:30 +08:00
 SeaRecluse

对比浮点数矩阵运算测试。
a = np.array([
[
[0.12,0.23,0.34,0.45], [0.56,0.67,0.78,0.89], [0.91,0.1011,0.1112,0.1213], [0.1314,0.1415,0.1516,0.1617] ],
[
[0.12,0.23,0.34,0.45], [0.56,0.67,0.78,0.89], [0.91,0.1011,0.1112,0.1213], [0.1314,0.1415,0.1516,0.1617] ],
[
[0.12,0.23,0.34,0.45], [0.56,0.67,0.78,0.89], [0.91,0.1011,0.1112,0.1213], [0.1314,0.1415,0.1516,0.1617] ],
[
[0.12,0.23,0.34,0.45], [0.56,0.67,0.78,0.89], [0.91,0.1011,0.1112,0.1213], [0.1314,0.1415,0.1516,0.1617] ],
])

b = np.array([
[
[0.12,0.23,0.34,0.45], [0.56,0.67,0.78,0.89], [0.91,0.1011,0.1112,0.1213], [0.1314,0.1415,0.1516,0.1617] ],
[
[0.12,0.23,0.34,0.45], [0.56,0.67,0.78,0.89], [0.91,0.1011,0.1112,0.1213], [0.1314,0.1415,0.1516,0.1617] ],
[
[0.12,0.23,0.34,0.45], [0.56,0.67,0.78,0.89], [0.91,0.1011,0.1112,0.1213], [0.1314,0.1415,0.1516,0.1617] ],
[
[0.12,0.23,0.34,0.45], [0.56,0.67,0.78,0.89], [0.91,0.1011,0.1112,0.1213], [0.1314,0.1415,0.1516,0.1617] ],
])

A: c = a * b
B: c = np.matmul(a,b)
C: c = a @ b

测试下来耗时 A < B < C ???
这是啥情况,原生*运算比 numpy 优化过的速度还快???

2459 次点击
所在节点    Python
10 条回复
silkriver
2019-03-25 10:30:45 +08:00
你这全都是 numpy 优化过的速度…… ufunc 了解一下
* 和 np.multiply 等价
@ 和 np.matmul 等价
enenaaa
2019-03-25 10:39:43 +08:00
一看就是没学过 c++的, 重载运算符啊。
SeaRecluse
2019-03-25 10:44:47 +08:00
@silkriver 另一个问题是,在进行如下操作时:

a = a * 1000
b = b * 1000

α:c = a * b / 1000000
β:c = a @ b /1000000

为什么 time(A) < time(α),time(C) > time(β)呢😂?
其实本来是想验证浮点数计算的优化的,后者才是正式表达的矩阵乘法运算吧~
SeaRecluse
2019-03-25 10:46:04 +08:00
@enenaaa 你这样让我的写的第一个 cout << "Hello World" << endl; 很尴尬😂
silhouette
2019-03-25 11:11:19 +08:00
兄弟,运算符重载了解一下
silkriver
2019-03-25 12:28:55 +08:00
这很正常因为矩阵乘法运算量更大
menc
2019-03-25 17:14:17 +08:00
@SeaRecluse 写过 CPP 还不知道重载运算符不是更尴尬么。。
SeaRecluse
2019-03-25 17:26:49 +08:00
@menc 知道啊,不过写动态语言写多了完全忽略掉了 [捂脸
menc
2019-03-26 15:46:13 +08:00
@SeaRecluse python 的运算符重载也是很常用的东西
necomancer
2019-03-29 21:47:35 +08:00
* 不是矩阵乘法,计算量不一样。

In [1]:
...: a = random.random((1000,1000))

In [2]:
...: b = random.random((1000,1000))

In [3]: np.allclose(a@b, np.matmul(a,b))
Out[3]: True

In [4]: np.allclose(a*b, np.matmul(a,b))
Out[4]: False

In [5]: %timeit a@b
34.7 ms ± 1.91 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [6]: %timeit np.matmul(a,b)
34.6 ms ± 1.14 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [7]: np.__version__
Out[7]: '1.15.1'

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/548179

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX