Index pytorch 4d tensor by values in 2d tensor

不羁的心 提交于 2021-02-05 06:43:47

问题


I have two pytorch tensors:

  • X with shape (A, B, C, D)
  • I with shape (A, B)

Values in I are integers in range [0, C).


What is the most efficient way to get tensor Y with shape (A, B, D), such that:

Y[i][j][k] = X[i][j][ I[i][j] ][k]

回答1:


You probably want to use torch.gather for the indexing and expand to adjust I to the required size:

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()

testing the code:

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)


来源:https://stackoverflow.com/questions/53471716/index-pytorch-4d-tensor-by-values-in-2d-tensor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!