Bootstrap

pytorch-生成随机数的函数(torch.rand(), torch.randn(), torch.randn_like(), ...)

'pytorch生成随机数'
import torch
import torch.nn as nn

​​​​​​​
# 1.torch.rand(shape)生成形状为shape的随机张量,其中每个元素的值服从[0, 1)的均匀分布;

x1 = torch.rand(2, 2)
print(x1)
print(x1.shape)  # torch.Size([2, 2])
"""
tensor([[0.3563, 0.9433],
        [0.7455, 0.8324]])
"""

# 2.torch.randn(shape)生成形状为shape的随机张量,其中每个元素服从标准正态分布N(0, I)

x2 = torch.randn((2, 2))
print(x2)
print(x2.shape)  # torch.Size([2, 2])
"""
tensor([[ 1.2152, -0.1251],
        [-2.2646, -0.4037]])
"""

# 计算张量x2的均值和方差
def compute_mean_var(tensor):
    mean = tensor.mean().item()
    var = tensor.std().item()

    return mean, var

compute_mean_var(x2)  # (mean, var): (-0.3945775032043457, 1.4330765008926392)

# 3. torch.randn_like(tensor)接受一个张量,返回一个与该张量shape相同的随机张量,
# 其中每个元素服从均值为0方差为1的正态分布 
# 也就是说torch.randn_like(tensor) <=> torch.randn(tensor.shape) 
x3 = torch.randn_like(x2)  # x2.shape: (2, 2) 
print(x3) 
# tensor([[-0.6400, -2.0251], 
#         [ 0.7119, 0.6263]]) 
print(x3.shape)  # torch.Size([2, 2])

# 4.torch.randint(min, max, shape)生成形状为shape的随机张量,
# 其中每一个元素都是[min, max)范围内的整数(int)。
# torch.randint 不同于 random 库中的random.randint(min, max)函数 
# random.randint(min, max)函数 -> 随机返回[min, max]之间的一个整数

x4 = torch.randint(0, 22, (2, 2))
print(x4)
print(x4.shape)  # torch.Size([2, 2])
"""
tensor([[ 0,  2],
        [21,  4]])
"""

# 5.torch.randperm(n)接受一个参数n,返回一个长度为n的一维张量
# (从0到n-1的随机整数排列,其中每个整数只出现一次)

x5 = torch.randperm(11)
print(x5)  # tensor([ 7,  8,  9,  5,  4,  3,  1,  0, 10,  2,  6])
print(x5.shape)  # torch.Size([11])

;