Numpy数组广播规则

2024-04-27 16:14:41 发布

您现在位置: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形状
2条回答

好吧,后轴的含义在链接的文档页面上有解释。 如果有两个不同维数的数组,比如一个是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.

相关问题 更多 >