pytorch广播如何运作?

Aer*_*rin 4 python numpy linear-algebra numpy-broadcasting pytorch

torch.add(torch.ones(4,1), torch.randn(4))
Run Code Online (Sandbox Code Playgroud)

产生尺寸为Tensor : torch.Size([4,4]).

有人可以提供这背后的逻辑吗?

kma*_*o23 13

PyTorchbroadcasting基于numpy广播语义,可以通过阅读numpy broadcasting rulesPyTorch广播指南来理解.用一个例子来阐述这个概念可以直观地理解它.所以,请看下面的例子:

In [27]: t_rand
Out[27]: tensor([ 0.23451,  0.34562,  0.45673])

In [28]: t_ones
Out[28]: 
tensor([[ 1.],
        [ 1.],
        [ 1.],
        [ 1.]])
Run Code Online (Sandbox Code Playgroud)

现在torch.add(t_rand, t_ones),将其可视化为:

               # shape of (3,)
               tensor([ 0.23451,      0.34562,       0.45673])
      # (4, 1)          | | | |       | | | |        | | | |
      tensor([[ 1.],____+ | | |   ____+ | | |    ____+ | | |
              [ 1.],______+ | |   ______+ | |    ______+ | |
              [ 1.],________+ |   ________+ |    ________+ |
              [ 1.]])_________+   __________+    __________+
Run Code Online (Sandbox Code Playgroud)

这应该给出具有张量形状的输出(4,3):

# shape of (4,3)
In [33]: torch.add(t_rand, t_ones)
Out[33]: 
tensor([[ 1.23451,  1.34562,  1.45673],
        [ 1.23451,  1.34562,  1.45673],
        [ 1.23451,  1.34562,  1.45673],
        [ 1.23451,  1.34562,  1.45673]])
Run Code Online (Sandbox Code Playgroud)

另外,请注意,即使我们以与前一个相反的顺序传递参数,我们也会得到完全相同的结果:

# shape of (4, 3)
In [34]: torch.add(t_ones, t_rand)
Out[34]: 
tensor([[ 1.23451,  1.34562,  1.45673],
        [ 1.23451,  1.34562,  1.45673],
        [ 1.23451,  1.34562,  1.45673],
        [ 1.23451,  1.34562,  1.45673]])
Run Code Online (Sandbox Code Playgroud)

无论如何,我更喜欢以前的理解方式,以获得更直接的直观性.


为了图片理解,我剔除了下面列举的更多例子:

Example-1:

广播1


Example-2::

theano广播

TF分别代表True以及False和我们一起让广播(来源:哪些维度表示Theano).


Example-3:

以下是一些形状,其中数组b被 适当地广播以匹配数组的形状a.

可播放的形状

  • 很好的答案和例子,尤其是图片示例 (2认同)

Mat*_*haq 11

示例a + b

让:

a.shape = (2, 3, 4, 5, 1, 1, 1)
b.shape = (      4, 1, 6, 7, 8)
Run Code Online (Sandbox Code Playgroud)

第 1 步:将在 左侧b进行填充(左侧!),直到两者具有相同数量的轴:

a.shape = (2, 3, 4, 5, 1, 1, 1)
b.shape = (1, 1, 4, 1, 6, 7, 8)    <-- padded left with 1s
Run Code Online (Sandbox Code Playgroud)

步骤 2:接下来,如果 的轴的b长度为1,则该轴将重复,直到其长度与 的相应轴匹配a

a.shape = (2, 3, 4, 5, 1, 1, 1)
b.shape = (2, 3, 4, 5, 6, 7, 8)    <-- changed 1s to match a
Run Code Online (Sandbox Code Playgroud)

步骤 3:接下来,如果 的轴的a长度为1,则该轴将重复,直到其长度与 的相应轴匹配b

a.shape = (2, 3, 4, 5, 6, 7, 8)    <-- changed 1s to match b
b.shape = (2, 3, 4, 5, 6, 7, 8)
Run Code Online (Sandbox Code Playgroud)

这些形状匹配,因此a + b会成功运行。(如果它们不匹配,a + b就会失败。)

  • 这个答案比投票最多的答案要好得多,因为它清楚地显示了我们如何获得最终结果的例程。 (3认同)