伪随机数生成

Python 抽样

James Chapman

Curriculum Manager, DataCamp

"随机"是什么意思?

形容词 无方法或无意识决定地完成、发生或选择的。

1 牛津词典
Python 抽样

真随机数

  • 由物理过程生成,如抛硬币
  • Hotbits 使用放射性衰变
  • RANDOM.ORG 使用大气噪声
  • 真正的随机性成本高
1 https://www.fourmilab.ch/hotbits 2 https://www.random.org
Python 抽样

伪随机数生成

  • 伪随机数生成既便宜又快速
  • 下一个"随机数"由前一个"随机数"计算得出
  • 第一个"随机数"由种子生成
  • 相同的种子会产生相同的随机数
Python 抽样

伪随机数生成示例

seed = 1
calc_next_random(seed)
3
calc_next_random(3)
2
calc_next_random(2)
6
Python 抽样

随机数生成函数

  • 在前面加上 numpy.random,如 numpy.random.beta()
function distribution function distribution
.beta Beta分布 .hypergeometric 超几何分布
.binomial 二项分布 .lognormal 对数正态分布
.chisquare 卡方分布 .negative_binomial 负二项分布
.exponential 指数分布 .normal 正态分布
.f F分布 .poisson 泊松分布
.gamma Gamma分布 .standard_t t分布
.geometric 几何分布 .uniform 均匀分布
Python 抽样

可视化随机数

randoms = np.random.beta(a=2, b=2, size=5000)
randoms
array([0.6208281 , 0.73216171, 0.44298403, ..., 
       0.13411873, 0.52198411, 0.72355098])
plt.hist(randoms, bins=np.arange(0, 1, 0.05))
plt.show()

beta分布直方图

Python 抽样

随机数种子

np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
Python 抽样

使用不同的种子

np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
np.random.seed(20041004)
np.random.normal(loc=2, scale=1.5, size=2)
array([1.09364337, 4.55285159])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.67038916, 2.36677492])
Python 抽样

Passons à la pratique !

Python 抽样

Preparing Video For Download...