【问题标题】:pytorch best way to call unique_consecutive() on certain dimension of a tensor?pytorch 在张量的特定维度上调用 unique_consecutive() 的最佳方法?
【发布时间】:2021-05-25 06:57:00
【问题描述】:

在张量的特定维度上调用 unique_consecutive() 并用指定​​值填充左侧的最佳方法是什么? 为简单起见,我们可以使用 2D 张量作为示例:

input = tensor([[3, 3, 5, 5, 5],
                [3, 3, 2, 2, 3]])

如果指定填充值-1,我希望得到的是:

output = tensor([[3, 5, -1, -1, -1],
                 [3, 2, 3, -1, -1]])

另外,为了节省内存,如果可能的话,我宁愿在原地这样做。 谢谢!

【问题讨论】:

  • torch.unique_consecutive(input, dim = 1) 将产生一个具有以下内容的张量:[[3,5,5], [3,2,3]]。您是否希望删除最后一个 5,或者这是您问题中的拼写错误?
  • 不,[[3,5,5], [3,2,3]] 不是预期结果,预期结果如上所示:在每一行上,相同的连续元素折叠成一个,例如 [3, 3, 5, 5, 5 ] 变为 [3, 5],然后用 -1 填充变为 [3, 5, -1, -1, -1]

标签: python pytorch


【解决方案1】:

从 PyTorch 论坛 https://discuss.pytorch.org/t/best-way-to-run-unique-consecutive-on-certain-dimension/112662 找到了一个不错的解决方案,在此引用以供快速参考。


    x = tensor([[3, 3, 5, 5, 5],
                [3, 3, 2, 2, 3]])
    unique_x, indices = torch.unique_consecutive(x, return_inverse=True)
    indices -= indices.min(dim=1, keepdims=True)[0]
    result = -torch.ones_like(x)
    result = result.scatter_(1, indices, x)

【讨论】:

    猜你喜欢
    • 2021-06-10
    • 2020-01-13
    • 2022-07-26
    • 2021-10-23
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多