>>> import torch
>>> A = torch.tensor([[[ 1., 2., 3.],
... [ 5., 6., 7.]],
...
... [[ 9., 10., 11.],
... [13., 14., 15.]]])
>>> B = torch.tensor([[0, 2],
... [1, 0]])
>>> A.shape
torch.Size([2, 2, 3])
>>> B.shape
torch.Size([2, 2])
>>> C = torch.zeros_like(B)
>>> for i in range(B.shape[0]):
... for j in range(B.shape[1]):
... C[i,j] = A[i,j,B[i,j]]
...
>>> C
tensor([[ 1, 7],
[10, 13]])
>>> torch.gather(A, -1, B.unsqueeze(-1))
tensor([[[ 1.],
[ 7.]],
[[10.],
[13.]]])
>>> torch.gather(A, -1, B.unsqueeze(-1)).shape
torch.Size([2, 2, 1])
>>> torch.gather(A, -1, B.unsqueeze(-1)).squeeze(-1)
tensor([[ 1., 7.],
[10., 13.]])
您好,您可以使用torch.gather(A, -1, B.unsqueeze(-1)).squeeze(-1)。
A 和 B.unsqueeze(-1) 之间的第一个 -1 表示您要沿其选取元素的维度。
B.unsqueeze(-1) 中的第二个 -1 是向 B 添加一个暗度,以使两个张量具有相同的暗度,否则您将得到 RuntimeError: Index tensor must have the same number of dimensions as input tensor。
最后一个-1 是将结果从torch.Size([2, 2, 1]) 重塑为torch.Size([2, 2])