safari029’s blog

暗号通貨、セキュリティ、データ解析、プログラミング等の技術を中心とした適当なメモです。。。

機械学習の勉強をはじめてみる。

以前から気になっていた機械学習を勉強をはじめてみる。

事前知識

pythonを利用すると比較的楽にお勉強ができる。 ・機械学習にもいろいろ種類がある、最新のはやりはDeepLearning(googleの画像解析etc) ・数学はちゃんと勉強しておけばよかった。→必要性を感じて初めてやる気が出た。

初歩から勉強したらどうしたらいいのだろう、とりあえず以下を参考に単純ベイズ法とやらを自分実装しながら、数式も理解していく。

機械学習の Python との出会い

環境

''' $ python --version
Python 2.7.10

$ pip list | grep numpy numpy (1.10.1)

$ pip list | grep ipython ipython (4.0.0) ipython-genutils (0.1.0) '''

単純ベイズ

クラスを作成するところから勉強する。 fitで実際にの学習を行い、

# -*- coding:utf-8 -*-

#URL: http://www.kamishima.net/mlmpyja/

import numpy as np
import scipy as sp
#import matplotlib.pyplot as plt
import sklearn

class NaiveBayes1(object):
    #todo: make class

    def __init__(self):
        self.pY_= None
        self.pXgY_ = None

    def fit(self,X,y):

        # constants
        # n_features:xの特徴種類,n_fvalues:xの値
        n_samples = X.shape[0]
        n_features = X.shape[1]

        # n_classes:yのクラス ,n_fvalues:yの値
        n_classes = 2
        n_fvalues = 2

        if n_samples != len(y):
            raise ValueError('Mismatched number of samples.')

        nY = np.zeros(n_classes, dtype=np.int)
        for i in xrange(n_samples):
            nY[y[i]] += 1

        self.pY_ = np.empty(n_classes,dtype=np.float)
        for i in xrange(n_classes):
            self.pY_[i]= nY[i] / np.float(n_samples)

        nXY = np.zeros((n_features,n_fvalues,n_classes),dtype=np.int)
        for i in xrange(n_samples):
            for j in xrange(n_features):
                nXY[j,X[i,j],y[i]] +=1

        self.pXgY_ = np.empty((n_features,n_fvalues,n_classes),dtype=np.float)
        for j in xrange(n_features):
            for xi in xrange(n_fvalues):
                for yi in xrange(n_classes):
                    self.pXgY_[j,xi,yi]= nXY[j,xi,yi] / np.float(nY[yi])

    def predict(self, X):

        # constants
        n_samples = X.shape[0]
        n_features = X.shape[1]

        # memory for return values
        y = np.empty(n_samples, dtype=np.int)


        for i, xi in enumerate(X):

            #calc predict
            logpXY = np.log(self.pY_) + \
                     np.sum(np.log(self.pXgY_[np.arange(n_features),xi,:]),axis=0)

            y[i] = np.argmax(logpXY)

        return y

実行してみる。

import numpy as np

from nbayes1 import NaiveBayes1

data = np.genfromtxt('vote_filled.tsv',dtype=np.int)

X = data[:, :-1]
y = data[:, -1]

clr = NaiveBayes1()
clr.fit(X,y)

pre_y = clr.predict(X[:10,:])
for i in xrange(10):
    print i,y[i],pre_y[i]

tsvファイルはここから取得します。 sample data

感想

・書くことで数式はなんとなく理解できたが、予想(predict)の公式どうやって導けるのかはよくわからん。やっぱ数学の知識は大事。