how can i create a random int tensor where a certain percent is of a certain value? for example 25 are 1s and rest 0s?

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top