Torch equivalent of numpy.random.choice?

Hi !
To clear things up

If you want to do the equivalent of numpy.random.choice:

a = np.array([1, 2, 3, 4])
p = np.array([0.1, 0.1, 0.1, 0.7])
n = 2
replace = True

b = np.random.choice(a, p=p, size=n, replace=replace)

In pytorch you can use torch.multinomial :

a = torch.tensor([1, 2, 3, 4])
p = torch.tensor([0.1, 0.1, 0.1, 0.7])
n = 2
replace = True

idx = p.multinomial(num_samples=n, replacement=replace)
b = a[idx]

Careful, np.random.choice defaults to replace=True
But torch.multinomial defaults to replacement=False

14 Likes