将索引和高音的值组合成新的张量

时间:2019-08-01 09:44:16

标签: python pytorch

我有一个像a = torch.tensor([1,2,0,1,2])这样的张量。我想计算一个张量b,其张量a的索引和值如下: b = tensor([ [0,1], [1,2], [2,0], [3,1], [4,2] ])

编辑:a[i] is >= 0

2 个答案:

答案 0 :(得分:1)

一种方法是:

b = torch.IntTensor(list(zip(range(0, list(a.size())[0], 1), a.numpy())))

输出:

tensor([[0, 1],
        [1, 2],
        [2, 0],
        [3, 1],
        [4, 2]], dtype=torch.int32)

或者,您也可以如下使用torch.cat()

a = torch.tensor([1,2,0,1,2])
indices = torch.arange(0, list(a.size())[0])
res = torch.cat([indices.view(-1, 1), a.view(-1, 1)], 1) 

输出:

tensor([[0, 1],
        [1, 2],
        [2, 0],
        [3, 1],
        [4, 2]])

答案 1 :(得分:1)

a = torch.tensor([1,2,0,1,2])
print(a)
i = torch.arange(a.size(0))
print(i)
r = torch.stack((i, a), dim=1)
print(r)

tensor([1, 2, 0, 1, 2])
tensor([0, 1, 2, 3, 4])
tensor([[0, 1],
        [1, 2],
        [2, 0],
        [3, 1],
        [4, 2]])