pytorch compute pairwise difference:NumPy与PyTorch和不同PyTorch版本的结果不正确

问题描述 投票:1回答:2

假设我有两个数组,我想计算相同形状的两个矩阵的每两行之间的行方差异如下。这是numpy中程序的样子,我想在pytorch中复制相同的东西。

>>> a = np.array([[1,2,3],[4,5,6]])
>>> b = np.array([[3,4,5],[5,3,2]])
>>> c = a[np.newaxis,:,:] - b[:,np.newaxis,:]
>>> print(c)
[[[-2 -2 -2]
  [ 1  1  1]]

 [[-4 -1  1]
  [-1  2  4]]]

顺便说一下,我尝试使用pytorch做同样的事情,但它不起作用。无论如何我们可以在pytorch中完成同样的事情

>>> import torch
>>> a = torch.from_numpy(a)
>>> b = torch.from_numpy(b)
>>> c1 = a[None,:,:]
>>> c2 = b[:,None,:]
>>> diff = c1 - c2
>>> print(diff.size())
torch.Size([1, 2, 3])

我其实是在寻找torch.Size([2,2,3])。 (P.S.我也试过从pytorch挤压,但它不起作用)。

python numpy pytorch tensor numpy-ndarray
2个回答
3
投票

由于使用PyTorch 0.1,出现了这个问题。如果使用PyTorch 1.0.1,NumPy的相同操作一般化为PyTorch而没有任何修改和问题。以下是Colab中运行的快照。

enter image description here

我们可以看到,我们确实得到了相同的结果。


这是尝试重现您获得错误结果时遇到的错误:

>>> t1 = torch.from_numpy(a)
>>> t2 = torch.from_numpy(b)
>>> t1[np.newaxis, ...] - t2[:, np.newaxis, ...]

(0 ,.,.) = 
 -2 -2 -2
 -1  2  4
[torch.LongTensor of size 1x2x3]

>>> torch.__version__
'0.1.12_1'

所以,请将你的PyTorch版本升级到1.0.1!


Digging more into for details:

它在PyTorch 0.1版中不起作用的主要原因是广播没有完全实现。基本上,张量提升为3D,然后进行减法可以分两步实现,如(版本1.0.1):

>>> t1[:1, ] - t2
>>> tensor([[-2, -2, -2],   # t1_r1
            [-4, -1,  1]])  # t1_r2

>>> t1[1:, ] - t2
>>> tensor([[ 1,  1,  1],   # t2_r1
            [-1,  2,  4]])  # t2_r2

通过按行顺序堆叠行(t1_r1,t2_r1,t1_r2,t2_r2)将上述两个操作的结果放在一起,在每个行为2D之后将给出形状(2, 2, 3)

现在,尝试在版本0.1中执行上述两个步骤,它会抛出错误:

RuntimeError:/opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/TH/generic/THTensorMath.c:831中的张量大小不一致


1
投票

我使用的是最新版本的Pytorch 1.0.1。这个解决方案对我有用:


a = torch.tensor([[1,2,3],[4,5,6]])
b = torch.tensor([[3,4,5],[5,3,2]])
c = a.view(1, 2, 3) - b.view(2, 1, 3)
"""
tensor([[[-2, -2, -2],
         [ 1,  1,  1]],

        [[-4, -1,  1],
         [-1,  2,  4]]])
"""
c.size()
"""
torch.Size([2, 2, 3])
"""
© www.soinside.com 2019 - 2024. All rights reserved.