LoginSignup
1
3

More than 3 years have passed since last update.

[python]算数・数学⑤~集合と順列と確率~

Last updated at Posted at 2019-07-15

前回まで

前回はこちら

改めて

機械学習を始めるにも、算数や数学がわからないと、入門書すら読めない。ただそこまで、ちゃんと解説してあるものもない。ということで最低限必要な数学基礎をこの記事で書けたらいいなと思っています。

環境

ほぼ影響ないですが、python3系を利用。

前提

四則演算や累乗(2乗とか3乗とか)がわかっていること。

集合

集合とは以下のようなものを言います。一つ一つは要素と言います。
{1,3,5,7,9}

10以下の奇数を要素として集合を記述するときに
{1,3,5,7,9}
という書き方と
{x|xは10以下の奇数の自然数}
という書き方ができます。

要素xが集合Aに属してることを$x\in{A}$と記述します。$1\in{A}$ですし$2\in{A}$ですね。

なお
A = {1,2,3,4,5,6,7,8,9,10}つまり{x|xは10以下の自然数}
B = {1,3,5,7,9}
とあったときに、BはAの部分的な集合(部分集合)と言えるので、$B\subset{A}$もしくは$A\supset{B}$ とすることができます。

pythonでかいてみます。

a = {1,2,3,4,5,6,7,8,9,10}
b = {1,3,5,7,9}
#ちなみにset型となっています。
type(a) #->set

b <= a    #->True

集合の要素を変えてみます

a = {1,2,3,4,5,6}
b = {5,6,7,8,9,10}

a|b#和集合:合体させて重複無くしたもの
->{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

a&b#積集合:重複しているもの
->{5,6}

a-b#差集合:aにあってbにないもの
->{1, 2, 3, 4}

b-a#差集合:bにあってaにないもの
->{7, 8, 9, 10}

a^b#対象差:aもしくはbにしかないもの
->{1, 2, 3, 4,7, 8, 9, 10}

#集合に要素を追加:add()
#集合から要素を削除: discard(), remove(), pop(), clear()

順列

懐かしきこういうやつ。
${}_n P_r = n\times(n-1)\times(n-2)\times(n-3)\times・・・\times(n-r+1)$

7個から3桁を作る場合は

${}_{7} P_3 = 7\times(7-1)\times(7-2)=7\times6\times5=210$
となる。

import itertools
num = {1,2,3,4,5,6,7}
a = set(itertools.permutations(num,3))
len(a) # -> 210

階乗

7個から7桁を作る場合は

${}_{7} P_7 = 7!= 7\times6\times5\times6・・・\times1=5040$

b = set(itertools.permutations(num,7))
len(b) #->5040

import math
math.factorial(7)#->5040

重複順列(一度選んだものを再度選べる場合)

${}_n \Pi_r = n^r$

7つの数字を1つずつ選んで戻して3桁を作る場合

${}_7 \Pi_3 = 7^3$

#7個の数字から1つずつ3回選ぶ
num = {1,2,3,4,5,6,7}
a = set(itertools.product(num,num,num))
len(a)
# -> 343

組み合わせ(Combination)

順番を考慮しないものです。
つまり(1,2,3)と(3,2,1)を同じものとみなします。

${}_nC_r=\frac{nPr}{r!}$

例えば5つの数字から3つの組み合わせを作る

${}_5 C_3 = \frac{5\times{4}\times{3}}{3\times{2}\times{1}}$

num = {1,2,3,4,5}
p = len(set(itertools.permutations(num,3)))
f = math.factorial(3)#階乗
com = p/f
com #-> 10.0

もっと簡単に以下のメソッドで出来る
c = set(itertools.combinations(num,3))
len(c)

ここまで

ここまで。確率については結構雑な感じになっていますが、違う投稿で、尤度の説明でもう少し具体的にしていきます。

次回は微分について投稿していきます。

1
3
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
1
3