numpy阵列点积

时间:2019-01-04 08:32:33

标签: python numpy dot-product

我们都知道向量之间的点积必须返回标量:

import numpy as np
a = np.array([1,2,3])
b = np.array([3,4,5])
print(a.shape) # (3,)
print(b.shape) # (3,)
a.dot(b) # 26
b.dot(a) # 26

完美。但是,如果我们使用“实数”(请看Difference between numpy.array shape (R, 1) and (R,))行向量或列向量,那么为什么numpy点积会在尺寸上返回错误?

arow = np.array([[1,2,3]])
brow = np.array([[3,4,5]])
print(arow.shape) # (1,3)
print(brow.shape) # (1,3)
arow.dot(brow) # ERROR
brow.dot(arow) # ERROR

acol = np.array([[1,2,3]]).reshape(3,1)
bcol = np.array([[3,4,5]]).reshape(3,1)
print(acol.shape) # (3,1)
print(bcol.shape) # (3,1)
acol.dot(bcol) # ERROR
bcol.dot(acol) # ERROR

2 个答案:

答案 0 :(得分:3)

由于显式添加了第二维,因此不再使用向量,而是使用二维矩阵。取矩阵的点积时,乘积的内部尺寸必须匹配。

因此,您需要转置一个矩阵。您转置的那一个将确定结果的含义和形状。

1x3乘以3x1矩阵将得到1x1矩阵(即标量)。这是内部产品。 1x3矩阵的3x1倍将产生3x3的外部乘积。

答案 1 :(得分:1)

您还可以使用@运算符,它实际上是矩阵乘法。 在这种情况下,以及在点积中,您都需要注意矩阵的大小(ndarray始终应为dim兼容),但是它更具可读性:

>>> a = np.array([1,2,3])
>>> a.shape
(3,)
>>> b= np.array([[1,2,3]])
>>> b.shape
(1, 3)
>>> a@b
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: shapes (3,) and (1,3) not aligned: 3 (dim 0) != 1 (dim 0)
>>> a@b.T
array([14])