PyTorch广播失败。遵循“{规则”

时间:2017-10-07 23:07:54

标签: python numpy torch pytorch

我有一些让我感到困惑的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:

  

如果符合以下规则,则两个张量是“可播放的”:

     
      
  1. 每个张量至少有一个维度。
  2.   
  3. 在尺寸大小上进行迭代时,从尾随尺寸开始,尺寸尺寸必须相等,其中一个为1,或者其中一个不存在。
  4.   

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

出了什么问题?我是否误解了文档,如果是,那么什么语法会产生相同的结果?

1 个答案:

答案 0 :(得分:0)

确认您使用的是正确版本的pytorch。它必须是0.2.0,这是在pytorch中引入广播的时候。

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

Out[3]: '0.2.0_4'
相关问题