我有两个火炬张量:
X
,形状为(A, B, C, D)
I
,形状为(A, B)
I
中的值是[0, C)
范围内的整数。
获取具有形状Y
的张量(A, B, D)
的最有效方法是什么,
Y[i][j][k] = X[i][j][ I[i][j] ][k]
答案 0 :(得分:1)
您可能希望使用torch.gather
进行索引编制,并使用expand
将I
调整为所需大小:
eI = I[..., None, None].expand(-1, -1, 1, X.size(3)) # make eI the same for the last dimension
Y = torch.gather(X, dim=2, index=eI).squeeze()
测试代码:
A = 3
B = 4
C = 5
D = 7
X = torch.rand(A, B, C, D)
I = torch.randint(0, C, (A, B), dtype=torch.long)
eI = I[..., None, None].expand(-1, -1, 1, X.size(3))
Y = torch.gather(X, dim=2, index=eI).squeeze()
# manually gather
refY = torch.empty(A, B, D)
for i in range(A):
for j in range(B):
refY[i, j, :] = X[i, j, I[i,j], :]
(refY == Y).all()
# Out[]: tensor(1, dtype=torch.uint8)