【问题标题】:Fill tensor with another tensor where mask is true用掩码为真的另一个张量填充张量
【发布时间】:2021-03-18 21:16:50
【问题描述】:

我需要以一定的概率将张量new的元素插入到张量old中,为了简单起见,假设为0.8。 基本上这就是 masked_fill 会做的事情,但它只适用于一维张量。 其实我在做

    prob = torch.rand(trgs.shape, dtype=torch.float32).to(trgs.device)
    mask = prob < 0.8

    dim1, dim2, dim3, dim4 = new.shape
    for a in range(dim1):
        for b in range(dim2):
            for c in range(dim3):
                for d in range(dim4):
                    old[a][b][c][d] = old[a][b][c][d] if mask[a][b][c][d] else new[a][b][c][d]

这太糟糕了。我想要类似的东西

    prob = torch.rand(trgs.shape, dtype=torch.float32).to(trgs.device)
    mask = prob < 0.8

    old = trgs.multidimensional_masked_fill(mask, new)

【问题讨论】:

    标签: python pytorch tensor


    【解决方案1】:

    我不确定您的某些对象是什么,但这应该可以让您在短时间内完成所需的操作:

    old 是您现有的数据。

    mask 是您以概率 p 生成的掩码

    new 是包含您要插入的元素的新张量。

    # torch.where
    result = old.where(mask, new)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-17
      • 2016-03-21
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 2018-03-24
      • 2023-03-29
      • 2016-06-20
      相关资源
      最近更新 更多