LoginSignup
5
5

More than 5 years have passed since last update.

Pythonでデータの分析を出来るようになりたい(その2)

Last updated at Posted at 2015-12-31

(その2)

(文中に出てくるページ参照は 統計学が最強の学問である[実践編]データ分析のための思想と方法 - 西内啓 著 という本のページです。)

コインを2回投げるを1セットとして2セット投げた時の確率

その2では、P61の例のように、「2回投げる」=「1セット」として、2セット投げた場合(つまりコインは4回投げる)の結果を考える。
コインは4回投げられるから、表が出るパターンは

  • 表が0回
  • 表が1回
  • 表が2回
  • 表が3回
  • 表が4回

の5通り。

コード


from random import randint
from decimal import Decimal
from prettytable import PrettyTable
import numpy as np

def tossBiasedCoin():
    """ Returns 0 or 1 with 0 having 2/3 chance """
    return randint(0,2) % 2

# Make a 3x3 array
counts = [[0 for j in range(3)] for i in range(3)]

# Toss a coin many times to get counts
sampleCount = 50000
for num in range(sampleCount):    
    firstSet = [tossBiasedCoin(),tossBiasedCoin()]
    secondSet = [tossBiasedCoin(),tossBiasedCoin()]
    counts[sum(secondSet)][sum(firstSet)] += 1

# Conert all counts to perentage
TWOPLACES = Decimal(10) ** -2 
for i in range(3):
    for j in range(3):
        value = counts[i][j]        
        counts[i][j] = (100 * Decimal(counts[i][j])/Decimal(sampleCount)).quantize(TWOPLACES)
        print("Converted the value {} to percentage {}".format(value, counts[i][j]))

# Make summaries of number of heads.
keys = np.arange(5)
values = [counts[0][0], # 0
          counts[0][1]+counts[1][0], # 1
          counts[0][2]+counts[2][0]+counts[1][1],
          counts[1][2]+counts[2][1],
          counts[2][2]]

# Add row descriptions
counts[0].insert(0, '2nd set 0 head')
counts[1].insert(0, '2nd set 1 head')
counts[2].insert(0, '2nd set 2 heads')

# Create table with column descriptions, add rows, then show it.
table = PrettyTable(["", "1st set 0 head", "1st set 1 head", "1st set 2 heads"])
table.padding_width = 1
table.add_row(counts[0])
table.add_row(counts[1])
table.add_row(counts[2])
print table

# Draw a bar chart
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
rects = plt.bar(keys,
                 values, 
                 0.5,
                 alpha=0.4,
                 align="center", 
                 color='b')

plt.xlabel('Number of heads with two sets')
plt.ylabel('Probability (%)')
plt.title('Probabilities heads with a biased coin')
plt.xticks(keys, np.arange(5))

plt.tight_layout()
plt.show()

基本的には前回とほとんど同じプログラム構造。

結果を格納する変数が増えた

図1-19と同じにするために3x3の list を作る。

# Make a 3x3 array
counts = [[0 for j in range(3)] for i in range(3)]

コインを2セット(1セット=2回)投げる

50万回ループさせ、毎回合計4回コインを投げる。

# Toss a coin many times to get counts
sampleCount = 50000
for num in range(sampleCount):    
    firstSet = [tossBiasedCoin(),tossBiasedCoin()]
    secondSet = [tossBiasedCoin(),tossBiasedCoin()]
    counts[sum(secondSet)][sum(firstSet)] += 1

棒グラフのデータの準備

ちょっと面倒になってきた。「表が2回(枚)」でるパターンは、2セットの内、
1セット目が2枚、2セット目が0枚
1セット目が0枚、2セット目が2枚
1セット目が1枚、2セット目が1枚
の3通りあるから、それをすべて足す。

# Make summaries of number of heads.
keys = np.arange(5)
values = [counts[0][0], # 0
          counts[0][1]+counts[1][0], # 1
          counts[0][2]+counts[2][0]+counts[1][1],
          counts[1][2]+counts[2][1],
          counts[2][2]]

表のデータの準備

2x2構造から3x3構造に変えるために、3行目を加える。

# Add row descriptions
counts[0].insert(0, '2nd set 0 head')
counts[1].insert(0, '2nd set 1 head')
counts[2].insert(0, '2nd set 2 heads')

表と棒グラフを作る

基本的には増えた分に対応して変更を加えている。

# Create table with column descriptions, add rows, then show it.
table = PrettyTable(["", "1st set 0 head", "1st set 1 head", "1st set 2 heads"])
table.padding_width = 1
table.add_row(counts[0])
table.add_row(counts[1])
table.add_row(counts[2])
print table

# Draw a bar chart
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
rects = plt.bar(keys,
                 values, 
                 0.5,
                 alpha=0.4,
                 align="center", 
                 color='b')

plt.xlabel('Number of heads with two sets')
plt.ylabel('Probability (%)')
plt.title('Probabilities heads with a biased coin')
plt.xticks(keys, np.arange(5))

plt.tight_layout()
plt.show()

結果

image

なんだか「標準偏差」のグラフっぽく見えて来たぞ!っというのがこの本の、この章がデモンストレーションしようとしているそもそもの内容。

さらに「表が1枚」になる確率が一番高いのが分かる。これは「4回投げて表が出る確率(1/3)」はすなわち「4 x 1/3」= 1.333。つまり「4枚投げりゃぁだいたい表が1枚でるぞ」ということを表している。

(その3)につづく。

5
5
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
5
5