首页 > 解决方案 > 将 Tenor 的索引和值组合成一个新的张量

问题描述

我有一个像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

标签: pythonpytorch

解决方案


一种方法是:

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]])

推荐阅读