深層学習とその他

機械学習したいマン

scikit-learnのNaive Bayes使ってみた

アドベントカレンダー24日目です。
今日はscikit-learnでNaive Bayesを使ってみたいと思います。
adventar.org

Naive Bayesについて

今回はGaussian Naive Bayesを使います。

GaussianNB implements the Gaussian Naive Bayes algorithm for classification. The likelihood of the features is assumed to be Gaussian

 \displaystyle 
P \left( x _ { i } | y \right) = \frac { 1 } { \sqrt { 2 \pi \sigma _ { y } ^ { 2 } } } \exp \left( - \frac { \left( x _ { i } - \mu _ { y } \right) ^ { 2 } } { 2 \sigma _ { y } ^ { 2 } } \right)
The parameters \sigma _ { y } and \mu _ { y } are estimated using maximum likelihood.

https://scikit-learn.org/stable/modules/naive_bayes.html#gaussian-naive-bayes

詳しくはよくわかりませんが、使うだけならSVMと同じように簡単です。

学習と分類

とりあえず必要なものをインポートします。
ちょっと種類が多いのは、混同行列を出したりしたからです。

import itertools
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt

from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix



今回はデータセットにdigitを使います。
digits.dataでデータが、digits.targetでラベルが取得できます。

digits = datasets.load_digits()
data = digits.data
target = digits.target



データを学習用とテスト用に分けて学習を始めます。

(X_train, X_test, y_train, y_test) = train_test_split(data, target)
gnb = GaussianNB()
clf = gnb.fit(X_train, y_train)



あとは分類してみましょう。

y_pred = clf.predict(X_test)
np.mean(y_test == y_pred)
Out[19]: 0.8577777777777778



使用したコード及び、classification_reportとconfusion matrixはこちらに載せておきます。


まとめ

今回はNaive Bayesを使ってみましたが、非常にお手軽でした。
scikit-learnにはほかのNaive Bayesもあるので、試してみてください。