logo

Sampling Randomly from a Given Distribution in PyTorch 📂Machine Learning

Sampling Randomly from a Given Distribution in PyTorch

Overview

Introducing how to random sample from a given distribution in PyTorch. Various distributions such as Beta, Bernoulli, Cauchy, Gamma, Pareto, and Poisson are implemented. This article explains using the uniform distribution as an example.

Code1

The code to random sample from the uniform distribution from $0$ to $5$ in PyTorch is as follows:

>>> m = torch.distributions.Uniform(0.0, 5)
>>> m.sample()
tensor(1.6371)

To sample a tensor of size $2 \times 4$,

>>> torch.distributions.Uniform(0.0, 5).sample((2,4))
tensor([[0.8507, 4.6457, 3.2871, 3.2514],
        [1.5863, 3.3836, 1.0727, 2.7350]])

This is similar to np.random.uniform(0.0, 5, (2,4)) in NumPy, and rand(Uniform(0.0, 5), 2,4) in Julia.

It’s also possible to draw from multiple ranges, but in this case, the range must be entered as a tensor. To draw one from between $[0,2]$ and another between $[5, 6]$,

>>> m = torch.distributions.Uniform(torch.tensor([0.0, 5.0]), torch.tensor([2.0, 6.0]))
>>> m.sample()
tensor([1.0503, 5.5265])

Environment

  • Colab
  • Version: Python 3.8.10, PyTorch1.13.1+cu116