首页 > 解决方案 > 用 Nd 数组和一维数组理解 numpy.dot

问题描述

对于由于不清楚我在问什么而投票关闭的人,以下是我帖子中的问题:

  1. 谁能告诉我结果是y什么?
  2. 数学中有什么叫做和积的东西吗?
  3. 是否x受制于广播?
  4. 为什么是y列/行向量?
  5. 万一x=np.array([[7],[2],[3]])呢?
w=np.array([[1,2,3],[4,5,6],[7,8,9]])
x=np.array([7,2,3])
y=np.dot(w,x)

谁能告诉我结果是y什么?

在此处输入图像描述 我特意把截图拼接起来,让你假装自己在测试,不能运行 python 来得到结果。

https://docs.scipy.org/doc/numpy-1.15.4/reference/generated/numpy.dot.html#numpy.dot

如果 a 是 ND 数组且 b 是一维数组,则它是 a 和 b 的最后一个轴上的和积。

数学中有什么叫做和积的东西吗?

是否x受制于广播?

为什么是y列/行向量?

万一x=np.array([[7],[2],[3]])呢?

标签: pythonnumpy

解决方案


np.dot如果尺寸与乘法相匹配,则只不过是矩阵乘法(即 w 为 3x3,x 为 1x3,因此无法进行 WX 的矩阵乘法,但 XW 可以)。在第一种情况下:

>>> w=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> x=np.array([7,2,3])
>>> w.shape
(3, 3)
>>> x.shape # 1d vector
(3, )

所以在这种情况下,它返回W 的每一行与 X的内积:

>>> [np.dot(ww,x) for ww in w]
[20, 56, 92]
>>> np.dot(w,x)
array([20, 56, 92]) # as they are both same

更改顺序

>>> y = np.dot(x,w) # matrix mult as usual
>>> y
array([36, 48, 60])

在第二种情况下:

>>> x=np.array([[7],[2],[3]])
>>> x.shape
(3, 1)
>>> y = np.dot(w,x) # matrix mult
>>> y
array([[20],
       [56],
       [92]])

但是,这个时间维度与乘法 (3x1,3x3) 和内积 (1x1,1x3) 都不匹配,因此会引发错误。

>>> y = np.dot(x,w)
Traceback (most recent call last):

  File "<ipython-input-110-dcddcf3bedd8>", line 1, in <module>
    y = np.dot(x,w)

ValueError: shapes (3,1) and (3,3) not aligned: 1 (dim 1) != 3 (dim 0)

推荐阅读