(1)torch.rand(sizes, out=None)
产生一个服从均匀分布的张量,张量内的数据包含从区间[0,1)的随机数。参数size是一个整数序列,用于定义张量大小。
a = torch.rand(20,1)
print(a)
b = torch.rand((2,2))
print(b)
tensor([[0.4332],
[0.0209],
[0.0262],
[0.7276],
[0.2274],
[0.4040],
[0.4350],
[0.0849],
[0.0711],
[0.1297],
[0.0102],
[0.3941],
[0.4395],
[0.1449],
[0.0768],
[0.5904],
[0.4775],
[0.7641],
[0.1154],
[0.8411]])
tensor([[0.3198, 0.7445],
[0.2221, 0.1359]])
(2)torch.randn(sizes, out=None)
产生一个服从标准整正态分布的张量,张量内数据均值为0,方差为1,即为高斯白噪声。sizes作用同上。
a = torch.randn(20,1)
print(a)
b = torch.randn((2,2))
print(b)
tensor([[-0.5412],
[ 1.1345],
[-0.6147],
[-0.7924],
[-0.6533],
[-0.9084],
[-0.8547],
[ 0.4920],
[ 0.7865],
[ 0.3324],
[ 0.4163],
[ 1.1134],
[-0.7867],
[ 0.2625],
[-1.1835],
[-0.4285],
[-0.5762],
[ 2.1192],
[ 0.2680],
[ 1.8534]])
tensor([[ 0.1031, 0.4589],
[-1.1752, 1.1279]])
(3)torch.normal(means, std, out=None)
产生一个服从离散正态分布的张量随机数,可以指定均值和标准差。
其中,标准差std是一个张量包含每个输出元素相关的正态分布标准差。
注:这里用到了Broadcast自动扩展
'''
通过torch.normal创建正态分布张量
'''
# mean:张量 std: 张量
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std)
print("mean:{}\nstd:{}".format(mean, std))
print(t_normal)
print("*"*5)
# mean:标量 std: 标量
t_normal = torch.normal(0., 1., size=(4,)) # size=(4,)设置张量的大小
print(t_normal)
print("*"*5)
# mean:张量 std: 标量
mean = torch.arange(1, 5, dtype=torch.float)
std = 1
t_normal = torch.normal(mean, std)
print("mean:{}\nstd:{}".format(mean, std))
print(t_normal)
print("*"*5)
(4)torch.randperm(n, out=None, requires_grad=True)
返回从0到n-1的整数的随机排列数
a = torch.randperm(6)
print(a)
tensor([2, 0, 4, 3, 1, 5])
(5)torch.randint(low=0, high, size, out=None, requires_grad=False)
返回一个张量,该张量填充了在[low,high)均匀生成的随机整数。
张量的形状由可变的参数大小定义。
a = torch.randint(1,10,(3,3))
print(a)
tensor([[2, 7, 4],
[5, 4, 1],
[2, 4, 6]])
参考:https://blog.youkuaiyun.com/weixin_44739213/article/details/108617473
834

被折叠的 条评论
为什么被折叠?



