iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
AI & Data

我比機器更需要學習系列 第 15

Day15 單純貝氏分類器實作

https://github.com/PacktPublishing/Machine-Learning-Algorithms

單純貝氏有三種版本白努力、多項式、高斯,今天先學白努力。
白努力:是二元分布,適用於特徵存在或不存在時。
多項式:是離散分布,適用於特徵為整數時(NLP中單辭出現頻率)。
高斯:是連續分布。

白努力單純貝氏

一樣先導入套件,上面的是用來算數學的;下面的是用來畫畫的,並且幫它們取綽號(np & plt)。

import numpy as np
import matplotlib.pyplot as plt

再來,用seed()隨機產生整數的亂數後,設定樣本數300,建立資料集。

np.random.seed(1000)
nb_samples = 300
from sklearn.datasets import make_classification
def show_dataset(X, Y):
    fig, ax = plt.subplots(1, 1, figsize=(30, 25))
    ax.grid()
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    for i in range(nb_samples):
        if Y[i] == 0:
            ax.scatter(X[i, 0], X[i, 1], marker='o', color='r')
        else:
            ax.scatter(X[i, 0], X[i, 1], marker='^', color='b')
    plt.show()
X, Y = make_classification(n_samples=nb_samples, n_features=2, n_informative=2, n_redundant=0)

https://ithelp.ithome.com.tw/upload/images/20210918/20137546HUwNXislsR.png

接著,把資料分成訓練用跟測試用,跟之前一樣。不同的是BernoulliNB裡面有binarize功能,用來內部轉換特徵,需要自行設定二元門檻,這裡是設定0.0,建模後得到準確率。

from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.naive_bayes import BernoulliNB
bnb = BernoulliNB(binarize=0.0)
bnb.fit(X_train, Y_train)
print('Bernoulli Naive Bayes score: %.3f' % bnb.score(X_test, Y_test)) // Bernoulli Naive Bayes score: 0.840
bnb_scores = cross_val_score(bnb, X, Y, scoring='accuracy', cv=10)
print('Bernoulli Naive Bayes CV average score: %.3f' % bnb_scores.mean()) // Bernoulli Naive Bayes CV average score: 0.853

最後,試試看模型準不準確就完工了。

data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
Yp = bnb.predict(data)
print(Yp)

最近,小弟有看到一篇資料科學家寫的很淺顯易懂的貝氏定理,在此跟各位分享/images/emoticon/emoticon37.gif

https://leemeng.tw/intuitive-understandind-of-bayes-rules-and-learn-from-experience.html


上一篇
Day14 邏輯斯迴歸實作
下一篇
Day16 支持向量機實作
系列文
我比機器更需要學習23
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言