我想要一个具有指定百分比0s 的随机位掩码.我设计的功能是:
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, …Run Code Online (Sandbox Code Playgroud) 我想知道下面的代码是否有更有效的替代方案,而不在第四行中使用“for”循环?
import torch
n, d = 37700, 7842
k = 4
sample = torch.cat([torch.randperm(d)[:k] for _ in range(n)]).view(n, k)
mask = torch.zeros(n, d, dtype=torch.bool)
mask.scatter_(dim=1, index=sample, value=True)
Run Code Online (Sandbox Code Playgroud)
基本上,我想做的是创建一个n掩码d张量,使得每一行中的k随机元素都是 True。