Python實現鳶尾花數據集分類問題——基於skearn的SVM
代碼如下:
1 # !/usr/bin/env python 2 # encoding: utf-8 3 __author__ = 'Xiaolin Shen' 4 from sklearn import svm 5 import numpy as np 6 from sklearn import model_selection 7 import matplotlib.pyplot as plt 8 import matplotlib as mpl 9 from matplotlib import colors 10 11 12 13 # 當使用numpy中的loadtxt函數導入該數據集時,假設數據類型dtype為浮點型,但是很明顯數據集的第五列的數據類型是字符串並不是浮點型。 14 # 因此需要額外做一個工作,即通過loadtxt()函數中的converters參數將第五列通過轉換函數映射成浮點類型的數據。 15 # 首先,我們要寫出一個轉換函數: 16 # 定義一個函數,將不同類別標簽與數字相對應 17 def iris_type(s): 18 class_label={b'Iris-setosa':0,b'Iris-versicolor':1,b'Iris-virginica':2} 19 return class_label[s] 20 21 #(1)使用numpy中的loadtxt讀入數據文件 22 filepath='IRIS_dataset.txt' # 數據文件路徑 23 data=np.loadtxt(filepath,dtype=float,delimiter=',',converters={4:iris_type}) 24 #以上4個參數中分別表示: 25 #filepath :文件路徑。eg:C:/Dataset/iris.txt。 26 #dtype=float :數據類型。eg:float、str等。 27 #delimiter=',' :數據以什么分割符號分割。eg:‘,’。 28 #converters={4:iris_type} :對某一列數據(第四列)進行某種類型的轉換,將數據列與轉換函數進行映射的字典。eg:{1:fun},含義是將第2列對應轉換函數進行轉換。 29 # converters={4: iris_type}中“4”指的是第5列。 30 31 # print(data) 32 #讀入結果示例為: 33 # [[ 5.1 3.5 1.4 0.2 0. ] 34 # [ 4.9 3. 1.4 0.2 0. ] 35 # [ 4.7 3.2 1.3 0.2 0. ] 36 # [ 4.6 3.1 1.5 0.2 0. ] 37 # [ 5. 3.6 1.4 0.2 0. ]] 38 39 40 41 #(2)將原始數據集划分成訓練集和測試集 42 X ,y=np.split(data,(4,),axis=1) #np.split 按照列(axis=1)進行分割,從第四列開始往后的作為y 數據,之前的作為X 數據。函數 split(數據,分割位置,軸=1(水平分割) or 0(垂直分割))。 43 x=X[:,0:2] #在 X中取前兩列作為特征(為了后期的可視化畫圖更加直觀,故只取前兩列特征值向量進行訓練) 44 x_train,x_test,y_train,y_test=model_selection.train_test_split(x,y,random_state=1,test_size=0.3) 45 # 用train_test_split將數據隨機分為訓練集和測試集,測試集占總數據的30%(test_size=0.3),random_state是隨機數種子 46 # 參數解釋: 47 # x:train_data:所要划分的樣本特征集。 48 # y:train_target:所要划分的樣本結果。 49 # test_size:樣本占比,如果是整數的話就是樣本的數量。 50 # random_state:是隨機數的種子。 51 # (隨機數種子:其實就是該組隨機數的編號,在需要重復試驗的時候,保證得到一組一樣的隨機數。比如你每次都填1,其他參數一樣的情況下你得到的隨機數組是一樣的。但填0或不填,每次都會不一樣。 52 # 隨機數的產生取決於種子,隨機數和種子之間的關系遵從以下兩個規則:種子不同,產生不同的隨機數;種子相同,即使實例不同也產生相同的隨機數。) 53 54 55 #(3)搭建模型,訓練SVM分類器 56 # classifier=svm.SVC(kernel='linear',gamma=0.1,decision_function_shape='ovo',C=0.1) 57 # kernel='linear'時,為線性核函數,C越大分類效果越好,但有可能會過擬合(defaul C=1)。 58 classifier=svm.SVC(kernel='rbf',gamma=0.1,decision_function_shape='ovo',C=0.8) 59 # kernel='rbf'(default)時,為高斯核函數,gamma值越小,分類界面越連續;gamma值越大,分類界面越“散”,分類效果越好,但有可能會過擬合。 60 # decision_function_shape='ovo'時,為one v one分類問題,即將類別兩兩之間進行划分,用二分類的方法模擬多分類的結果。 61 # decision_function_shape='ovr'時,為one v rest分類問題,即一個類別與其他類別進行划分。 62 #開始訓練 63 classifier.fit(x_train,y_train.ravel()) 64 #調用ravel()函數將矩陣轉變成一維數組 65 # (ravel()函數與flatten()的區別) 66 # 兩者所要實現的功能是一致的(將多維數組降為一維), 67 # 兩者的區別在於返回拷貝(copy)還是返回視圖(view), 68 # numpy.flatten() 返回一份拷貝,對拷貝所做的修改不會影響(reflects)原始矩陣, 69 # 而numpy.ravel()返回的是視圖(view),會影響(reflects)原始矩陣。 70 71 72 def show_accuracy(y_hat,y_train,str): 73 pass 74 75 #(4)計算svm分類器的准確率 76 print("SVM-輸出訓練集的准確率為:",classifier.score(x_train,y_train)) 77 y_hat=classifier.predict(x_train) 78 show_accuracy(y_hat,y_train,'訓練集') 79 print("SVM-輸出測試集的准確率為:",classifier.score(x_test,y_test)) 80 y_hat=classifier.predict(x_test) 81 show_accuracy(y_hat,y_test,'測試集') 82 # SVM-輸出訓練集的准確率為: 0.838095238095 83 # SVM-輸出測試集的准確率為: 0.777777777778 84 85 86 # 查看決策函數,可以通過decision_function()實現。decision_function中每一列的值代表距離各類別的距離。 87 # print('decision_function:\n', classifier.decision_function(x_train)) 88 print('\npredict:\n', classifier.predict(x_train)) 89 90 91 # (5)繪制圖像 92 # 1.確定坐標軸范圍,x,y軸分別表示兩個特征 93 x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的范圍 x[:, 0] ":"表示所有行,0表示第1列 94 x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的范圍 x[:, 0] ":"表示所有行,1表示第2列 95 x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j] # 生成網格采樣點(用meshgrid函數生成兩個網格矩陣X1和X2) 96 grid_test = np.stack((x1.flat, x2.flat), axis=1) # 測試點,再通過stack()函數,axis=1,生成測試點 97 # .flat 將矩陣轉變成一維數組 (與ravel()的區別:flatten:返回的是拷貝 98 99 print("grid_test = \n", grid_test) 100 # print("x = \n",x) 101 grid_hat = classifier.predict(grid_test) # 預測分類值 102 103 print("grid_hat = \n", grid_hat) 104 # print(x1.shape()) 105 grid_hat = grid_hat.reshape(x1.shape) # 使之與輸入的形狀相同 106 107 108 # 2.指定默認字體 109 mpl.rcParams['font.sans-serif'] = [u'SimHei'] 110 mpl.rcParams['axes.unicode_minus'] = False 111 112 # 3.繪制 113 cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF']) 114 cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b']) 115 116 alpha=0.5 117 118 plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light) # 預測值的顯示 119 # plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', s=50, cmap=cm_dark) # 樣本 120 plt.plot(x[:, 0], x[:, 1], 'o', alpha=alpha, color='blue', markeredgecolor='k') 121 plt.scatter(x_test[:, 0], x_test[:, 1], s=120, facecolors='none', zorder=10) # 圈中測試集樣本 122 plt.xlabel(u'花萼長度', fontsize=13) 123 plt.ylabel(u'花萼寬度', fontsize=13) 124 plt.xlim(x1_min, x1_max) 125 plt.ylim(x2_min, x2_max) 126 plt.title(u'鳶尾花SVM二特征分類', fontsize=15) 127 # plt.grid() 128 plt.show() 129 130 131 132 133 ''' 134 #輸出訓練集的准確率 135 print(classifier.score(x_train,x_test)) 136 137 #由於准確率表現不直觀,可以通過其他方式觀察結果。 138 139 #首先將原始結果與訓練集預測結果進行對比: 140 y_train_hat=classifier.predict(x_train) 141 y_train_1d=y_train.reshape((-1)) 142 comp=zip(y_train_1d,y_train_hat) #用zip把原始結果和預測結果放在一起。顯示如下: 143 print(list(comp)) 144 145 #同樣的,可以用訓練好的模型對測試集的數據進行預測: 146 print(classifier.score(x_test,y_test)) 147 y_test_hat=classifier.predict(x_test) 148 y_test_1d=y_test.reshape((-1)) 149 comp=zip(y_test_1d,y_test_hat) 150 print(list(comp)) 151 152 153 #還可以通過圖像進行可視化: 154 plt.figure() 155 plt.subplot(121) 156 plt.scatter(x_train[:,0],x_train[:,1],c=y_train.reshape((-1)),edgecolors='k',s=50) 157 plt.subplot(122) 158 plt.scatter(x_train[:,0],x_train[:,1],c=y_train_hat.reshape((-1)),edgecolors='k',s=50) 159 160 '''
程序運行結果:
數據可視化展示: