目录

  • 1  随机抽样

    • 1.1  离散型随机变量

      • 1.1.1  二项分布
      • 1.1.2  泊松分布
      • 1.1.3  超几何分布
    • 1.2  连续型随机变量
      • 1.2.1  均匀分布
      • 1.2.2  正态分布
      • 1.2.3  指数分布
    • 1.3  其它随机函数
      • 1.3.1  随机从序列中获取元素
      • 1.3.2  对数据集进行洗牌操作

随机抽样

numpy.random 模块对 Python 内置的 random 进行了补充,增加了一些用于高效生成多种概率分
布的样本值的函数,如正态分布、泊松分布等。

  • numpy.random.seed(seed=None) Seed the generator.

seed() 用于指定随机数生成时所用算法开始的整数值,如果使用相同的 seed() 值,则每次生成的随
机数都相同,如果不设置这个值,则系统根据时间来自己选择这个值,此时每次生成的随机数因时间
差异而不同。

在对数据进行预处理时,经常加入新的操作或改变处理策略,此时如果伴随着随机操作,最好还是指
定唯一的随机种子,避免由于随机的差异对结果产生影响。

离散型随机变量

二项分布

二项分布可以用于一次实验只有两种结果,各结果对应的概率相等的多次实验的概率问题。比如
处理猜10次拳赢6次的概率等类似的问题。
二项分布概率函数的数学表示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wAeG7jaj-1606318499499)(attachment:image.png)]

  • 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)。请问,最终所有的勘探井都勘探失败的概率?

import numpy as np
import matplotlib.pyplot as plt
from scipy import statsnp.random.seed(20201125)
n = 9# 做某件事情的次数
p = 0.1# 做某件事情成功的概率
size = 50000
x = np.random.binomial(n, p, size)#成功的次数'''
或者使用binom.rvs
使用binom.rvs(n, p, size=1)函数模拟一个二项随机变量,可视化地表现概率
y = stats.binom.rvs(n, p, size=size)#返回一个numpy.ndarray
'''
print(np.sum(x == 0) / size) # 0.3897
plt.hist(x)
plt.xlabel('随机变量:成功次数')
plt.ylabel('样本中出现的次数')
plt.show()
0.3904D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 38543 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 26426 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 21464 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 37327 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 65306 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 25104 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 21151 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 27425 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 25968 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 26679 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 26412 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20013 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20986 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 29616 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 30340 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 38543 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 26426 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 21464 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 37327 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 65306 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 25104 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 21151 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 27425 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 25968 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 26679 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 26412 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20013 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20986 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 29616 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 30340 missing from current font.font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-c6mFT0KR-1606318499501)(output_10_2.png)]

plt.hist(x)
plt.xlabel('成功次数')
plt.ylabel('样本中次数')
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zcrN4SmI-1606318499502)(output_11_0.png)]

s = stats.binom.pmf(range(10), n, p)
print(np.around(s, 3))#它返回一个列表,列表中每个元素表示随机变量中对应值的概率
[0.387 0.387 0.172 0.045 0.007 0.001 0.    0.    0.    0.   ]

【例】模拟投硬币,投2次,请问两次都为正面的概率?

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
np.random.seed(20200605)
n = 2# 做某件事情的次数,这里是投两次硬币
p = 0.5#做某件事情成功的概率,在这里即投硬币为正面的概率
size = 50000
x = np.random.binomial(n, p, size)#成功的次数
'''或者使用binom.rvs
#使用binom.rvs(n, p, size=1)函数模拟一个二项随机变量,可视化地表现概率
y = stats.binom.rvs(n, p, size=size)#返回一个numpy.ndarray
'''
print(np.sum(x == 0) / size) # 0.25154
print(np.sum(x == 1) / size) # 0.49874
print(np.sum(x == 2) / size) # 0.24972
plt.hist(x, density=True)
plt.xlabel('随机变量:硬币为正面次数')
plt.ylabel('50000个样本中出现的次数')
plt.show()
#它返回一个列表,列表中每个元素表示随机变量中对应值的概率
s = stats.binom.pmf(range(n + 1), n, p)
print(np.around(s, 3))
# [0.25 0.5 0.25]
0.25154
0.49874
0.24972D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 30828 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 24065 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20026 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 27491 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 38754 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20010 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 30828 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 24065 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20026 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 27491 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 38754 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20010 missing from current font.font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pWj3m4Bw-1606318499503)(output_14_2.png)]

[0.25 0.5  0.25]

泊松分布

泊松分布主要用于估计某个时间段某事件发生的概率。泊松概率函数的数学表示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L8Qhu5Vu-1606318499504)(attachment:image.png)]

  • numpy.random.poisson(lam=1.0, size=None) Draw samples from a Poisson distribution.

表示对一个泊松分布进行采样, size 表示采样的次数, lam 表示一个单位内发生事件的平均值,函
数的返回值表示一个单位内事件发生的次数。

【例】假定某航空公司预定票处平均每小时接到42次订票电话,那么10分钟内恰好接到6次电话的概
率是多少?

import numpy as np
from scipy import stats
import matplotlib.pyplot as pltnp.random.seed(20200605)
lam = 42 / 6# 平均值:平均每十分钟接到42/6次订票电话
size = 50000
x = np.random.poisson(lam, size)
'''或者
#模拟服从泊松分布的50000个随机变量
x = stats.poisson.rvs(lam,size=size)
'''print(np.sum(x == 6) / size) # 0.14988
plt.hist(x)
plt.xlabel('随机变量:每十分钟接到订票电话的次数')
plt.ylabel('50000个样本中出现的次数')
plt.show()#用poisson.pmf(k, mu)求对应分布的概率:概率质量函数 (PMF)
x = stats.poisson.pmf(6, lam)
print(x) # 0.14900277967433773
0.14988

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CNrxkMMV-1606318499505)(output_21_1.png)]

0.14900277967433773

超几何分布

在超几何分布中,各次实验不是独立的,各次实验成功的概率也不等。 超几何分布概率函数的数学表
示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WNItnOwl-1606318499506)(attachment:image.png)]

  • 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只狗的概率(无放回抽样)。

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
np.random.seed(20200605)
size = 500000
x = np.random.hypergeometric(ngood=7, nbad=13, nsample=12, size=size)
'''或者
#用rvs(M, n, N, loc=0, size=1, random_state=None)模拟
x = stats.hypergeom.rvs(M=20,n=7,N=12,size=size)
'''print(np.sum(x == 3) / size) # 0.198664
plt.hist(x, bins=8) #条数为8
plt.xlabel('狗的数量')
plt.ylabel('50000个样本中出现的次数')
plt.title('超几何分布',fontsize=20)
plt.show()"""
M 为总体容量
n 为总体中具有成功标志的元素的个数
N,k 表示抽取N个元素有k个是成功元素
"""
x = range(8)
#用hypergeom.pmf(k, M, n, N, loc)来计算k次成功的概率
s = stats.hypergeom.pmf(k=x, M=20, n=7, N=12)
print(np.round(s, 3))  #保留三位小数
# [0. 0.004 0.048 0.199 0.358 0.286 0.095 0.01 ]
0.198664D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 36229 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20960 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20309 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20998 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 24067 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 29399 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 30340 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 25968 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 37327 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20010 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 26679 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 26412 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20013 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20986 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 29616 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 27425 missing from current font.font.set_text(s, 0.0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 29399 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 30340 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 25968 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 37327 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20010 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 26679 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 26412 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20013 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20986 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 29616 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 27425 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 36229 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20960 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20309 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20998 missing from current font.font.set_text(s, 0, flags=flags)
D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 24067 missing from current font.font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wr3NbGbb-1606318499506)(output_27_2.png)]

[0.    0.004 0.048 0.199 0.358 0.286 0.095 0.01 ]

超几何分布的均值与方差
均值E(x) = N(n/M)
方差Var(x) = N(n/M)(1‐n/M)((M‐N)/(M‐1))
注释:考虑n次实验的超几何分布,令p=n/M,当总体容量足够大时((M‐N)/(M‐1))近似于1,此时数学期望为
Np,方差为Np(1‐p).

#用stats(M, n, N, loc=0, moments='mv')计算均值和方差
stats.hypergeom.stats(20,7,12,moments='mv')  #Mean(‘m’), variance(‘v’), skew(‘s’), and/or kurtosis(‘k’).
(array(4.2), array(1.14947368))

连续型随机变量

均匀分布

  • numpy.random.uniform(low=0.0, high=1.0, size=None) Draw samples from a uniform
    distribution.

【例】在low到high范围内,创建大小为size的均匀分布的随机数

import numpy as np
import matplotlib.pyplot as plt
from scipy import statsnp.random.seed(20200614)
a = 0
b = 100
size = 50000
x = np.random.uniform(a, b, size=size)print(np.all(x >= 0)) # True
print(np.all(x < 100)) # True
y = (np.sum(x < 50)- np.sum(x < 10)) / size
print(y) # 0.40144plt.hist(x, bins=20)
plt.show()
a = stats.uniform.cdf(10, 0, 100)
b = stats.uniform.cdf(50, 0, 100)
print(b- a) # 0.4
True
True
0.40144

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pBOPxXeE-1606318499507)(output_34_1.png)]

0.4

作为 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)之间均匀分布的随机数。

import numpy as np
np.random.seed(20200614)
print(np.random.rand())
# 0.7594819171852776print(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.7594819171852776print(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]]
0.7594819171852776
[0.75165827 0.16552651 0.0538581  0.46671446 0.89076925]
[[0.10073292 0.14624784 0.40273923][0.21844459 0.22226682 0.37246217][0.50334257 0.01714939 0.47780388][0.08755349 0.86500477 0.70566398]]
0.7594819171852776
[0.75165827 0.16552651 0.0538581  0.46671446 0.89076925]
[[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)之间随机整数。

import numpy as np
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]]
[0 0 0 1 0 1 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[[3 3 0 1][1 1 0 1]]
[[2 1 7 7][7 2 4 6][8 7 2 8]]

正态分布

标准正态分布数学表示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4qruJjOl-1606318499508)(attachment:image.png)]

  • numpy.random.randn(d0, d1, …, dn) Return a sample (or samples) from the “standard
    normal” distribution

【例】根据指定大小产生满足标准正态分布的数组(均值为0,标准差为1)。

import numpy as np
import matplotlib.pyplot as plt
from scipy import statsnp.random.seed(20200614)
size = 50000
x = np.random.randn(size)
y1 = (np.sum(x < 1) - np.sum(x < -1)) / size
y2 = (np.sum(x < 2) - np.sum(x < -2)) / size
y3 = (np.sum(x < 3) - np.sum(x < -3)) / size
print(y1) # 0.68596
print(y2) # 0.95456
print(y3) # 0.99744plt.hist(x, bins=20)
plt.show()
y1 = stats.norm.cdf(1) - stats.norm.cdf(-1)
y2 = stats.norm.cdf(2) - stats.norm.cdf(-2)
y3 = stats.norm.cdf(3) - stats.norm.cdf(-3)
print(y1) # 0.6826894921370859
print(y2) # 0.9544997361036416
print(y3) # 0.9973002039367398
0.68596
0.95456
0.99744

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GVJsuhpO-1606318499508)(output_50_1.png)]

0.6826894921370859
0.9544997361036416
0.9973002039367398

还可以指定分布以及所需参数来进行随机,例如高斯分布中的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

【例】

import numpy as np
import matplotlib.pyplot as pltnp.random.seed(20200614)
x = 0.5 * np.random.randn(2, 4) + 5'''或者
#模拟10000个随机变量
x = 0.5*stats.norm.rvs(size=(2,4))+5
'''
print(x)
# [[5.39654234 5.4088702 5.49104652 4.95817289]
# [4.31977933 4.76502391 4.70720327 4.36239023]]np.random.seed(20200614)
mu = 5#平均值
sigma = 0.5#标准差
x = np.random.normal(mu, sigma, (2, 4))
print(x)
# [[5.39654234 5.4088702 5.49104652 4.95817289]
# [4.31977933 4.76502391 4.70720327 4.36239023]]size = 50000x = np.random.normal(mu, sigma, size)
print(np.mean(x)) # 4.996403463175092
print(np.std(x, ddof=1)) # 0.4986846716715106(#样本标准差)
'''
ddof:int, optional
Means Delta Degrees of Freedom. The divisor used in calculations is N ‐ ddof, where N
represents the number of elements. By default ddof is zero.
'''
[[5.39654234 5.4088702  5.49104652 4.95817289][4.31977933 4.76502391 4.70720327 4.36239023]]
[[5.39654234 5.4088702  5.49104652 4.95817289][4.31977933 4.76502391 4.70720327 4.36239023]]
4.996403463175092
0.4986846716715106'\nddof:int, optional\nMeans Delta Degrees of Freedom. The divisor used in calculations is N ‐ ddof, where N\nrepresents the number of elements. By default ddof is zero.\n'

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xNFsfASn-1606318499509)(attachment:image.png)]

plt.hist(x, bins=20)
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5YeMhYSC-1606318499509)(output_57_0.png)]

指数分布

指数分布描述时间发生的时间长度间隔。指数分布的数学表示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w4kwrvap-1606318499510)(attachment:image.png)]

  • numpy.random.exponential(scale=1.0, size=None) Draw samples from an exponential
    distribution.

【例】 scale = 1/lambda

import numpy as np
import matplotlib.pyplot as plt
from scipy import statsnp.random.seed(20200614)
lam = 7
size = 50000
x = np.random.exponential(1 / lam, size)
'''或者
#rvs(loc=0, scale=1/lam, size=size, random_state=None)模拟
'''
y1 = (np.sum(x < 1 / 7)) / size
y2 = (np.sum(x < 2 / 7)) / size
y3 = (np.sum(x < 3 / 7)) / size
print(y1) # 0.63218
print(y2) # 0.86518
print(y3) # 0.95056plt.hist(x, bins=20)
plt.show()
y1 = stats.expon.cdf(1 / 7, scale=1 / lam)
y2 = stats.expon.cdf(2 / 7, scale=1 / lam)
y3 = stats.expon.cdf(3 / 7, scale=1 / lam)
print(y1) # 0.6321205588285577
print(y2) # 0.8646647167633873
print(y3) # 0.950212931632136
0.63218
0.86518
0.95056

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jSCOg8e7-1606318499510)(output_63_1.png)]

0.6321205588285577
0.8646647167633873
0.950212931632136

其它随机函数

随机从序列中获取元素

  • 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 。

import numpy as np
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]
[2 0 1]
[3 2 3]
[3 0 2]
['pooh' 'rabbit' 'pooh' 'pooh' 'pooh']
[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。

【例】洗牌,改变自身内容,打乱顺序。

import numpy as np
np.random.seed(20200614)
x = np.arange(10)
np.random.shuffle(x)
print(x)
# [6 8 7 5 3 9 1 4 0 2]
print(np.random.shuffle([1, 4, 9, 12, 15]))
# None
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]]
np.random.shuffle(x)
print(x)
# [[ 4 5 6 7]
# [ 0 1 2 3]
# [ 8 9 10 11]
# [16 17 18 19]
# [12 13 14 15]]
[6 8 7 5 3 9 1 4 0 2]
None
[[ 0  1  2  3][ 4  5  6  7][ 8  9 10 11][12 13 14 15][16 17 18 19]]
[[ 8  9 10 11][ 0  1  2  3][12 13 14 15][16 17 18 19][ 4  5  6  7]]

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轴的数据,但是它不会改变原来的数
组。

【例】

import numpy as np
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]]
[6 8 7 5 3 9 1 4 0 2]
[ 4  1  9 15 12]
[[ 0  1  2  3][ 4  5  6  7][ 8  9 10 11][12 13 14 15][16 17 18 19]]
[[ 8  9 10 11][ 0  1  2  3][12 13 14 15][16 17 18 19][ 4  5  6  7]]

随机抽样的python实现相关推荐

  1. 基于 Python 的 8 种常用抽样方法

    抽样是统计学.机器学习中非常重要,也是经常用到的方法,因为大多时候使用全量数据是不现实的,或者根本无法取到.所以我们需要抽样,比如在推断性统计中,我们会经常通过采样的样本数据来推断估计总体的样本. 上 ...

  2. 从样本中抽样的Python技术

    从样本中抽样的Python技术 1. 简单随机抽样 2. 分层随机抽样 3. 簇抽样 4. 系统抽样 5. 分层整群抽样 6. 自助法 7. 集群抽样 8. 分层抽样 9. 系统整群抽样 10. 非概 ...

  3. 关于VGA、DVI、HDMI的区别大盘点

    这几天有朋友一直在讨论VGA与HDMI接口的区别,这个之前我们就HDMI与VGA的传输距离进行了初步的了解,随着技术的发展,VGA与HDMI接口也有新的更新,这期我们了再深入的了解VGA.DVI.HD ...

  4. python随机抽取样本1500个_(python)随机抽样

    随机抽样法就是调查对象总体中每个部分都有同等被抽中的可能,是一种完全依照机会均等的原则进行的抽样调查,被称为是一种"等概率".随机抽样有四种基本形式,即简单随机抽样.等距抽样.类型 ...

  5. python之Numpy随机抽样

    随机抽样 前言 一.随机模块 二.离散型随机变量 二项分布 计算期望和方差 泊松分布 超几何分布 三.连续型随机变量 均匀分布 四.正态分布 五.指数分布 其他随机函数 前言 numpy.random ...

  6. python随机抽样_掌握python中的随机抽样

    python随机抽样 Python provides many useful tools for random sampling as well as functions for generating ...

  7. 【深度学习】python实现等距随机抽样

    在实际的样本抽帧需求中,往往有这样一种需求,例如,从20帧到75帧,抽取29帧数据,如果使用python自带的randint 函数,往往抽取的数据间隔是不一致的,这就需要等距随机抽样. 等距随机抽样就 ...

  8. python进行excel随机抽样

    最近需要对多个excel中数万条数据进行随机抽样,采用python进行. excel读取和写入使用openpyxl第三方库. 随机抽样使用random.sample函数. (抽取遇到的最大问题是不知道 ...

  9. python随机抽样numpy_随机抽样 (`numpy.random`) | NumPy 中文

    # 随机抽样 (numpy.random) Numpy的随机数例程使用 BitGenerator 和 Generator 的组合来生成伪随机数以创建序列,并使用这些序列从不同的统计分布中进行采样: B ...

最新文章

  1. 1.2控制台的大体设置:
  2. 谈一谈 MPU6050 姿态融合(转)
  3. WINDOWS SERVER 2003 DHCP服务器全攻略
  4. Win11右键菜单变换Win10风格
  5. 安装后添加没有class library_《没有秘密的你》:戚薇曝光手机号,粉丝急忙添加后却甜哭了?...
  6. Linux串口编程详解
  7. python 爬虫框架_Python实战:爬虫框架(6)
  8. 星巴克又出事 被强制执行1087万!网友:欠租了吗?
  9. 以拼多多为例,中国互联网企业在农业上都做了哪些努力?
  10. Java界面排号系统_【前端系统】javaweb技术的医院门诊在线预约及排号管理系统的实现...
  11. 基于华为云的一个典型的持续部署方案
  12. 用户名登陆时如何在后面加一个小红*_最后一个登陆框引起的血案
  13. linux思源黑体乱码,Source Han Sans 思源黑体字体包
  14. keepalived 二
  15. 实训流水账之day01—安装软件
  16. pde中微元分析法的主要思想_有限元法(FEM)
  17. 异步电动机的matlab建模与仿真,异步电动机的matlab建模与仿真
  18. java历史记录_简单的带历史记录的搜索功能实现
  19. 【IdeaVR2019快捷操作(三)】-基础功能小组协作使用介绍
  20. mysql双活脑裂_从两地三中心到双活数据中心

热门文章

  1. 一生一代一双人:我与51CTO学院的情缘----写于51CTO学院2周年庆
  2. 扒一扒那些叫欧拉的定理们(七)——欧拉线定理的证明
  3. 11度青春之《老男孩》
  4. CodeForces 19E 仙女fairy
  5. 给小朋友讲故事——科学课,地球,太阳和月亮第二集人类登月第一段
  6. 德勤加拿大:在Flow链上创建NFT所消耗的能量比人们搜索或发布一个帖子还少
  7. 联想TinkPad S3-490 后盖拆机教程
  8. 如何用PS(photoshop)给照片加文字
  9. 小米4 miui专用 Xposed安装器86版
  10. 《数学之美》吴军-读书笔记