Issue
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?
Solution
Following my answer here: How to randomly set a fixed number of elements in each row of a tensor in PyTorch
Say you want a matrix with dimensions n X d
where exactly 25% of the values in each row are 1 and the rest 0, desired_tensor
will have the result you want:
n = 2
d = 5
rand_mat = torch.rand(n, d)
k = round(0.25 * d) # For the general case change 0.25 to the percentage you need
k_th_quant = torch.topk(rand_mat, k, largest = False)[0][:,-1:]
bool_tensor = rand_mat <= k_th_quant
desired_tensor = torch.where(bool_tensor,torch.tensor(1),torch.tensor(0))
Answered By - Gil Pinsky
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.