偽隨機數生成

Python 中的抽樣

James Chapman

Curriculum Manager, DataCamp

什麼是隨機?

依據 {adjective},在沒有方法或主觀決策下製作、執行、發生或選擇。

1 Oxford Languages
Python 中的抽樣

真正的隨機數

  • 來自物理過程,例如擲硬幣
  • Hotbits 使用放射性衰變
  • RANDOM.ORG 使用大氣噪音
  • 真的隨機很昂貴
1 https://www.fourmilab.ch/hotbits 2 https://www.random.org
Python 中的抽樣

偽隨機數生成

  • 偽隨機數生成既便宜快速
  • 下一個「隨機」數由前一個「隨機」數計算而得
  • 第一個「隨機」數由 seed 產生
  • 相同的 seed 值會產生相同的隨機數
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 Hypergeometric
.binomial Binomial .lognormal Lognormal
.chisquare Chi-squared .negative_binomial Negative binomial
.exponential Exponential .normal Normal
.f F .poisson Poisson
.gamma Gamma .standard_t t
.geometric Geometric .uniform 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 中的抽樣

隨機數的 seed

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 中的抽樣

使用不同的 seed

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 中的抽樣

一起來練習吧!

Python 中的抽樣

Preparing Video For Download...