【问题标题】:How to index tensor with high dimensional tensor如何用高维张量索引张量
【发布时间】:2021-12-30 22:14:10
【问题描述】:

我有两个张量 x 用于值,y 用于索引。 x.shape 和 y.shape 除了最后一个维度是相同的。 例如:

x=torch.tensor([[1, 6, 7, 5, 6],
        [8, 6, 7, 8, 4],
        [2, 8, 3, 5, 6]])
# x.shape:(3,5)
y=torch.tensor([[1, 2],
        [2, 3],
        [2, 2]])
# y.shape:(3,2)

有没有一种简单的方法可以将它切片x[y]所以结果是:

torch.tensor([6,7],[7,8],[3,3])

如果 x 和 y 是高维张量会怎样:

x.shape=(a,b,c,d)
y.shape=(a,b,c,e)
# a, b, c, d, e are positive integer

【问题讨论】:

    标签: indexing pytorch tensor


    【解决方案1】:

    这正是torch.gather 所做的。

    >> torch.gather(x, -1, y) # index along the last dimension
    tensor([[6, 7],
            [7, 8],
            [3, 3]])
    

    完全相同的命令也适用于您的高维案例。

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 2019-09-15
      • 1970-01-01
      • 2019-02-19
      • 2019-02-05
      • 2020-10-26
      • 2018-06-08
      • 2020-07-20
      • 2021-06-27
      相关资源
      最近更新 更多