所以我正在阅读 pytorch 文档,试图学习和理解一些东西(因为我是机器学习的新手),我发现了
torch.bernoulli()
并且我明白(我错过了理解它)它近似于具有1 和 0 之间的值到 1 或 0 取决于值(就像经典学校小于 0.5 = 0 ,大于或等于 0.5 = 1)
经过我自己的一些实验,是的,它按预期工作
>>>y = torch.Tensor([0.500])
>>>x
>>> 0.5000
[torch.FloatTensor of size 1]
>>> torch.bernoulli(x)
>>> 1
[torch.FloatTensor of size 1]
但是当我查看文档时发现有点奇怪
>>> a = torch.Tensor(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1]
>>> a
0.7544 0.8140 0.9842
**0.5282** 0.0595 0.6445
0.1925 0.9553 0.9732
[torch.FloatTensor of size 3x3]
>>> torch.bernoulli(a)
1 1 1
**0** 0 1
0 1 1
[torch.FloatTensor of size 3x3]
在示例中 0.5282 近似为 0 , 那是怎么发生的 ?或者这是文档中的错误,因为我尝试了它并且 0.5282 按预期近似为 1。
torch.distributions.Bernoulli()
samples 并返回二进制值(即 0 或 1)。在这里,它以概率 p 返回 1
,并以 1-p 的概率返回 0
。
下面的例子会让理解更清楚:
In [141]: m = torch.distributions.Bernoulli(torch.tensor([0.63]))
In [142]: m.sample() # 63% chance 1; 37% chance 0
Out[142]: tensor([ 0.])
In [143]: m.sample() # 63% chance 1; 37% chance 0
Out[143]: tensor([ 1.])
In [144]: m.sample() # 63% chance 1; 37% chance 0
Out[144]: tensor([ 0.])
In [145]: m.sample() # 63% chance 1; 37% chance 0
Out[145]: tensor([ 0.])
In [146]: m.sample() # 63% chance 1; 37% chance 0
Out[146]: tensor([ 1.])
In [147]: m.sample() # 63% chance 1; 37% chance 0
Out[147]: tensor([ 1.])
In [148]: m.sample() # 63% chance 1; 37% chance 0
Out[148]: tensor([ 1.])
In [149]: m.sample() # 63% chance 1; 37% chance 0
Out[149]: tensor([ 1.])
In [150]: m.sample() # 63% chance 1; 37% chance 0
Out[150]: tensor([ 1.])
In [151]: m.sample() # 63% chance 1; 37% chance 0
Out[151]: tensor([ 1.])
因此,我们采样了 10 次,其中
1
7 次,大约接近 63%。我们需要对这个有限次数进行采样,以分别获得 0
s 和 1
s 的准确百分比 37 和 63;这是因为大数定律。