Numpy阵列广播规则

2024-09-30 16:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在理解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

因为AB都有两个列,所以我认为这是可行的。所以,我可能误解了“尾轴”这个术语,以及它是如何应用于N维数组的

有人能解释一下为什么我的例子不起作用,以及“拖尾轴”是什么意思吗


Tags: numpy元素规则documentation矩阵数组arraytutorial
3条回答
关于广播,我们应该考虑两点。第一:什么是可能的。第二:有多少可能的事情是由numpy完成的

我知道这看起来可能有点混乱,但我会通过一些例子来说明

让我们从零级开始

假设我们有两个矩阵。第一个矩阵有三个维度(称为A),第二个矩阵有五个维度(称为B)。numpy尝试匹配最后一个/后续维度。所以numpy不关心B的前两个维度。然后numpy将这些后续维度相互比较。当且仅当它们相等或其中一个为1时,numpy说“好的,你们两个匹配”。如果这些条件不满足,numpy会“对不起……这不是我的工作!”

但我知道,你们可能会说,当它们是可设计的(4和2/9和3)时,比较最好以能够处理的方式进行。您可以说它可以被复制/广播一个整数(例如2/3 in-out)。我同意你的看法。这就是我开始讨论的原因,我区分了什么是可能的,什么是numpy的能力

好的,拖尾轴的含义在链接文档页面上解释。 如果有两个具有不同维度编号的数组,例如一个1x2x3和另一个2x3,则只比较后面的公共维度,在本例中为2x3。但是如果两个数组都是二维的,那么它们相应的大小必须相等,或者其中一个必须是1。数组具有大小1的维度称为单数维度,数组可以沿着这些维度广播

在您的例子中,您有一个2x24x24 != 2,并且42都不等于1,所以这不起作用

http://cs231n.github.io/python-numpy-tutorial/#numpy-broadcasting

Broadcasting two arrays together follows these rules:

  1. If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.

  2. The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.

  3. The arrays can be broadcast together if they are compatible in all dimensions.
  4. After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
  5. In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension

If this explanation does not make sense, try reading the explanation from the documentation or this explanation.

相关问题 更多 >