How to sample values within a range from pytorch distributions?

m = Normal(torch.tensor([0.0]), torch.tensor([1.0]))
How do I sample values only within -1 and 1.

Please help!


If you want sample in [-1, 1), you can simply called 2*torch.rand(num_samples) - 1, where num_samples is the number of samples you want

But i want the values to be sampled from the normal distribution

A normal distribution isn’t bound between -1 and +1, it’s bound between -infinity and +infinity, why do you want only the values in [-1, +1]?

1 Like

One way is to pass the values through tanh() function

vals = torch.tanh(torch.rand(num_of_samples))

Tanh function will simply kind of scale your values in a range of [-1 : 1], which satisfies your question

How do I sample values only within -1 and 1.

Yes, that would scale between -1 and +1, but the probability values associated with those points would be incorrect. You’d need to multiply those values by the determinant of the Jacobian of the transformation in order to correct the probability values as well.