PyTorch 广播失败。 "Rules" 已关注

PyTorch Broadcasting Failing. "Rules" Followed

我有一些 PyTorch 示例让我感到困惑,我希望能够解决这个问题。

首先,根据 PyTorch 页面,我希望这些示例能够像它们的 numpy 等价物一样工作,即 these。第一个例子非常直观。这些兼容广播:

Image  (3d array): 256 x 256 x 3
Scale  (1d array):             3
Result (3d array): 256 x 256 x 3

以这些为例:

torch.Tensor([[1,2,3]])/torch.Tensor([1,2,3])
Out[5]: 

 1  1  1
[torch.FloatTensor of size 1x3]
torch.Tensor([[1,2,3]])/torch.Tensor([1,2,3])
Out[6]: 

  1  1  1
[torch.FloatTensor of size 1x3]

torch.Tensor([[[1,2,3]]])/torch.Tensor([1,2,3])
Out[7]: 

(0 ,.,.) = 
  1  1  1
[torch.FloatTensor of size 1x1x3]

但是,这是 numpy 示例的结果:

torch.randn(256,256,3)/torch.Tensor([1,2,3])
Traceback (most recent call last):

  File "<ipython-input-12-4c328d453e24>", line 1, in <module>
    torch.randn(256,256,3)/torch.Tensor([1,2,3])

  File "/home/nick/anaconda3/lib/python3.6/site-packages/torch/tensor.py", line 313, in __div__
    return self.div(other)

RuntimeError: inconsistent tensor size at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/TH/generic/THTensorMath.c:873

Here is an excerpt which says this ought to work:

Two tensors are “broadcastable” if the following rules hold:

  1. Each tensor has at least one dimension.
  2. When iterating over the dimension sizes, starting at the trailing dimension, the dimension sizes must either be equal, one of them is 1, or one of them does not exist.

如果将张量转换为 numpy 数组,算法将按预期工作。

怎么了?我是否误解了文档?如果是,是什么语法导致了相同的结果?

确认您使用的是正确版本的 pytorch。肯定是0.2.0,也就是pytorch引入broadcasting的时候。

In[2]: import torch
In[3]: torch.__version__

Out[3]: '0.2.0_4'