樸素貝葉斯

原理

貝葉斯分類是一類分類算法的總稱,這類算法均以貝葉斯定理爲基礎,故統稱爲貝葉斯分類。

貝葉斯定理

P(AB)P(A|B) 表示事件B已經發生的前提下,事件A發生的概率,叫做事件B發生下事件A的條件概率。其基本求解公式爲:
P(AB)=P(AB)P(B)P(A|B)=\frac{P(AB)}{P(B)}
貝葉斯定理之所以有用,是因爲我們在生活中經常遇到這種情況:我們可以很容易直接得出P(A|B),P(B|A)則很難直接得出,但我們更關心P(B|A),貝葉斯定理就爲我們打通從P(A|B)獲得P(B|A)的道路:
P(BA)=P(AB)P(B)P(A)P(B|A)=\frac{P(A|B)P(B)}{P(A)}

樸素貝葉斯算法包含多種方法,主要有貝努力樸素貝葉斯、高斯樸素貝葉斯、多項式樸素貝葉斯。

貝努力樸素貝葉斯

該模型適用於符合貝努力分佈的數據集,貝努力分佈也被成爲“二項分佈”或者“0-1 分佈”。

import numpy as np
from sklearn.naive_bayes import BernoulliNB
  
  
def bayes1():
   # 分別表示:[刮北風、悶熱、多雲、天氣預報有雨]
   X = np.array([[0, 1, 0, 1],
                 [1, 1, 1, 0],
                 [0, 1, 1, 0],
                 [0, 0, 0, 1],
                 [0, 1, 1, 0],
                 [0, 1, 0, 1],
                 [1, 0, 0, 1]])
   # 實際的 7 天中,是否有雨,0-沒雨,1-有雨
   y = np.array([0, 1, 1, 0, 1, 0, 0])
   counts = {}
   for label in np.unique(y):
       counts[label] = X[y == label].sum(axis=0)
   print('feature counts:\n{}'.format(counts))
   clf = BernoulliNB()
   clf.fit(X, y)
   Next_day = [[0, 0, 1, 0]]
   pre = clf.predict(Next_day)
   print('------------')
   if pre == [1]:
       print('要下雨了')
   else:
       print('晴天')
   print('--------------')
   # 樸素貝葉斯對於預測具體的數值並不擅長,給出的概率僅供參考
   print('模型預測分類的概率:{}'.format(clf.predict_proba(Next_day)))
   print('--------------')

運行結果

feature counts:
{0: array([1, 2, 0, 4]), 1: array([1, 3, 3, 0])}
------------
要下雨了
--------------
模型預測分類的概率:[[0.13848881 0.86151119]]
--------------
高斯樸素貝葉斯

改模型適用於符合高斯分佈的數據集,或者說符合正態分佈。

from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
import numpy as np


def guassian1():
    X, y = make_blobs(n_samples=500, centers=5, random_state=8)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=8)
    gnb = GaussianNB()
    gnb.fit(X_train, y_train)
    print('--------------')
    print('模型得分:{:.3f}'.format(gnb.score(X_test, y_test)))
    print('-----------')
    x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
    y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
    # 用不同的色塊表示不同的分類
    xx, yy = np.meshgrid(np.arange(x_min, x_max, .02),
                         np.arange(y_min, y_max, .02))
    z = gnb.predict(np.c_[(xx.ravel(), yy.ravel())]).reshape(xx.shape)
    plt.pcolormesh(xx, yy, z)
    # 用散點圖畫出訓練集和測試數據集
    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, edgecolors='k')
    plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, marker='*', edgecolors='k')
    # 設定橫軸縱軸的範圍
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    # 設定圖題
    plt.title('gaussianNB')
    plt.show()

運行結果

--------------
模型得分:0.968
-----------
高斯分佈
多項式樸素貝葉斯

該模型適用於符合多項式分佈的數據集,輸入的 X 必須是非負的。

from sklearn.naive_bayes import MultinomialNB
from sklearn.preprocessing import MinMaxScaler
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split


def multinomial1():
    X, y = make_blobs(n_samples=500, centers=5, random_state=8)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=8)
    scaler = MinMaxScaler()
    scaler.fit(X_train)
    X_train_scaled = scaler.transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    mnb = MultinomialNB()
    mnb.fit(X_train_scaled, y_train)
    print('------')
    print('模型得分:{:.3f}'.format(mnb.score(X_test_scaled, y_test)))
    print('------') 

運行結果

------
模型得分:0.320
------
預測腫瘤
# 導入威斯康星乳腺腫瘤數據集
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
    

def example1():
    cancer = load_breast_cancer()
    print('--------------')
    print(cancer.keys())
    print('---------------------')
    print('腫瘤的分類:', cancer['target_names'])
    print('腫瘤的特徵:', cancer['feature_names'])
    X, y = cancer.data, cancer.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=38)
    print('------------------')
    print('訓練集數據形態:', X_train.shape)
    print('測試集數據形態:', X_test.shape)
    print('------------------')
    gnb = GaussianNB()
    gnb.fit(X_train, y_train)
    print('----------------')
    print('訓練集得分:{:.3f}'.format(gnb.score(X_train, y_train)))
    print('測試集得分:{:.3f}'.format(gnb.score(X_test, y_test)))
    print('----------------')

運行結果

--------------
dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename'])
---------------------
腫瘤的分類: ['malignant' 'benign']
腫瘤的特徵: ['mean radius' 'mean texture' 'mean perimeter' 'mean area'
 'mean smoothness' 'mean compactness' 'mean concavity'
 'mean concave points' 'mean symmetry' 'mean fractal dimension'
 'radius error' 'texture error' 'perimeter error' 'area error'
 'smoothness error' 'compactness error' 'concavity error'
 'concave points error' 'symmetry error' 'fractal dimension error'
 'worst radius' 'worst texture' 'worst perimeter' 'worst area'
 'worst smoothness' 'worst compactness' 'worst concavity'
 'worst concave points' 'worst symmetry' 'worst fractal dimension']
------------------
訓練集數據形態: (426, 30)
測試集數據形態: (143, 30)
------------------
----------------
訓練集得分:0.948
測試集得分:0.944
----------------
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章