Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - How to get a uniform distribution in a range [r1,r2] in PyTorch?

I want to get a 2-D torch.Tensor with size [a,b] filled with values from a uniform distribution (in range [r1,r2]) in PyTorch.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If U is a random variable uniformly distributed on [0, 1], then (r1 - r2) * U + r2 is uniformly distributed on [r1, r2].

Thus, you just need:

(r1 - r2) * torch.rand(a, b) + r2

Alternatively, you can simply use:

torch.FloatTensor(a, b).uniform_(r1, r2)

To fully explain this formulation, let's look at some concrete numbers:

r1 = 2 # Create uniform random numbers in half-open interval [2.0, 5.0)
r2 = 5

a = 1  # Create tensor shape 1 x 7
b = 7

We can break down the expression (r1 - r2) * torch.rand(a, b) + r2 as follows:

  1. torch.rand(a, b) produces an a x b (1x7) tensor with numbers uniformly distributed in the range [0.0, 1.0).
x = torch.rand(a, b)
print(x)
# tensor([[0.5671, 0.9814, 0.8324, 0.0241, 0.2072, 0.6192, 0.4704]])
  1. (r1 - r2) * torch.rand(a, b) produces numbers distributed in the uniform range [0.0, -3.0)
print((r1 - r2) * x)
tensor([[-1.7014, -2.9441, -2.4972, -0.0722, -0.6216, -1.8577, -1.4112]])
  1. (r1 - r2) * torch.rand(a, b) + r2 produces numbers in the uniform range [5.0, 2.0)
print((r1 - r2) * x + r2)
tensor([[3.2986, 2.0559, 2.5028, 4.9278, 4.3784, 3.1423, 3.5888]])

Now, let's break down the answer suggested by @Jonasson: (r2 - r1) * torch.rand(a, b) + r1

  1. Again, torch.rand(a, b) produces (1x7) numbers uniformly distributed in the range [0.0, 1.0).
x = torch.rand(a, b)
print(x)
# tensor([[0.5671, 0.9814, 0.8324, 0.0241, 0.2072, 0.6192, 0.4704]])
  1. (r2 - r1) * torch.rand(a, b) produces numbers uniformly distributed in the range [0.0, 3.0).
print((r2 - r1) * x)
# tensor([[1.7014, 2.9441, 2.4972, 0.0722, 0.6216, 1.8577, 1.4112]])
  1. (r2 - r1) * torch.rand(a, b) + r1 produces numbers uniformly distributed in the range [2.0, 5.0)
print((r2 - r1) * x + r1)
tensor([[3.7014, 4.9441, 4.4972, 2.0722, 2.6216, 3.8577, 3.4112]])

In summary, (r1 - r2) * torch.rand(a, b) + r2 produces numbers in the range [r2, r1), while (r2 - r1) * torch.rand(a, b) + r1 produces numbers in the range [r1, r2).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...