我在理解Numpy中阵列广播的规则时遇到了一些困难
显然,如果在两个维度和形状相同的数组上执行元素相乘,一切都很好。此外,如果将多维数组与标量相乘,它也会起作用。这我理解
但是如果你有两个不同形状的N维数组,我不清楚广播规则到底是什么。该documentation/tutorial说明:为了广播,操作中两个数组的后轴的大小必须相同,或者其中一个必须为一
好的,我通过尾轴假设它们指的是M x N
数组中的N
。这意味着,如果我尝试将两个2D数组(矩阵)乘以相等的列数,它应该可以工作吗?除了它没有
>>> from numpy import *
>>> A = array([[1,2],[3,4]])
>>> B = array([[2,3],[4,6],[6,9],[8,12]])
>>> print(A)
[[1 2]
[3 4]]
>>> print(B)
[[ 2 3]
[ 4 6]
[ 6 9]
[ 8 12]]
>>>
>>> A * B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
因为A
和B
都有两个列,所以我认为这是可行的。所以,我可能误解了“尾轴”这个术语,以及它是如何应用于N维数组的
有人能解释一下为什么我的例子不起作用,以及“拖尾轴”是什么意思吗
我知道这看起来可能有点混乱,但我会通过一些例子来说明
让我们从零级开始
假设我们有两个矩阵。第一个矩阵有三个维度(称为A),第二个矩阵有五个维度(称为B)。numpy尝试匹配最后一个/后续维度。所以numpy不关心B的前两个维度。然后numpy将这些后续维度相互比较。当且仅当它们相等或其中一个为1时,numpy说“好的,你们两个匹配”。如果这些条件不满足,numpy会“对不起……这不是我的工作!”
但我知道,你们可能会说,当它们是可设计的(4和2/9和3)时,比较最好以能够处理的方式进行。您可以说它可以被复制/广播一个整数(例如2/3 in-out)。我同意你的看法。这就是我开始讨论的原因,我区分了什么是可能的,什么是numpy的能力
好的,拖尾轴的含义在链接文档页面上解释。 如果有两个具有不同维度编号的数组,例如一个
1x2x3
和另一个2x3
,则只比较后面的公共维度,在本例中为2x3
。但是如果两个数组都是二维的,那么它们相应的大小必须相等,或者其中一个必须是1
。数组具有大小1
的维度称为单数维度,数组可以沿着这些维度广播在您的例子中,您有一个
2x2
和4x2
和4 != 2
,并且4
或2
都不等于1
,所以这不起作用从http://cs231n.github.io/python-numpy-tutorial/#numpy-broadcasting:
相关问题 更多 >
编程相关推荐