如何根据pytorch中的另一个张量选择索引

spa*_*del 9 python indices pytorch

这个任务看起来很简单,但我不知道该怎么做。

所以我有两个张量:

  • indices形状为 的索引张量(2, 5, 2),其中最后一个维度对应于 x 和 y 维度中的索引
  • value形状为“值张量” (2, 5, 2, 16, 16),我希望使用 x 和 y 索引选择最后两个维度

更具体地说,索引在 0 到 15 之间,我想得到一个输出:

out = value[:, :, :, x_indices, y_indices]
Run Code Online (Sandbox Code Playgroud)

因此,输出的形状应为(2, 5, 2)。有人可以帮我吗?多谢!

编辑:

我尝试了收集的建议,但不幸的是它似乎不起作用(我改变了尺寸,但这并不重要):

首先我生成一个坐标网格:

y_t = torch.linspace(-1., 1., 16, device='cpu').reshape(16, 1).repeat(1, 16).unsqueeze(-1)
x_t = torch.linspace(-1., 1., 16, device='cpu').reshape(1, 16).repeat(16, 1).unsqueeze(-1)
grid = torch.cat((y_t, x_t), dim=-1).permute(2, 0, 1).unsqueeze(0)
grid = grid.unsqueeze(1).repeat(1, 3, 1, 1, 1)
Run Code Online (Sandbox Code Playgroud)

在下一步中,我将创建一些索引。在这种情况下,我总是采用索引 1:

indices = torch.ones([1, 3, 2], dtype=torch.int64)
Run Code Online (Sandbox Code Playgroud)

接下来我就用你的方法:

indices = indices.unsqueeze(-1).unsqueeze(-1)
new_coords = torch.gather(grid, -1, indices).squeeze(-1).squeeze(-1)
Run Code Online (Sandbox Code Playgroud)

最后,我手动为 x 和 y 坐标选择索引 1:

new_coords_manual = grid[:, :, :, 1, 1]
Run Code Online (Sandbox Code Playgroud)

这将输出以下新坐标:

new_coords
tensor([[[-1.0000, -0.8667],
         [-1.0000, -0.8667],
         [-1.0000, -0.8667]]])

new_coords_manual
tensor([[[-0.8667, -0.8667],
         [-0.8667, -0.8667],
         [-0.8667, -0.8667]]])
Run Code Online (Sandbox Code Playgroud)

如您所见,它仅适用于一维。您知道如何解决这个问题吗?

Iva*_*van 3

您可以做的是将前三个轴压平并应用torch.gather

>>> grid.flatten(start_dim=0, end_dim=2).shape
torch.Size([6, 16, 16])

>>> torch.gather(grid.flatten(0, 2), axis=1, indices)
tensor([[[-0.8667, -0.8667],
         [-0.8667, -0.8667],
         [-0.8667, -0.8667]]])
Run Code Online (Sandbox Code Playgroud)

正如文档页面上所解释的,这将执行:

out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1