在numpy中广播数组 [英] broadcasting arrays in numpy

查看:95
本文介绍了在numpy中广播数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个数组并将其重塑为以下尺寸:(-1,1,1,1)和(-1,1):

I got an array and reshaped it to the following dimentions: (-1,1,1,1) and (-1,1):

 Array A:
[-0.888788523827  0.11842529285   0.319928774626  0.319928774626  0.378755429421  1.225877519716  3.830653798838]

A.reshape(-1,1,1,1):
[[[[-0.888788523827]]]


 [[[ 0.11842529285 ]]]


 [[[ 0.319928774626]]]


 [[[ 0.319928774626]]]


 [[[ 0.378755429421]]]


 [[[ 1.225877519716]]]


 [[[ 3.830653798838]]]]

A.reshape(-1,1):
[[-0.888788523827]
 [ 0.11842529285 ]
 [ 0.319928774626]
 [ 0.319928774626]
 [ 0.378755429421]
 [ 1.225877519716]
 [ 3.830653798838]]

然后我完成了减法运算,广播进入了,所以我得到的矩阵是7x1x7x1.

Then I have done substractig and broadcasting came in, so my resulting matrix is 7x1x7x1.

我很难想象广播的中间步骤.我的意思是我无法想象重复播放数组的哪些元素以及它们在广播时的外观. 请问有人可以阐明这个问题吗?

I have a hard time to visualize the intermediate step what broadcasting does. I mean I cannot imagine what elements of arrays are repeated and what they look like while broadcasting. Could somebody shed some light on this problem,please?

推荐答案

In [5]: arr = np.arange(4)
In [6]: A = arr.reshape(-1,1,1,1)
In [7]: B = arr.reshape(-1,1)
In [8]: C = A + B
In [9]: C.shape
Out[9]: (4, 1, 4, 1)
In [10]: A.shape
Out[10]: (4, 1, 1, 1)
In [11]: B.shape
Out[11]: (4, 1)

有2条基本广播规则:

  • 扩展尺寸以匹配-通过在开始处添加尺寸1尺寸
  • 调整尺寸1的所有尺寸以匹配

因此在此示例中:

 (4,1,1,1) + (4,1)
 (4,1,1,1) + (1,1,4,1)    # add 2 size 1's to B
 (4,1,4,1) + (4,1,4,1)    # adjust 2 of the 1's to 4
 (4,1,4,1)

第一步也许是最令人困惑的. (4,1)扩展为(1,1,4,1),而不是(4,1,1,1).该规则旨在避免歧义-通过以一致的方式扩展,而不一定是人类可能会直观地想要的.

The first step is, perhaps, the most confusing. The (4,1) is expanded to (1,1,4,1), not (4,1,1,1). The rule is intended to avoid ambiguity - by expanding in a consistent manner, not necessarily what a human might intuitively want.

想象一下两个数组都需要扩展才能匹配的情况,并且可以在两个方向上添加一个维度:

Imagine the case where both arrays need expansion to match, and it could add a dimension in either direction:

 (4,) and (3,)
 (1,4) and (3,1)  or (4,1) and (1,3)
 (3,4)            or (4,3)
 confusion

该规则要求程序员选择向右扩展(4,1)或(3,1)的哪一个.然后numpy可以清楚地添加另一个.

The rule requires that the programmer choose which one expands to the right (4,1) or (3,1). numpy can then unambiguously add the other.

举一个简单的例子:

In [22]: A=np.arange(3).reshape(-1,1)
In [23]: B=np.arange(3)
In [24]: C = A+B   (3,1)+(3,) => (3,1)+(1,3) => (3,3)
In [25]: C
Out[25]: 
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])
In [26]: C.shape
Out[26]: (3, 3)

存在[0,2,4],但在C的对角线上.

The [0,2,4] are present, but on the diagonal of C.

当这样广播时,结果是一种outer和:

When broadcasting like this, the result is a kind of outer sum:

In [27]: np.add.outer(B,B)
Out[27]: 
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

这篇关于在numpy中广播数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆