首页 > 解决方案 > 使用 Numpy,计算大小为 10 的向量与大小为 (5, 10) 的矩阵中的每一行的内积的最佳方法是什么?

问题描述

1. np.dot(vector1*matrix1)
2. np.array([np.dot(row,vector1) for row in matrix1])
3. np.matmul(vector1,matrix1)
4. np.dot(matrix1,vector1)
5. np.sum(matrix1*vector1,axis=1)

标签: pythonnumpy

解决方案


首先,我们可以询问哪些有效!

In [4]: vector1 = np.arange(10)
In [5]: matrix1 = np.arange(50).reshape(5,10)

首先错误的使用方式dot

In [6]: np.dot(vector1*matrix1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-c0ee48ce8d26> in <module>()
----> 1 np.dot(vector1*matrix1)

TypeError: Required argument 'b' (pos 2) not found

下一个有效的

In [7]: np.array([np.dot(row,vector1) for row in matrix1])
Out[7]: array([ 285,  735, 1185, 1635, 2085])

另一种错误的方式 - 的基本规则matmuldot'a的最后一个,b的第二个到最后一个':

In [8]: np.matmul(vector1,matrix1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-90d753017fdf> in <module>()
----> 1 np.matmul(vector1,matrix1)

ValueError: shapes (10,) and (5,10) not aligned: 10 (dim 0) != 5 (dim 0)

使用dot (a (5,10) 对与 (10,) ok) 的正确方法:

In [9]: np.dot(matrix1,vector1)
Out[9]: array([ 285,  735, 1185, 1635, 2085])

和另一个正确的方法。

In [10]: np.sum(matrix1*vector1,axis=1)
Out[10]: array([ 285,  735, 1185, 1635, 2085])

那些有效的产生相同的结果。

[9] 中的顺序也适用于matmul. 也可以写成matrix1 @ vector1

至于“最佳”,我们可以尝试计时。我的猜测是 [9] 最快,[7] 最慢。

(5,10) 与 (10,) 配对的情况是 (5,10) 与 (10,n) 配对以产生 (5,n) 的规范 2d 情况的推广。


推荐阅读