torch.rand (randn, random以及normal)对比

(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值