原标题:Numpy入门教程:07. 随机抽样
背景
什么是 NumPy 呢?
NumPy 这个词来源于两个单词 -- Numerical 和 Python 。其是一个功能强大的 Python 库,可以帮助程序员轻松地进行数值计算,通常应用于以下场景:
执行各种数学任务,如:数值积分、微分、内插、外推等。因此,当涉及到数学任务时,它形成了一种基于 Python 的 MATLAB 的快速替代。
计算机中的图像表示为多维数字数组。NumPy 提供了一些优秀的库函数来快速处理图像。例如,镜像图像、按特定角度旋转图像等。
在编写机器学习算法时,需要对矩阵进行各种数值计算。如:矩阵乘法、求逆、换位、加法等。NumPy 数组用于存储训练数据和机器学习模型的参数。
随机抽样
numpy.random 模块对 Python 内置的 random 进行了补充,增加了一些用于高效生成多种概率分布的样本值的函数,如正态分布、泊松分布等。
numpy.random.seed(seed=None) Seed the generator.
seed 用于指定随机数生成时所用算法开始的整数值,如果使用相同的 seed 值,则每次生成的随机数都相同,如果不设置这个值,则系统根据时间来自己选择这个值,此时每次生成的随机数因时间差异而不同。
在对数据进行预处理时,经常加入新的操作或改变处理策略,此时如果伴随着随机操作,最好还是指定唯一的随机种子,避免由于随机的差异对结果产生影响。
离散型随机变量
二项分布
numpy.random.binomial(n, p, size=None) Draw samples from a binomial distribution.
表示对一个二项分布进行采样, size 表示采样的次数, n 表示做了 n 重伯努利试验, p 表示成功的概率,函数的返回值表示 n 中成功的次数。
【例】野外正在进行9(n=9)口石油勘探井的发掘工作,每一口井能够开发出油的概率是0.1(p=0.1)。请问,最终所有的勘探井都勘探失败的概率?
【例】模拟投硬币,投2次,请问两次都为正面的概率?
泊松分布
numpy.random.poisson(lam=1.0, size=None) Draw samples from a Poisson distribution.
表示对一个泊松分布进行采样, size 表示采样的次数, lam 表示一个单位内发生事件的平均值,函数的返回值表示一个单位内事件发生的次数。
【例】假定某航空公司预定票处平均每小时接到42次订票电话,那么10分钟内恰好接到6次电话的概率是多少?
超几何分布
numpy.random.hypergeometric(ngood, nbad, nsample, size=None) Draw samples from a Hypergeometric distribution.
表示对一个超几何分布进行采样, size 表示采样的次数, ngood 表示总体中具有成功标志的元素个数, nbad 表示总体中不具有成功标志的元素个数, ngood+nbad 表示总体样本容量, nsample 表示抽取元素的次数(小于或等于总体样本容量),函数的返回值表示抽取 nsample 个元素中具有成功标识的元素个数。
【例】一共20只动物里有7只是狗,抽取12只有3只狗的概率(无放回抽样)。
连续型随机变量
均匀分布
numpy.random.uniform(low=0.0, high=1.0, size=None) Draw samples from a uniform distribution.
Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform .
【例】在low到high范围内,创建大小为size的均匀分布的随机数。
作为 uniform 的特列,可以得到 [0,1) 之间的均匀分布的随机数。
numpy.random.rand(d0, d1, …, dn) Random values in a given shape.
Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1) .
【例】根据指定大小产生[0,1)之间均匀分布的随机数。
importnumpy asnp
np.random.seed( 20200614)
print(np.random.rand)
# 0.7594819171852776
print(np.random.rand( 5))
# [0.75165827 0.16552651 0.0538581 0.46671446 0.89076925]
print(np.random.rand( 4, 3))
# [[0.10073292 0.14624784 0.40273923]
# [0.21844459 0.22226682 0.37246217]
# [0.50334257 0.01714939 0.47780388]
# [0.08755349 0.86500477 0.70566398]]
np.random.seed( 20200614)
print(np.random.uniform) # 0.7594819171852776
print(np.random.uniform(size= 5))
# [0.75165827 0.16552651 0.0538581 0.46671446 0.89076925]
print(np.random.uniform(size=( 4, 3)))
# [[0.10073292 0.14624784 0.40273923]
# [0.21844459 0.22226682 0.37246217]
# [0.50334257 0.01714939 0.47780388]
# [0.08755349 0.86500477 0.70566398]]
作为 uniform 的另一特例,可以得到 [low,high) 之间均匀分布的随机整数。
numpy.random.randint(low, high=None, size=None, dtype='l') Return random integers from low (inclusive) to high (exclusive).
Return random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low).
【例】若 high 不为 None 时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数。
importnumpy asnp
np.random.seed( 20200614)
x = np.random.randint( 2, size= 10)
print(x)
# [0 0 0 1 0 1 0 0 0 0]
x = np.random.randint( 1, size= 10)
print(x)
# [0 0 0 0 0 0 0 0 0 0]
x = np.random.randint( 5, size=( 2, 4))
print(x)
# [[3 3 0 1]
# [1 1 0 1]]
x = np.random.randint( 1, 10, [ 3, 4])
print(x)
# [[2 1 7 7]
# [7 2 4 6]
# [8 7 2 8]]
正态分布
numpy.random.randn(d0, d1, …, dn) Return a sample (or samples) from the "standard normal" distribution.
【例】根据指定大小产生满足标准正态分布的数组(均值为0,标准差为1)。
还可以指定分布以及所需参数来进行随机,例如高斯分布中的mu和sigma。
numpy.random.normal(loc=0.0, scale=1.0, size=None) Draw random samples from a normal (Gaussian) distribution.
normal 为创建均值为 loc(mu),标准差为 scale(sigma),大小为 size 的数组。
sigma * np.random.randn(...) + mu
【例】
指数分布
numpy.random.exponential(scale=1.0, size=None) Draw samples from an exponential distribution.
【例】 scale = 1/lambda
其它随机函数
numpy.random.choice(a, size=None, replace=True, p=None) Generates a random sample from a given 1-D array.
从序列中获取元素,若 a 为整数,元素取值从 np.range(a) 中随机获取;若 a 为数组,取值从 a 数组元素中随机获取。该函数还可以控制生成数组中的元素是否重复 replace ,以及选取元素的概率 p 。
【例】
importnumpy asnp
np.random.seed( 20200614)
x = np.random.choice( 10, 3)
print(x) # [2 0 1]
x = np.random.choice( 10, 3, p=[ 0.05, 0, 0.05, 0.9, 0, 0, 0, 0, 0, 0])
print(x) # [3 2 3]
x = np.random.choice( 10, 3, replace= False, p=[ 0.05, 0, 0.05, 0.9, 0, 0, 0, 0, 0, 0])
print(x) # [3 0 2]
aa_milne_arr = [ 'pooh', 'rabbit', 'piglet', 'Christopher']
x = np.random.choice(aa_milne_arr, 5, p=[ 0.5, 0.1, 0.1, 0.3])
print(x) # ['pooh' 'rabbit' 'pooh' 'pooh' 'pooh']
np.random.seed( 20200614)
x = np.random.randint( 0, 10, 3)
print(x) # [2 0 1]
数据一般都是按照采集顺序排列的,但是在机器学习中很多算法都要求数据之间相互独立,所以需要先对数据集进行洗牌操作。
numpy.random.shuffle(x) Modify a sequence in-place by shuffling its contents.
This function only shuffles the array along the first axis of a
multi-dimensional array. The order of sub-arrays is changed but
their contents remains the same.
对 x 进行重排序,如果 x 为多维数组,只沿第 0 轴洗牌,改变原来的数组,输出为None。
【例】洗牌,改变自身内容,打乱顺序。
numpy.random.permutation(x) Randomly permute a sequence, or return a permuted range.
If x is a multi-dimensional array, it is only shuffled along its first index.
permutation 函数的作用与 shuffle 函数相同,可以打乱第0轴的数据,但是它不会改变原来的数组。
【例】
importnumpy asnp
np.random.seed( 20200614)
x = np.arange( 10)
y = np.random.permutation(x)
print(y)
# [6 8 7 5 3 9 1 4 0 2]
print(np.random.permutation([ 1, 4, 9, 12, 15]))
# [ 4 1 9 15 12]
x = np.arange( 20).reshape(( 5, 4))
print(x)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]
# [16 17 18 19]]
y = np.random.permutation(x)
print(y)
# [[ 8 9 10 11]
# [ 0 1 2 3]
# [12 13 14 15]
# [16 17 18 19]
# [ 4 5 6 7]]
参考文献
https://www.jianshu.com/p/63434ad5ea64
当前活动
我是终身学习者“ 老马”,一个长期践行“结伴式学习”理念的 中年大叔。
我崇尚分享,渴望成长,于2010年创立了“ LSGO软件技术团队”,并加入了国内著名的开源组织“ Datawhale”,也是“ Dre@mtech”、“ 智能机器人研究中心”和“ 大数据与哲学社会科学实验室”的一员。
愿我们一起学习,一起进步,相互陪伴,共同成长。
后台回复「搜搜搜」,随机获取电子资源! 返回搜狐,查看更多
责任编辑: