当涉及到 numpy 中两个不同维度的数组时,点积和乘法矩阵是否相同

我在计算两个向量的点积时观察到了奇怪的输出。我的代码是


a1 = np.array([[1], [2], [3]])

a2 = np.array([[1, 2, 3]]) 


print(a1*a2)

print(np.dot(a1, a2))

两者的输出相同,我不明白为什么它在要求点时将两个矩阵相乘


产品。对于形状为 (x, 1) 和 (1, y) 的任何矩阵,都会观察到同样的情况。


谢谢


POPMUISE
浏览 88回答 2
2回答

互换的青春

在 numpy 中,dot并不真正意味着点积。dot本质上类似于矩阵乘法。因此,有人可能会说它既多余又令人困惑,这就是为什么我自己根本不使用它。要获得您似乎想要的行为,您可以使用vdot:>>> np.vdot(a1,a2)14>>> np.vdot(a2,a1)14

繁星淼淼

In [189]: a1 = np.array([[1], [2], [3]])&nbsp; &nbsp; &nbsp;...: a2 = np.array([[1, 2, 3, 4]])In [190]:&nbsp;In [190]: a1.shape, a2.shapeOut[190]: ((3, 1), (1, 4))矩阵乘法:In [191]: a1@a2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # np.matmulOut[191]:&nbsp;array([[ 1,&nbsp; 2,&nbsp; 3,&nbsp; 4],&nbsp; &nbsp; &nbsp; &nbsp;[ 2,&nbsp; 4,&nbsp; 6,&nbsp; 8],&nbsp; &nbsp; &nbsp; &nbsp;[ 3,&nbsp; 6,&nbsp; 9, 12]])广播元素乘法:In [192]: a1*a2Out[192]:&nbsp;array([[ 1,&nbsp; 2,&nbsp; 3,&nbsp; 4],&nbsp; &nbsp; &nbsp; &nbsp;[ 2,&nbsp; 4,&nbsp; 6,&nbsp; 8],&nbsp; &nbsp; &nbsp; &nbsp;[ 3,&nbsp; 6,&nbsp; 9, 12]])(3,1) 与 (1,4) => (3,4) 与 (3,4) => (3,4)调整 Size 1 维度以匹配其他数组与matmul:In [193]: a1.dot(a2)Out[193]:&nbsp;array([[ 1,&nbsp; 2,&nbsp; 3,&nbsp; 4],&nbsp; &nbsp; &nbsp; &nbsp;[ 2,&nbsp; 4,&nbsp; 6,&nbsp; 8],&nbsp; &nbsp; &nbsp; &nbsp;[ 3,&nbsp; 6,&nbsp; 9, 12]])形状不匹配:In [194]: a2.dot(a1)Traceback (most recent call last):&nbsp; File "<ipython-input-194-4e2276e15f5f>", line 1, in <module>&nbsp; &nbsp; a2.dot(a1)ValueError: shapes (1,4) and (3,1) not aligned: 4 (dim 1) != 3 (dim 0)用爱因斯坦符号:In [195]: np.einsum('ij,jk->ik',a1,a2)Out[195]:&nbsp;array([[ 1,&nbsp; 2,&nbsp; 3,&nbsp; 4],&nbsp; &nbsp; &nbsp; &nbsp;[ 2,&nbsp; 4,&nbsp; 6,&nbsp; 8],&nbsp; &nbsp; &nbsp; &nbsp;[ 3,&nbsp; 6,&nbsp; 9, 12]])在真正的矩阵乘法中,这会将所有行乘以所有列,并在共享维度上求和。因为j维度为 1,所以求和没有什么区别。我们可以看到广播的效果:In [198]: np.broadcast_arrays(a1,a2)Out[198]:&nbsp;[array([[1, 1, 1, 1],&nbsp; &nbsp; &nbsp; &nbsp; [2, 2, 2, 2],&nbsp; &nbsp; &nbsp; &nbsp; [3, 3, 3, 3]]),&nbsp;array([[1, 2, 3, 4],&nbsp; &nbsp; &nbsp; &nbsp; [1, 2, 3, 4],&nbsp; &nbsp; &nbsp; &nbsp; [1, 2, 3, 4]])]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python