【发布时间】:2021-08-09 07:23:22
【问题描述】:
我有一个 nx1 张量和一个 nxm 张量。我想使用 nxm 张量从 nx1 张量收集值。
例如
用于输入tensor([1, 2, 3, 4]) 和
索引tensor([[0, 3], [2, 1],[1, 3], [2,3]])
输出应该是
tensor([[1, 4], [3, 2], [2,4], [3,4])
索引在二维矩阵中,值将从一维列表中收集。
如何为此目的使用 torch.gather/ 或任何 Torch 张量函数? 我的以下代码给出了错误
t = torch.tensor([[1, 2, 3, 4]])
ind = torch.tensor([[0, 3], [2, 1],[1, 3], [2,3]])
torch.gather(t, 0, ind)
RuntimeError: index 2 is out of bounds for dimension 0 with size 1
编辑: 你可以做简单的索引来实现这个输出。
t[ind]
这是最好的方法吗?我假设这涉及广播输入数组。
编辑
在前向传递中使用 t[ind] 会导致错误
/pytorch/aten/src/ATen/native/cuda/IndexKernel.cu:84: operator(): block: [430,0,0], thread: [97,0,0] Assertion `index >= -sizes[i] && index < sizes[i] && "index out of bounds"` failed.
当我尝试在前向传递中打印张量时,在 t[ind] 操作之后没有显示输出。这是有道理的,因为 getitem 不是传播损失的可微操作。 因此,在 getitem 上使用聚集是一个有效的用例。
【问题讨论】:
-
您为什么要使用
torch.gather来解决您可以使用__getitem__解决的问题?由于您已使用t[ind]编辑了您的问题,因此该问题似乎没有实际意义。 -
t[ind] 在前向传递中的操作是不可微的。当我对张量使用此 getitem 功能时,我收到错误 /pytorch/aten/src/ATen/native/cuda/IndexKernel.cu:84: operator(): block: [430,0, 0],线程:[97,0,0] 断言
index >= -sizes[i] && index < sizes[i] && "index out of bounds"失败。