文章目录
1. torch.bernouli
torch.bernoulli(input, *, generator=None, out=None) → Tensor
input : 表示的是一个概率值组成的矩阵
output:表示的是一个跟input同等大小的矩阵,输出矩阵是来自伯努利分布
从伯努利分布中绘制二进制随机数(0或1)。
- 举例:
假设我们input矩阵如下:
input_rand=tensor([[0.5564, 0.0900, 0.8406, 0.7404],
[0.9572, 0.7736, 0.4841, 0.6658],
[0.7223, 0.0511, 0.8271, 0.8581]])
[0.5564,0.0900,0.8406,0.7404]表示:
0.5565
概
率
抽
到
1
0.5565概率抽到\qquad1
0.5565概率抽到1
0.0900
概
率
抽
到
1
0.0900概率抽到\qquad1
0.0900概率抽到1
0.8406
概
率
抽
到
1
0.8406概率抽到\qquad1
0.8406概率抽到1
0.7404
概
率
抽
到
1
0.7404概率抽到\qquad1
0.7404概率抽到1
- 测试代码如下:
import torch
from torch import nn
# draw the sample from [0,1),shape is (3,4);
# input_rand is probability to get the value 1
input_rand = torch.rand((3,4))
# draw the sample from bernoulli distribution;the probability is input_rand
output_rand = torch.bernoulli(input_rand)
# get a tensor filled all the value ones
input_ones = torch.ones((3,4))
# the probability is 1 ; so the output is all 1
output_ones = torch.bernoulli(input_ones)
# get a tensor filled all the value zeros
input_zeros = torch.zeros((3,4))
# the probability is 0 ; so the output is all 0
output_zeros = torch.bernoulli(input_zeros)
print(f"input_rand={input_rand}")
print(f"output_rand={output_rand}")
print("*"*50)
print(f"input_zeros={input_zeros}")
print(f"output_zeros={output_zeros}")
print("*"*50)
print(f"input_ones={input_ones}")
print(f"output_ones={output_ones}")
input_rand=tensor([[0.3222, 0.4630, 0.8227, 0.6225],
[0.3587, 0.6961, 0.6875, 0.9904],
[0.4817, 0.5500, 0.9436, 0.0660]])
output_rand=tensor([[0., 0., 1., 1.],
[0., 1., 0., 1.],
[1., 1., 1., 0.]])
**************************************************
input_zeros=tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
output_zeros=tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
**************************************************
input_ones=tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
output_ones=tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])