I was wondering if there is any more efficient alternative for the below code, without using the "for" loop in the 4th line?
import torch
n, d = 37700, 7842
k = 4
sample = torch.cat([torch.randperm(d)[:k] for _ in range(n)]).view(n, k)
mask = torch.zeros(n, d, dtype=torch.bool)
mask.scatter_(dim=1, index=sample, value=True)
Basically, what I am trying to do is to create an n
by d
mask tensor, such that in each row exactly k
random elements are True.