【问题标题】:How can I zero out duplicate values in each row of a PyTorch tensor?如何将 PyTorch 张量的每一行中的重复值清零?
【发布时间】:2020-09-29 16:21:08
【问题描述】:

我想写一个函数来实现this question中描述的行为。

也就是说,我想在 PyTorch 中将矩阵的每一行中的重复值清零。例如,给定一个矩阵

torch.Tensor(([1, 2, 3, 4, 3, 3, 4],
              [1, 6, 3, 5, 3, 5, 4]])

我想得到

torch.Tensor(([1, 2, 3, 4, 0, 0, 0],
              [1, 6, 3, 5, 0, 0, 4]])

torch.Tensor(([1, 2, 3, 4, 0, 0, 0],
              [1, 6, 3, 5, 4, 0, 0]])

根据链接的问题,仅torch.unique() 是不够的。我想知道如何在没有循环的情况下实现这个功能。

【问题讨论】:

    标签: python numpy pytorch torch


    【解决方案1】:
    x = torch.tensor([
        [1, 2, 3, 4, 3, 3, 4],
        [1, 6, 3, 5, 3, 5, 4]
    ], dtype=torch.long)
    
    # sorting the rows so that duplicate values appear together
    # e.g., first row: [1, 2, 3, 3, 3, 4, 4]
    y, indices = x.sort(dim=-1)
    
    # subtracting, so duplicate values will become 0
    # e.g., first row: [1, 2, 3, 0, 0, 4, 0]
    y[:, 1:] *= ((y[:, 1:] - y[:, :-1]) !=0).long()
    
    # retrieving the original indices of elements
    indices = indices.sort(dim=-1)[1]
    
    # re-organizing the rows following original order
    # e.g., first row: [1, 2, 3, 4, 0, 0, 0]
    result = torch.gather(y, 1, indices)
    
    print(result) # => output
    

    输出

    tensor([[1, 2, 3, 4, 0, 0, 0],
            [1, 6, 3, 5, 0, 0, 4]])
    

    【讨论】:

    • @MustafaAydın 添加。
    • 我认为你可以使用tensor.diff() 方法来处理减法部分
    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2017-12-13
    相关资源
    最近更新 更多