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.