Creating a tensor mask based of rate/percentage/ratio

Good day,

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]]

Thanks in advance.

You could create the values using the defined number of samples beforehand, shuffle them, and reshape to the desired output:

ones, zeros = 30, 70
x = torch.cat((torch.zeros(zeros), torch.ones(ones)))
x = x[torch.randperm(x.size(0))]
x = x.view(10, 10)
print(x)
> tensor([[0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],
          [1., 0., 0., 0., 0., 0., 1., 1., 1., 1.],
          [1., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
          [0., 0., 1., 1., 0., 0., 1., 0., 1., 0.],
          [0., 1., 0., 0., 0., 1., 1., 0., 0., 0.],
          [0., 0., 0., 1., 1., 0., 0., 0., 1., 1.],
          [1., 0., 0., 0., 0., 0., 1., 1., 0., 0.],
          [0., 0., 0., 0., 1., 1., 0., 0., 0., 0.],
          [0., 1., 1., 0., 0., 0., 1., 0., 0., 0.],
          [1., 0., 0., 0., 0., 0., 1., 0., 1., 0.]])

It works like a charm. Thank you very much.