朴素貝葉斯對鳶尾花數據集進行分類


注:本人純粹為了練手熟悉各個方法的用法

使用高斯朴素貝葉斯對鳶尾花數據進行分類

代碼:

 1 # 通過朴素貝葉斯對鳶尾花數據進行分類
 2 
 3 from sklearn import datasets
 4 from sklearn.model_selection import train_test_split
 5 from sklearn.naive_bayes import MultinomialNB, GaussianNB
 6 import matplotlib.pyplot as plt
 7 import numpy as np
 8 import matplotlib as mpl
 9 from sklearn.preprocessing import StandardScaler
10 from sklearn.pipeline import Pipeline
11 
12 iris = datasets.load_iris() # 加載鳶尾花數據
13 iris_x = iris.data  # 獲取數據
14 # print(iris_x)
15 iris_x = iris_x[:, :2]  # 取前兩個特征值
16 # print(iris_x)
17 iris_y = iris.target    # 0, 1, 2
18 x_train, x_test, y_train, y_test = train_test_split(iris_x, iris_y, test_size=0.75, random_state=1) # 對數據進行分類 一部分最為訓練一部分作為測試
19 # clf = GaussianNB()
20 # ir = clf.fit(x_train, y_train)
21 clf = Pipeline([
22         ('sc', StandardScaler()),
23         ('clf', GaussianNB())])     # 管道這個沒深入理解 所以不知所以然
24 ir = clf.fit(x_train, y_train.ravel())  # 利用訓練數據進行擬合
25 
26 # 畫圖:   
27 x1_max, x1_min = max(x_test[:, 0]), min(x_test[:, 0])   # 取0列特征得最大最小值
28 x2_max, x2_min = max(x_test[:, 1]), min(x_test[:, 1])   # 取1列特征得最大最小值
29 t1 = np.linspace(x1_min, x1_max, 500)   # 生成500個測試點
30 t2 = np.linspace(x2_min, x2_max, 500)   
31 x1, x2 = np.meshgrid(t1, t2)  # 生成網格采樣點
32 x_test1 = np.stack((x1.flat, x2.flat), axis=1)
33 y_hat = ir.predict(x_test1) # 預測
34 mpl.rcParams['font.sans-serif'] = [u'simHei']   # 識別中文保證不亂嗎
35 mpl.rcParams['axes.unicode_minus'] = False
36 cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF']) # 測試分類的顏色
37 cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])    # 樣本點的顏色
38 plt.figure(facecolor='w')
39 plt.pcolormesh(x1, x2, y_hat.reshape(x1.shape), cmap=cm_light)  # y_hat  25000個樣本點的畫圖,
40 plt.scatter(x_test[:, 0], x_test[:, 1], edgecolors='k', s=50, c=y_test, cmap=cm_dark)   # 測試數據的真實的樣本點(散點) 參數自行百度
41 plt.xlabel(u'花萼長度', fontsize=14)
42 plt.ylabel(u'花萼寬度', fontsize=14)
43 plt.title(u'GaussianNB對鳶尾花數據的分類結果', fontsize=18)
44 plt.grid(True)
45 plt.xlim(x1_min, x1_max)
46 plt.ylim(x2_min, x2_max)
47 plt.show()
48 y_hat1 = ir.predict(x_test)
49 result = y_hat1 == y_test
50 print(result)
51 acc = np.mean(result)
52 print('准確度: %.2f%%' % (100 * acc))

圖片顯示:

正確率:

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM