在 numpy 中,我意识到以下两个计算会产生不同的结果。
a = np.array([1,2,3,4])
b = np.array([1,2,3,4])
dot_product1 = np.dot(a, b) <--- I think this should be an error
print(dot_product1)
a = np.array([1,2,3,4])
b = np.array([1,2,3,4]).reshape(-1,1)
dot_product2 = np.dot(a, b)
print(dot_product2)
dot_product1 是标量值 30,但 dot_product2 是 1x1 矩阵,[30]。
我对线性代数的理解是,我们无法计算 1 x 4 矩阵与另一个 1 x 4 矩阵的点积。我预计第三行会失败,但它成功了。
代码的第二部分计算一个 1 x 4 矩阵和一个 4 x 1 矩阵,生成一个 1 x 1 矩阵。这正是我所期望的。
有人可以帮忙解释一下这些计算之间有什么区别吗?
您阅读了
np.dot
文档吗?注意它关于 1d 参数的说法吗?
In [209]: a = np.array([1,2,3,4])
...: b = np.array([1,2,3,4])
...: dot_product1 = np.dot(a, b)
...: print(dot_product1, type(dot_product1))
...:
...: a = np.array([1,2,3,4])
...: b = np.array([1,2,3,4]).reshape(-1,1)
...: dot_product2 = np.dot(a, b)
...: print(dot_product2, type(dot_product2), dot_product2.shape)
30 <class 'numpy.int32'>
[30] <class 'numpy.ndarray'> (1,)
In [210]: a.shape, b.shape
Out[210]: ((4,), (4, 1))
第一个确实产生一个标量,一个内积。与
np.sum(a,b)
相同。
第二个将 (4,) 与 (4,1) 组合,产生 (1,) 形状。不是 1x1!