Val*_*acé 7 python indexing torch pytorch tensor
我有以下火炬张量:
tensor([[-0.2, 0.3],
[-0.5, 0.1],
[-0.4, 0.2]])
Run Code Online (Sandbox Code Playgroud)
和以下 numpy 数组:(如果需要,我可以将其转换为其他内容)
[1 0 1]
Run Code Online (Sandbox Code Playgroud)
我想得到以下张量:
tensor([0.3, -0.5, 0.2])
Run Code Online (Sandbox Code Playgroud)
即我希望 numpy 数组索引张量的每个子元素。最好不使用循环。
提前致谢
您可能想要使用torch.gather- “沿着由暗淡指定的轴收集值。”
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().unsqueeze(1)
# or torch.from_numpy(idxs).long().view(-1,1)
Run Code Online (Sandbox Code Playgroud)
t.gather(1, idxs)
tensor([[ 0.3000],
[-0.5000],
[ 0.2000]])
Run Code Online (Sandbox Code Playgroud)
在这里,您的索引是 numpy 数组,因此您必须将其转换为 LongTensor。
| 归档时间: |
|
| 查看次数: |
9169 次 |
| 最近记录: |