numpy,pytorch生成随机数,随机分布总结

在我们的平时的项目中,经常会用到生成随机数的方法。比如交叉验证中,随机采集的设置。在本文中将主要基于numpy常见的生成随机数方法和pytorch生成的随机数方法进行总结,并会分析随机种子对结果的影响,最后以五折交叉验证的随机数的划分为例,讲解随机数的使用。

文章目录


一、numpy的随机数生成

numpy.random模块填补了Python内建的random模块的不足,可以高效的生成多种概率分布下的完整样本值数组


生成指定形状的0-1之间的随机数

np.random.random()和np.random.rand()(请注意是rand()不是randn()!)
不同之处在random的输入是一个参数,得使用()将需要的参数传入,rand则直接根据需要的大小传入对应尺寸的参数,参数数无限制。

生成指定范围内的随机整数

np.random.randint()
三个参数:
参数1: 起始整数(包括在范围内)
参数2: 终止整数(不包括在范围内)
参数3: 获取采样的个数
通过这样的方式,能够生成在指定范围内随机的整数,且每个整数生成的概率相同

生成指定分布的随机整数

np.random.randn()和np.random.normal()
randn()生成服从均值为0,标准差为1的正态分布随机数
normal()默认生成标准正态分布,包含三个参数:
参数1:均值
参数2:标准差
参数3:生成的随机数的大小

生成指定区间的均匀分布

np.random.uniform()
参数1,参数2确定均匀分布的区间
参数3用来确定生成的随机数的大小

按照指定概率从指定数组中,随机抽出某个数

np.random.choice()
参数1: 表示采样的数组
参数2: 表示采样数组中每个元素被采样的概率
例如:d = np.random.choice([1,2,3,4], p = [0.1,0.2,0.3,0.4])

二、Pytorch的随机数生成方式

生成0-1之间均匀分布抽取随机数

torch.rand(*sizes)

均匀生成范围内的随机整数

torch.randint()返回在[low,high)之间均匀生成的随机整数填充的张量:
但是有个情况需要注意!
在输入第三个参数需要用括号的形式,将大小参数集合在一起,同时如果只有一个参数需要在参数后加上,号,否则程序无法正常运行
例如:
torch.randint(0,2,(1,)) 正常运行
torch.randint(0,2,(1))出错

标准正态分布

torch.randn(*sizes)

生成随机排列

torch.randperm()
参数1:参数为n,则返回整数从0到n-1的随机排列
例如:torch.randperm(4)
结果:tensor([1,3,2,0])
返回LongTensor

线性间距向量

torch.linspace(start,end,steps=)
例如:
import torch
print(torch.linspace(1,10,steps = 3))
输出:tensor([ 1.0000, 5.5000, 10.0000])

利用生成随机数划分五折交叉验证

每一个迭代周期中,先划分出测试集的索引号,然后从总的序列中,将测试集对应的索引号一个一个pop出,然后获得训练集的索引

    torch.manual_seed(0)
    save_path = 'data//predict_300//'
    file_list = os.listdir('./data/origin_300')
    order     = torch.randperm(300)
    order     = order.numpy()
    order     = np.array(order)
    file_list = np.array(file_list)

    shuffle_order1   = file_list[order.reshape(-1)]
    dice_list       = []
    train_lines     = []

    for i in range(5): 
        shuffle_order = shuffle_order1
        test_start  = np.int(300*(i/5))
        test_end    = np.int(300*((i+1)/5))

        pop_list    = torch.arange(test_start,test_end,1)
        pop_list    = pop_list.numpy().tolist()
        pop_list    = list(reversed(pop_list))

        test_lines  = shuffle_order[test_start:test_end]
        shuffle_order = shuffle_order.tolist()

        for x in pop_list:
            shuffle_order.pop(int(x))

        train_lines = shuffle_order
        test_data        = Cartilage_Dataset_origin(test_lines, imgs_transform=x_transforms,masks_transform=y_transforms)
        dice        = k_floder(train_lines,test_data)

欢迎喜欢的朋友点赞,谢谢大家,best wishes!

上一篇:pytorch实现回归模型


下一篇:HTML学习笔记(三)CSS引入方式及基本选择器、组合选择器、属性选择器