亂數產生器與駭客統計

Statistical Thinking in Python (Part 1)

Justin Bois

Teaching Professor at the California Institute of Technology

駭客統計(Hacker statistics)

  • 用重複模擬量測來估算機率。
Statistical Thinking in Python (Part 1)

  ch3-2.004.png

1 Image: artist unknown
Statistical Thinking in Python (Part 1)

ch3-2.005.png

1 Image: Heritage Auction
Statistical Thinking in Python (Part 1)

模擬擲硬幣

ch3-2.010.png

Statistical Thinking in Python (Part 1)

伯努利試驗

  • 一種只有兩種結果的實驗:「成功」(True)與「失敗」(False)。
Statistical Thinking in Python (Part 1)

np.random 模組

import numpy as np
rng = np.random.default_rng()

rng
Generator(PCG64) at 0x7F9433D38120
Statistical Thinking in Python (Part 1)

亂數種子(seed)

  • 輸入亂數演算法的整數種子
  • 只有在需要可重現時才手動設定亂數種子
  • rng = np.random.default_rng(seed) 指定
Statistical Thinking in Python (Part 1)

模擬 4 次擲硬幣

rng = np.random.default_rng(42)

random_numbers = rng.random(size=4)
random_numbers
array([0.77395605, 0.43887844, 0.85859792, 0.69736803])
heads = random_numbers < 0.5
heads
array([False,  True, False, False])
np.sum(heads)
1
Statistical Thinking in Python (Part 1)

模擬 4 次擲硬幣

n_all_heads = 0  # Initialize number of 4-heads trials
for _ in range(10000):
     heads = np.random.random(size=4) < 0.5
     n_heads = np.sum(heads)
     if n_heads == 4:
         n_all_heads += 1

n_all_heads / 10000
0.0607
Statistical Thinking in Python (Part 1)

駭客統計的機率估計

  • 先決定如何模擬資料
  • 進行大量重複模擬
  • 機率≈出現目標結果的試驗比例
Statistical Thinking in Python (Part 1)

一起來練習吧!

Statistical Thinking in Python (Part 1)

Preparing Video For Download...