Python 用数组索引火炬张量

Python 用数组索引火炬张量,python,indexing,pytorch,tensor,torch,Python,Indexing,Pytorch,Tensor,Torch,我有以下火炬张量: tensor([[-0.2, 0.3], [-0.5, 0.1], [-0.4, 0.2]]) 以及下面的numpy数组:(如果需要,我可以将其转换为其他形式) 我想得到以下张量: tensor([0.3, -0.5, 0.2]) i、 我希望numpy数组为张量的每个子元素建立索引。最好不使用回路 提前感谢只需简单地为第一个维度使用一个范围(len(index)) import torch a = torch.tensor([[-0.2, 0.

我有以下火炬张量:

tensor([[-0.2,  0.3],
    [-0.5,  0.1],
    [-0.4,  0.2]])
以及下面的numpy数组:(如果需要,我可以将其转换为其他形式)

我想得到以下张量:

tensor([0.3, -0.5, 0.2])
i、 我希望numpy数组为张量的每个子元素建立索引。最好不使用回路

提前感谢

只需简单地为第一个维度使用一个范围(len(index))

import torch

a = torch.tensor([[-0.2,  0.3],
    [-0.5,  0.1],
    [-0.4,  0.2]])

c = [1, 0, 1]


b = a[range(3),c]

print(b)
您可能希望使用-“沿dim指定的轴聚集值。”

t=torch.tensor([-0.2,0.3],
[-0.5,  0.1],
[-0.4,  0.2]])
idxs=np.array([1,0,1])
idxs=torch.from_numpy(idxs.long().unsqueze(1)
#或者torch.from_numpy(idxs.long().view(-1,1)
t.gather(1,idxs)
张量([[0.3000],
[-0.5000],
[ 0.2000]])

这里,你的索引是numpy数组,所以你必须将它转换为LongTensor。

我选择了这个答案,因为当张量较大时,它会更快
import torch

a = torch.tensor([[-0.2,  0.3],
    [-0.5,  0.1],
    [-0.4,  0.2]])

c = [1, 0, 1]


b = a[range(3),c]

print(b)