15 SVM - 程式碼案例二 - 鳶尾花資料不同分類器效果比較
阿新 • • 發佈:2018-12-07
SVM的章節已經講完,具體內容請參考:《01 SVM - 大綱》
《14 SVM - 程式碼案例一 - 鳶尾花資料SVM分類》
回顧案例一中的標頭檔案:
import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import warnings from sklearn import svm#svm匯入 from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.exceptions import ChangedBehaviorWarning
案例二 - 鳶尾花資料不同分類器效果比較
常規操作:
1、標頭檔案引入SVM相關的包
2、防止中文亂碼
3、去警告
4、讀取資料
5、資料分割訓練集和測試集 6:4
import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import warnings from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression,RidgeClassifier from sklearn.neighbors import KNeighborsClassifier ## 設定屬性防止中文亂碼 mpl.rcParams['font.sans-serif'] = [u'SimHei'] mpl.rcParams['axes.unicode_minus'] = False warnings.filterwarnings('ignore', category=ChangedBehaviorWarning) ## 讀取資料 # 'sepal length', 'sepal width', 'petal length', 'petal width' iris_feature = u'花萼長度', u'花萼寬度', u'花瓣長度', u'花瓣寬度' path = './datas/iris.data' # 資料檔案路徑 data = pd.read_csv(path, header=None) x, y = data[list(range(4))], data[4] y = pd.Categorical(y).codes #把文字資料進行編碼,比如a b c編碼為 0 1 2 x = x[[0, 1]] ## 資料分割 x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=28, train_size=0.6)
資料SVM分類器構建:
svm = SVC(C=1, kernel='linear')
## 模型訓練
svm.fit(x_train, y_train)
svm.intercept_
Linear分類器構建:
RidgeClassifier(): ridge是為了解決特徵大於樣本,而導致分類效果較差的情況,而提出的。
svm有一個重要的瓶頸——當特徵數大於樣本數的時候,效果變差。
lr = LogisticRegression() rc = RidgeClassifier() knn = KNeighborsClassifier() ## 模型訓練 lr.fit(x_train, y_train) rc.fit(x_train, y_train) knn.fit(x_train, y_train)
效果評估:
svm_score1 = accuracy_score(y_train, svm.predict(x_train))
svm_score2 = accuracy_score(y_test, svm.predict(x_test))
lr_score1 = accuracy_score(y_train, lr.predict(x_train))
lr_score2 = accuracy_score(y_test, lr.predict(x_test))
rc_score1 = accuracy_score(y_train, rc.predict(x_train))
rc_score2 = accuracy_score(y_test, rc.predict(x_test))
knn_score1 = accuracy_score(y_train, knn.predict(x_train))
knn_score2 = accuracy_score(y_test, knn.predict(x_test))
畫圖 - 鳶尾花資料不同分類器準確率比較:
x_tmp = [0,1,2,3]
y_score1 = [svm_score1, lr_score1, rc_score1, knn_score1]
y_score2 = [svm_score2, lr_score2, rc_score2, knn_score2]
plt.figure(facecolor='w')
plt.plot(x_tmp, y_score1, 'r-', lw=2, label=u'訓練集準確率')
plt.plot(x_tmp, y_score2, 'g-', lw=2, label=u'測試集準確率')
plt.xlim(0, 3)
plt.ylim(np.min((np.min(y_score1), np.min(y_score2)))*0.9, np.max((np.max(y_score1), np.max(y_score2)))*1.1)
plt.legend(loc = 'lower right')
plt.title(u'鳶尾花資料不同分類器準確率比較', fontsize=16)
plt.xticks(x_tmp, [u'SVM', u'Logistic', u'Ridge', u'KNN'], rotation=0)
plt.grid(b=True)
plt.show()
畫圖比較分類結果:
N = 500
x1_min, x2_min = x.min()
x1_max, x2_max = x.max()
t1 = np.linspace(x1_min, x1_max, N)
t2 = np.linspace(x2_min, x2_max, N)
x1, x2 = np.meshgrid(t1, t2) # 生成網格取樣點
grid_show = np.dstack((x1.flat, x2.flat))[0] # 測試點
獲取各個不同演算法的測試值:
svm_grid_hat = svm.predict(grid_show)
svm_grid_hat = svm_grid_hat.reshape(x1.shape) # 使之與輸入的形狀相同
lr_grid_hat = lr.predict(grid_show)
lr_grid_hat = lr_grid_hat.reshape(x1.shape) # 使之與輸入的形狀相同
rc_grid_hat = rc.predict(grid_show)
rc_grid_hat = rc_grid_hat.reshape(x1.shape) # 使之與輸入的形狀相同
knn_grid_hat = knn.predict(grid_show)
knn_grid_hat = knn_grid_hat.reshape(x1.shape) # 使之與輸入的形狀相同
畫圖:
cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
plt.figure(facecolor='w', figsize=(14,7))
1、鳶尾花SVM特徵分類:
plt.subplot(221)
## 區域圖
plt.pcolormesh(x1, x2, svm_grid_hat, cmap=cm_light)
## 所以樣本點
plt.scatter(x[0], x[1], c=y, edgecolors='k', s=50, cmap=cm_dark) # 樣本
## 測試資料集
plt.scatter(x_test[0], x_test[1], s=120, facecolors='none', zorder=10) # 圈中測試集樣本
## lable列表
plt.xlabel(iris_feature[0], fontsize=13)
plt.ylabel(iris_feature[1], fontsize=13)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.title(u'鳶尾花SVM特徵分類', fontsize=16)
plt.grid(b=True, ls=':')
plt.tight_layout(pad=1.5)
2、鳶尾花Logistic特徵分類:
plt.subplot(222)
## 區域圖
plt.pcolormesh(x1, x2, lr_grid_hat, cmap=cm_light)
## 所以樣本點
plt.scatter(x[0], x[1], c=y, edgecolors='k', s=50, cmap=cm_dark) # 樣本
## 測試資料集
plt.scatter(x_test[0], x_test[1], s=120, facecolors='none', zorder=10) # 圈中測試集樣本
## lable列表
plt.xlabel(iris_feature[0], fontsize=13)
plt.ylabel(iris_feature[1], fontsize=13)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.title(u'鳶尾花Logistic特徵分類', fontsize=16)
plt.grid(b=True, ls=':')
plt.tight_layout(pad=1.5)
3、鳶尾花Ridge特徵分類:
plt.subplot(223)
## 區域圖
plt.pcolormesh(x1, x2, rc_grid_hat, cmap=cm_light)
## 所以樣本點
plt.scatter(x[0], x[1], c=y, edgecolors='k', s=50, cmap=cm_dark) # 樣本
## 測試資料集
plt.scatter(x_test[0], x_test[1], s=120, facecolors='none', zorder=10) # 圈中測試集樣本
## lable列表
plt.xlabel(iris_feature[0], fontsize=13)
plt.ylabel(iris_feature[1], fontsize=13)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.title(u'鳶尾花Ridge特徵分類', fontsize=16)
plt.grid(b=True, ls=':')
plt.tight_layout(pad=1.5)
4、鳶尾花KNN特徵分類:
plt.subplot(224)
## 區域圖
plt.pcolormesh(x1, x2, knn_grid_hat, cmap=cm_light)
## 所以樣本點
plt.scatter(x[0], x[1], c=y, edgecolors='k', s=50, cmap=cm_dark) # 樣本
## 測試資料集
plt.scatter(x_test[0], x_test[1], s=120, facecolors='none', zorder=10) # 圈中測試集樣本
## lable列表
plt.xlabel(iris_feature[0], fontsize=13)
plt.ylabel(iris_feature[1], fontsize=13)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.title(u'鳶尾花KNN特徵分類', fontsize=16)
plt.grid(b=True, ls=':')
plt.tight_layout(pad=1.5)
plt.show()