python – 有没有一种在Pytorch中创建随机位掩码的有效方法?

我想要一个随机位掩码,其中指定百分比为0.我设计的功能是:

def create_mask(shape, rate):
    """
    The idea is, you take a random permutations of numbers. You then mod then
    mod it by the [number of entries in the bitmask] / [percent of 0s you
    want]. The number of zeros will be exactly the rate of zeros need. You
    can clamp the values for a bitmask.
    """
    mask = torch.randperm(reduce(operator.mul, shape, 1)).float().cuda()
    # Mod it by the percent to get an even dist of 0s.
    mask = torch.fmod(mask, reduce(operator.mul, shape, 1) / rate)
    # Anything not zero should be put to 1
    mask = torch.clamp(mask, 0, 1)
    return mask.view(shape)

为了显示:

>>> x = create_mask((10, 10), 10)
>>> x

    1     1     1     1     1     1     1     1     1     1
    1     1     1     1     1     1     0     1     1     1
    0     1     1     1     1     0     1     1     1     1
    0     1     1     1     1     1     1     1     1     1
    1     1     1     1     1     1     1     1     1     0
    1     1     1     1     1     1     1     1     1     1
    1     1     1     0     1     1     1     0     1     1
    0     1     1     1     1     1     1     1     1     1
    1     1     1     0     1     1     0     1     1     1
    1     1     1     1     1     1     1     1     1     1
[torch.cuda.FloatTensor of size 10x10 (GPU 0)]

我对这种方法的主要问题是需要率来划分形状.我想要一个接受任意小数的函数,并在位掩码中给出大约百分比0.此外,我试图找到一种相对有效的方法.因此,我宁愿不将numpy数组从CPU移动到GPU.是否有一种有效的方法可以实现小数?

最佳答案 对于遇到这种情况的任何人来说,这将直接在GPU上创建一个大约80%零点的位掩码. (PyTorch 0.3)

torch.cuda.FloatTensor(10, 10).uniform_() > 0.8
点赞