ナイーブベイズ分類

Part 1: 数学的な準備
Part 2: ベイズの定理
Part 3: ナイーブベイズの紹介
Part 4: 数学的な背景
Part 5: 確率を使った分類
Part 6: Gaussian Naive Bayes
Part 7: Scikit Learnを使ったGaussian Naive Bayes

Part 1: 数学的な準備

まずは足し算で使われるΣの、かけ算バージョン、Πについてです。

$$\prod_{i=1}^4 i = 1\cdot 2\cdot 3\cdot 4, $$ これは連続的なかけ算を意味するので、 $$\prod_{i=1}^4 i = 24. $$

Arg Max

与えられた関数を最大にする入力(定義域)を次のような記号で書くことがあります。

$$\operatorname*{arg\,max}_x f(x) := \{x \mid \forall y : f(y) \le f(x)\}$$

例えば、f(x)が 1−|x| なら、この関数を最大にするxは0になります。

$$\operatorname*{arg\,max}_x (1-|x|) = \{0\}$$

Part 2: ベイズの定理

統計に関して解説した付録のなかに、ベイズの定理を紹介したレクチャーがありますので、そちらを先にご覧ください。

Part 3: ナイーブベイズの紹介

ナイーブベイズ(Naive Bayes)は、スパムメールの分類などに実際に利用されている機械学習アルゴリズムです。ただ、その背景を完全に理解するには、数学的な記述が欠かせません。ここでは、細かいところを省略しながら、その本質をご紹介します。

Part 4: 数学的な背景

yが目的変数、説明変数が x1 から xn まであるとします。ベイズの定理を使うと、与えられた説明変数を元に、そのサンプルがどのクラスに属するかの確率を次のような式で計算できます。

$$P(y \mid x_1, \dots, x_n) = \frac{P(y) P(x_1, \dots x_n \mid y)} {P(x_1, \dots, x_n)}$$

ナイーブベイズのナイーブは、各説明変数が互いに独立であるという仮定から来ています。 $$P(x_i | y, x_1, \dots, x_{i-1}, x_{i+1}, \dots, x_n) = P(x_i | y)$$

この仮定のもとでは、すべての i について、式を次のように変形できます。

$$P(y \mid x_1, \dots, x_n) = \frac{P(y) \prod_{i=1}^{n} P(x_i \mid y)} {P(x_1, \dots, x_n)}$$

それぞれの変数について、クラスごとの確率を求めればよいので、計算が楽になります。

Part 5: 確率を使った分類

ナイーブベイズでは、それぞれのクラスに属する確率が計算されるので、最終的には、そのサンプルを、確率が最も大きいクラスに分類します。ここで、arg maxの記号が出てくる分けです。

P(x1, ..., xn) は手元のデータセットに関しては一定の値なので、無視できます。

$$P(y \mid x_1, \dots, x_n) \propto P(y) \prod_{i=1}^{n} P(x_i \mid y)$$

最終的には、もっとも大きな確率が割り当たるクラスに、サンプルを分類します。

$$\hat{y} = \arg\max_y P(y) \prod_{i=1}^{n} P(x_i \mid y),$$

Part 6: Gaussian Naive Bayes

説明変数が連続値の場合、これを正規分布に従うものとしてモデル化すると、モデルの構築や計算が楽にです。サンプルデータのアヤメのデータも連続値ですので、後ほどの、Gaussian Naive Bayesを利用します。

$$p(x=v|c)=\frac{1}{\sqrt{2\pi\sigma^2_c}}\,e^{ -\frac{(v-\mu_c)^2}{2\sigma^2_c} }$$

Part 7: Scikit learnを使ったGaussian Naive Bayes

In [1]:
import pandas as pd
from pandas import Series,DataFrame

import matplotlib.pyplot as plt
import seaborn as sns

# Gaussian Naive Bayes のためのコード
from sklearn import datasets
from sklearn import metrics
from sklearn.naive_bayes import GaussianNB

アヤメのデータを使います。

In [2]:
iris = datasets.load_iris()

X = iris.data

Y = iris.target

print(iris.DESCR)
Iris Plants Database

Notes
-----
Data Set Characteristics:
    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
    :Summary Statistics:
    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20  0.76     0.9565  (high!)
    ============== ==== ==== ======= ===== ====================
    :Missing Attribute Values: None
    :Class Distribution: 33.3% for each of 3 classes.
    :Creator: R.A. Fisher
    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
    :Date: July, 1988

This is a copy of UCI ML iris datasets.
http://archive.ics.uci.edu/ml/datasets/Iris

The famous Iris database, first used by Sir R.A Fisher

This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.

References
----------
   - Fisher,R.A. "The use of multiple measurements in taxonomic problems"
     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
     Mathematical Statistics" (John Wiley, NY, 1950).
   - Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis.
     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
     Structure and Classification Rule for Recognition in Partially Exposed
     Environments".  IEEE Transactions on Pattern Analysis and Machine
     Intelligence, Vol. PAMI-2, No. 1, 67-71.
   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions
     on Information Theory, May 1972, 431-433.
   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II
     conceptual clustering system finds 3 classes in the data.
   - Many, many more ...

まずは、インスタンスを作るところから

In [3]:
model = GaussianNB()

データを、テスト用とトレーニング用に分けます。

In [9]:
from sklearn.cross_validation import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0)

fitを使います。

In [10]:
model.fit(X_train,Y_train)
Out[10]:
GaussianNB()

予測の精度を比較してみましょう。

In [11]:
predicted = model.predict(X_test)

expected = Y_test

metricsが便利です。

In [12]:
print(metrics.accuracy_score(expected, predicted))
1.0

Part 8: More Resources

There are plenty more resources and types of Naive Bayes Classifiers, For more resources on Naive Bayes, check out the following links:

1.) SciKit Learn Documentation

2.) Wikipedia Naive Bayes