データマイニングの学習 - 単純ベイジアン分類アルゴリズム 獣のがんとの実際の戦闘

目次

1. 単純ベイズ分類アルゴリズムに関する統計的知識

2. 単純ベイズ分類器

3. 単純ベイズ分類器の Python 実装

(1) インストールする必要がある sklearn ライブラリを呼び出します。

(2) 例1(データの分布とデータ形式を確認する)

 (3) 例 2 (乳がんデータセット全体を単純ベイジアン分類アルゴリズムで解析し、腫瘍の良性か悪性かを判断するモデルを取得するようにトレーニングする)

1. データセットの特徴とラベルを表示する

 2. train_test_split() によってデータセット全体をトレーニングセットとテストセットに分割し、データフォームを表示します

 3. ガウス単純ベイジアン分類アルゴリズムを使用してトレーニング データセットを適合させます。

 4. 完全なガウスナイーブベイジアン分類アルゴリズムトレーニング乳がんデータセットコード


1. 単純ベイズ分類アルゴリズムに関する統計的知識

  (1) 条件付き独立式:P(X,Y)=P(X)*P(Y)

(2) 条件付き確率の式:P(X|Y)=P(X,Y)/P(Y)、P(Y|X)=P(X,Y)/P(X)

  (3) 合計確率の計算式:

 

  (4) ベイズの公式:

2. 単純ベイズ分類器

基本的な考え方:分類されるサンプルが特定の確率分布に従うと仮定すると、まず分類されたサンプル データを通じて未分類サンプルの事前確率を推定し、次にベイズの公式を使用して未分類サンプルの事後確率を計算します (つまり、分類されていないサンプルの事後確率を予測します)。 (サンプルが特定のクラスに属する確率)、最終的に最大の事後確率を持つカテゴリを、未分類のサンプルが属するカテゴリとして選択します。

3. 単純ベイズ分類器の Python 実装

(1) インストールする必要がある sklearn ライブラリを呼び出します。

データ セットの説明: sklearn ライブラリに付属する乳がんデータ セットを使用します (乳がん患者データ: 合計 569 個のインスタンス (良性インスタンス 212 個と悪性インスタンス 357 個を含む)。各インスタンスには 30 個の属性値が含まれており、各属性値は細針です。乳房のしこりから撮影された吸引デジタル画像。10 個の特徴の平均と分散が含まれます。これらの 10 個の特徴には、半径、周長、面積などが含まれます)。

(2) 例1(データの分布とデータ形式を確認する)

コード例:

import pandas as pd
from sklearn.datasets import load_breast_cancer

cancer=load_breast_cancer()
cancerdf=pd.DataFrame(cancer.data,columns=cancer.feature_names)
print(cancerdf.head()) # head()默认显示前5行数据

  実行結果 (データの最初の 5 行を表示):

 (3) 例 2 (乳がんデータセット全体を単純ベイジアン分類アルゴリズムで解析し、腫瘍の良性か悪性かを判断するモデルを取得するようにトレーニングする)

1. データセットの特徴とラベルを表示する

コード:

import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix
from matplotlib import pyplot as plt
import seaborn as sns

cancer=load_breast_cancer()
print("肿瘤的分类:",cancer['target_names'])
print("肿瘤的分类:",cancer['feature_names'])

操作結果:

 2. train_test_split() によってデータセット全体をトレーニングセットとテストセットに分割し、データフォームを表示します

コード:

import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix
from matplotlib import pyplot as plt
import seaborn as sns
cancer=load_breast_cancer()
x,y=cancer.data,cancer.target
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=3)
print(x_train.shape)# 查看训练集数据形态
print(x_test.shape)# 查看测试集数据形态

操作結果:

 3. ガウス単純ベイジアン分類アルゴリズムを使用してトレーニング データセットを適合させます。

コード:

clf=GaussianNB()
clf.fit(x_train,y_train)#对训练集进行拟合
print(clf.score(x_train,y_train))
print(clf.score(x_test,y_test))

操作結果:

(ご覧のとおり、テスト セットの精度は 0.947 と高いです)

 4. 混同行列を描く

コード:

pred=clf.predict(x_test)
cm=confusion_matrix(pred,y_test)
plt.figure(dpi=300)
sns.heatmap(cm,cmap=sns.color_palette("Blues"),annot=True,fmt='d')
plt.xlabel('实际类别')
plt.ylabel('预测类别')
plt.show()    

操作結果:

 4. 完全なガウスナイーブベイジアン分類アルゴリズムトレーニング乳がんデータセットコード

次のように、上記のコードをカプセル化し、混同行列を視覚化する関数コードを追加して、完全なトレーニング プロセスのコードを取得します。

(次のコードはブロガーが個人的なニーズに基づいて作成したものであり、個人的なニーズに応じて調整することもできます)

import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix
from matplotlib import pyplot as plt
import seaborn as sns

#训练模型函数
def model_fit(x_train,y_train,x_test,y_test):
    clf=GaussianNB()
    clf.fit(x_train,y_train)#对训练集进行拟合
    print(clf.score(x_train,y_train))
    print(clf.score(x_test,y_test))
    pred=clf.predict(x_test)
    cm=confusion_matrix(pred,y_test)
    return cm

#混淆矩阵可视化
def matplotlib_show(cm):
    plt.figure(dpi=100)#设置窗口大小(分辨率)
    plt.title('Confusion Matrix')

    labels = ['a', 'b', 'c', 'd']
    tick_marks = np.arange(len(labels))
    plt.xticks(tick_marks, labels)
    plt.yticks(tick_marks, labels)
    sns.heatmap(cm, cmap=sns.color_palette("Blues"), annot=True, fmt='d')
    plt.ylabel('real_type')#x坐标为实际类别
    plt.xlabel('pred_type')#y坐标为预测类别
    plt.show()

if __name__ == '__main__':
    cancer = load_breast_cancer()
    x, y = cancer.data, cancer.target
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=3)
    cm=model_fit(x_train,y_train,x_test,y_test)
    matplotlib_show(cm)

操作結果:

 

 

おすすめ

転載: blog.csdn.net/weixin_52135595/article/details/126689536