Pytorch: Creating a tensor mask based of rate/percentage/ratio
How can I generate a mask tensor that has a specific ratio of 0 and 1? For example 70:30 of 0s and 1s in a 5 by 10 tensor will generate:
[[0,0,0,0,0,0,0,0,1,0],
[1,1,1,0,0,0,1,1,0,0],
[0,0,1,0,0,1,1,0,1,0],
[0,1,0,1,0,1,1,0,0,0],
[0,0,0,1,0,0,0,0,0,0]]


You can approximate the ratio using random sampling:
import torch

mask = torch.rand(5, 10)  # uniformly distributed between 0 and 1
mask = mask &lt; 0.3   # 30% pixels &quot;on&quot;

On average, mask will have the right amount of &quot;on&quot; pixels.

Alternatively, if you must have exactly 30% of &quot;on&quot; pixels, you can use torch.randperm to randomly permute a mask with exactly the number of &quot;on&quot; pixels:
raw = torch.zeros((5*10,))
raw[:int(0.3 * 5 * 10)] = 1.  # set EXACTLY 30% of the pixels in the mask
ridx = torch.randperm(5*10)   # a random permutation of the entries
mask = torch.reshape(raw[ridx], (5, 10))

