简体   繁体   English

如何在 PyTorch 中获得 [r1,r2] 范围内的均匀分布?

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

我想在 PyTorch 中获得一个大小为[a,b]的二维torch.Tensor ,其中填充了来自均匀分布(在[r1,r2]范围内)的值。

If U is a random variable uniformly distributed on [0, 1], then (r1 - r2) * U + r2 is uniformly distributed on [r1, r2].如果U是均匀分布在 [0, 1] 上的随机变量,则(r1 - r2) * U + r2均匀分布在 [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:我们可以将表达式(r1 - r2) * torch.rand(a, b) + r2如下:

  1. torch.rand(a, b) produces an axb (1x7) tensor with numbers uniformly distributed in the range [0.0, 1.0). torch.rand(a, b)产生一个axb (1x7) 张量,其数字均匀分布在 [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) (r1 - r2) * torch.rand(a, b)产生分布在均匀范围 [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) (r1 - r2) * torch.rand(a, b) + r2产生统一范围内的数字 [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现在,让我们分解@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).同样, torch.rand(a, b)产生 (1x7) 数字,均匀分布在 [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). (r2 - r1) * torch.rand(a, b)产生在 [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) (r2 - r1) * torch.rand(a, b) + r1产生在 [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).总之(r1 - r2) * torch.rand(a, b) + r2产生范围 [r2, r1) 中的数字,而(r2 - r1) * torch.rand(a, b) + r1产生范围内的数字范围 [r1, r2)。

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

Utilize the torch.distributions package to generate samples from different distributions.利用torch.distributions包从不同的分布中生成样本。

For example to sample a 2d PyTorch tensor of size [a,b] from a uniform distribution of range(low, high) try the following sample code例如,要从range(low, high)的均匀分布中采样大小为[a,b]的 2d PyTorch 张量,请尝试以下示例代码

import torch
a,b = 2,3   #dimension of the pytorch tensor to be generated
low,high = 0,1 #range of uniform distribution

x = torch.distributions.uniform.Uniform(low,high).sample([a,b]) 

To get a uniform random distribution, you can use要获得均匀的随机分布,您可以使用

torch.distributions.uniform.Uniform()

example,例子,

import torch
from torch.distributions import uniform

distribution = uniform.Uniform(torch.Tensor([0.0]),torch.Tensor([5.0]))
distribution.sample(torch.Size([2,3])

This will give the output, tensor of size [2, 3].这将给出输出,大小为 [2, 3] 的张量。

Please Can you try something like:请你可以尝试类似的东西:

import torch as pt
pt.empty(2,3).uniform_(5,10).type(pt.FloatTensor)

This answer uses NumPy to first produce a random matrix and then converts the matrix to a PyTorch tensor.这个答案使用 NumPy 首先生成一个随机矩阵,然后将矩阵转换为 PyTorch 张量。 I find the NumPy API to be easier to understand.我发现 NumPy API 更容易理解。

import numpy as np

torch.from_numpy(np.random.uniform(low=r1, high=r2, size=(a, b)))

PyTorch has a number of distributions built in. You can build a tensor of the desired shape with elements drawn from a uniform distribution like so: PyTorch 内置了许多分布。您可以使用从均匀分布中提取的元素构建所需shape的张量,如下所示:

from torch.distributions.uniform import Uniform

shape = 3,4
r1, r2 = 0,1

x = Uniform(r1, r2).sample(shape) 

For those who are frustratingly bashing their keyboard yelling "why isn't this working." 对于那些沮丧地抨击他们的键盘的人大喊“为什么这不起作用”。 as I was... note the underscore behind the word uniform. 就像我一样......注意制服这个词背后的下划线。

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

See this for all distributions: https://pytorch.org/docs/stable/distributions.html#torch.distributions.uniform.Uniform查看所有发行版: https ://pytorch.org/docs/stable/distributions.html#torch.distributions.uniform.Uniform

This is the way I found works:这是我发现工作的方式:

# generating uniform variables

import numpy as np

num_samples = 3
Din = 1
lb, ub = -1, 1

xn = np.random.uniform(low=lb, high=ub, size=(num_samples,Din))
print(xn)

import torch

sampler = torch.distributions.Uniform(low=lb, high=ub)
r = sampler.sample((num_samples,Din))

print(r)

r2 = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples,Din))

print(r2)

# process input
f = nn.Sequential(OrderedDict([
    ('f1', nn.Linear(Din,Dout)),
    ('out', nn.SELU())
]))
Y = f(r2)
print(Y)

but I have to admit I don't know what the point of generating sampler is and why not just call it directly as I do in the one liner (last line of code).但我不得不承认我不知道生成采样器的意义何在,为什么不直接调用它,就像我在一个衬里(最后一行代码)中所做的那样。

Comments:注释:


Reference:参考:

Pytorch (now?) has a random integer function that allows: Pytorch(现在?)有一个随机整数函数,它允许:

torch.randint(low=r1, high=r2, size=(1,), **kwargs)

and returns uniformly sampled random integers of shape size in range [r1, r2).并返回 [r1, r2) 范围内形状大小的均匀采样的随机整数。

https://pytorch.org/docs/stable/generated/torch.randint.htmlhttps://pytorch.org/docs/stable/generated/torch.randint.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 numpy:如何从文件加载有界(R1 C1到R2 C2)矩阵 - numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file 如何在 nn.LSTM 中取得 R2 分数 pytorch - How to make R2 score in nn.LSTM pytorch 编写代码在 sklearn 中生成两个圆,半径为 r1=2 和 r2=5,圆心位于 (5,3) - Writing code to generate two circles in sklearn with radius r1=2 and r2=5 with centres located at (5,3) 从具有半径R1和R2的环的图像中提取数据点 - Extract data points from image within an annulus with radius R1 and R2 将彩色图像转换为单行numpy数组(r1,g1,b1; r2,g2,b2;…) - Convert a color image into single-row numpy array (r1, g1, b1; r2, g2, b2; …) Pandas 数据框:基于某个当前行 R1,找到另一行 R2,其之间的所有行都匹配一个条件 - Pandas dataframe: Based on some current row R1, find another row R2 for which all rows in between match a condition 范围内的非均匀分布 - non-uniform distribution in a range 如何从 sklearn GridSearchCV 获取 MSE 和 R2? - How to get both MSE and R2 from a sklearn GridSearchCV? 如何使用 Python 中的离散均匀分布将 0-1 范围内的数字转换为 1-52 范围内的数字? - How can I transform numbers in a range of 0-1 to a 1-52 range using Discrete Uniform Distribution in Python? 如何计算Scikit中的R2值? - How is the R2 value in Scikit learn calculated?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM