確率の例
この演習では、復元抽出(置換あり)と非復元抽出(置換なし)の違いを復習します。シミュレーションで事象の確率を計算し、サンプリング方法を変えて確率への影響を確認します。
青3個、緑2個、黄5個の色付きキャンディが入ったボウルを考えます。1個ずつ、置換ありと置換なしのそれぞれで3個引きます。3個すべてが黄色になる確率を計算してください。
この演習はコースの一部です
Pythonで学ぶ統計シミュレーション
演習の手順
- 青のキャンディ
'b'を3個、緑のキャンディ'g'を2個、黄色のキャンディ'y'を5個もつリストとしてbowlを用意します。 - 置換ありで3個サンプルを引いたもの(
sample_rep)と、置換なしで3個引いたもの(sample_no_rep)を作成します。 - 置換ありのサンプルについて、
sample_repに'b'と'g'が1つも含まれなければsuccess_repをインクリメントします。同様に、sample_no_repに'b'と'g'が含まれなければsuccess_no_repをインクリメントします。 - それぞれの確率を、成功回数を反復回数で割って計算します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Set up the bowl
success_rep, success_no_rep, sims = 0, 0, 10000
bowl = list(____*3 + ____*2 + ____*5)
for i in range(sims):
# Sample with and without replacement & increment success counters
sample_rep = np.random.____(bowl, size=3, replace=____)
sample_no_rep = np.random.____(bowl, size=3, replace=____)
if ('b' not in sample_rep) & ('g' not in sample_rep) :
____
if ('b' not in sample_no_rep) & ('g' not in sample_no_rep) :
____
# Calculate probabilities
prob_with_replacement = ____/sims
prob_without_replacement = ____/sims
print("Probability with replacement = {}, without replacement = {}".format(prob_with_replacement, prob_without_replacement))