Random 0-1 matrix

I want to generate a 0-1 random matrix with certain number but random indexes. However, i don’t know how to control the number of random matrix.

Could you post a small example how your matrix should look like?
You can create a tensor with random values using e.g. this code:

torch.empty(4, 4).random_(2)

@ptrblck Excuse me, now i have a tensor

x = torch.rand(1, 2, 3)

and I want to generate another random mask tensor, which has k positive elements.

The following code could solve my problem, but it is too inefficient.

n = torch.prod(torch.tensor(x.shape)).item()
index = torch.multinomial(torch.rand(n), k, replacement=False)
mask = (x * 0).flatten()
mask[index] = 1
mask = mask.reshape(*x.shape)

Have any suggestion?

Where is the bottleneck and how long does this approach take?

@ptrblck , thanks for your reply,. I found that mask = (x * 0).flatten() wasted a lot of time. Then I modified my code. Now it looks like

n = torch.prod(torch.tensor(x.shape)).item()
index = np.random.randint(0, n, k)
mask = np.zeros((n,), dtype=np.float32)
mask[index] = 1
mask = mask.reshape(*x.shape)
mask = torch.from_numpy(mask)

The improvement in speed is obvious. I am looking for a more faster implementation…