【问题标题】:Torch.gather from 1D array using 2D indices [closed]使用 2D 索引从 1D 数组中收集 Torch.gather [关闭]
【发布时间】: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 &gt;= -sizes[i] &amp;&amp; index &lt; sizes[i] &amp;&amp; "index out of bounds" 失败。

标签: python pytorch tensor


【解决方案1】:

如果你想使用torch.gather:

torch.gather(t.expand(4, -1), 1, ind)

【讨论】:

    猜你喜欢
    • 2014-12-03
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2019-10-20
    • 2021-04-17
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多