0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ベルヌーイ分布を理解するために試してみた

Last updated at Posted at 2021-07-11

E資格受験勉強中です。

ベルヌーイ分布

Wikipadia:ベルヌーイ分布 では
「数学において、確率 p で 1 を、確率 q = 1 − p で 0 をとる、離散確率分布である。」
と説明されています。

コイン投げのように結果が2種類しかない試行(ベルヌーイ試行)を行った場合の分布のことを言うようです。

bernoulli_trial.py
import numpy as np

def bernoulli_trial(coin_data):
    prob_be_data = np.array([])
    for i in np.unique(coin_data):
        p = len(coin_data[coin_data==i]) / len(coin_data)
        print(i, 'が出る確率:', p)
        prob_be_data = np.append(prob_be_data, p)

print('>>1回目のベルヌーイ試行')        
coin_data = np.array([1, 0, 1, 0, 1])
bernoulli_trial(coin_data)

print('>>2回目のベルヌーイ試行') 
coin_data = np.array([0, 0, 0, 0, 0, 1, 1, 1])
bernoulli_trial(coin_data)

結果

>>1回目のベルヌーイ試行
0 が出る確率: 0.4
1 が出る確率: 0.6
>>2回目のベルヌーイ試行
0 が出る確率: 0.625
1 が出る確率: 0.375

結果をグラフにしてみます。

bernoulli_distribution.py
import numpy as np
import matplotlib.pyplot as plt

def bernoulli_trial(coin_data):
    prob_be_data = np.array([])
    for i in np.unique(coin_data):
        p = len(coin_data[coin_data==i]) / len(coin_data)
        print(i, 'が出る確率:', p)
        prob_be_data = np.append(prob_be_data, p)
    return prob_be_data

def bernoulli_distribution(be_data):
    fig, ax = plt.subplots()
    ax.bar([0, 1], be_data, tick_label= ['0', '1'])
    plt.grid(True)

print('>>1回目のベルヌーイ試行')        
coin_data = np.array([1, 0, 1, 0, 1])
be_data = bernoulli_trial(coin_data)
bernoulli_distribution(be_data)
print('>>2回目のベルヌーイ試行') 
coin_data = np.array([0, 0, 0, 0, 0, 1, 1, 1])
be_data = bernoulli_trial(coin_data)
bernoulli_distribution(be_data)

結果
image.png

二項分布を理解するために試してみた
に続きます。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?