python - 用 Nd 数组和一维数组理解 numpy.dot
问题描述
对于由于不清楚我在问什么而投票关闭的人,以下是我帖子中的问题:
- 谁能告诉我结果是
y
什么? - 数学中有什么叫做和积的东西吗?
- 是否
x
受制于广播? - 为什么是
y
列/行向量? - 万一
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]])
呢?
解决方案
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)
推荐阅读
- google-cloud-platform - Google Cloud Vision DOCUMENT_TEXT_DETECTION API 是否可配置?
- node.js - 在没有客户端 ID 的情况下在开发中使用条带连接
- python - 在 python 列表中查找未与相似值分组的项目
- python - 在循环熊猫中计算不同日子的平均值
- php - 无法刷新 Quickbooks API 中的访问令牌。检查 TLS 1.2 的 cURL 版本时出错
- speech-recognition - Google 针对 Google Meet 的新降噪器功能 (https://www.youtube.com/watch?v=1q61B8zdSV0)
- coq - 在什么情况下可以判定平等的平等?
- python - 以最正确的方式继承类实例属性
- python - OpenCV 错误:(addWeighted)操作既不是“数组操作数组”
- email - 用于复制新电子邮件主题的 AppleScript 代码