python - 使用 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)
解决方案
首先,我们可以询问哪些有效!
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])
另一种错误的方式 - 的基本规则matmul
是dot
'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 情况的推广。
推荐阅读
- .net - 与循环和条件作斗争
- html - FontAwesome 图标显示为正方形,如何解决?
- android - 在 recyclerView 中显示列表,使用改造按照 JSON 中的日期排序
- mindstorms - 在本地托管 EV3 Mindstorms 编辑器的 MakeCode
- matlab - matlab中结构张量的特征值分解
- three.js - 边缘像素在使用片段着色器映射的纹理中重复
- ruby-on-rails - 直接在 JS 中使用 webpacker 3+ 在 Rails 5.2 中支持 Sass
- r - R-Keras - 为什么 val_loss 没有绘图
- networking - 使用 python3 套接字连接到 Web 服务器
- android - 移动网络检查