Pytorch: How to create a random int tensor where a certain percent are of a certain value? For example, 25% are 1s, and rest 0s

In pytorch I can create a random zero and one tensor with around %50 distribution of each

import torch 
torch.randint(low=0, high=2, size=(2, 5))

I am wondering how I can make a tensor where only 25% of the values are 1s, and the rest are zeros?

I typically use either
(torch.rand((2, 5)) < 0.25).float()
or
torch.full((2, 5), 0.25).bernoulli_()

So technically, the second saves one step (rand + compare + float vs. full + bernoulli), but I haven’t really seen this as the bottleneck in anything I do, so it entirely depends on my mood - whether the glass is half full or half rand.

Best regards

Thomas

2 Likes