Python支援向量機(SVM)例項
SVM(Support Vector Machine)指的是支援向量機,是常見的一種判別方法。在機器學習領域,是一個有監督的學習模型,通常用來進行模式識別、分類以及迴歸分析。
Matlab中有林智仁編寫的libsvm工具包可以很好地進行進行SVM訓練。Python中我們有sklearn工具包來進行機器學習演算法訓練,Scikit-Learn庫已經實現了所有基本機器學習的演算法。
由於從UCI資料庫中下載的Iris原始資料集的樣子是這樣的,前四列為特徵列,第五列為類別列,分別有三種類別Iris-setosa, Iris-versicolor, Iris-virginica。
需要使用numpy對其進行分割操作。
下載iris.data即可。
Python3程式碼:
from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import colors
from sklearn.model_selection import train_test_split
def iris_type(s):
it = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica' : 2}
return it[s]
path = 'C:\\Users\\dell\\desktop\\iris.data' # 資料檔案路徑
data = np.loadtxt(path, dtype=float, delimiter=',', converters={4: iris_type})
x, y = np.split(data, (4,), axis=1)
x = x[:, :2]
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6)
# clf = svm.SVC(C=0.1, kernel='linear', decision_function_shape='ovr')
clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr')
clf.fit(x_train, y_train.ravel())
print(clf.score(x_train, y_train)) # 精度
y_hat = clf.predict(x_train)
print(clf.score(x_test, y_test))
y_hat2 = clf.predict(x_test)
x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的範圍
x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的範圍
x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j] # 生成網格取樣點
grid_test = np.stack((x1.flat, x2.flat), axis=1) # 測試點
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
grid_hat = clf.predict(grid_test) # 預測分類值
grid_hat = grid_hat.reshape(x1.shape) # 使之與輸入的形狀相同
alpha = 0.5
plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light) # 預測值的顯示
plt.plot(x[:, 0], x[:, 1], 'o', alpha=alpha, color='blue', markeredgecolor='k')
plt.scatter(x_test[:, 0], x_test[:, 1], s=120, facecolors='none', zorder=10) # 圈中測試集樣本
plt.xlabel(u'花萼長度', fontsize=13)
plt.ylabel(u'花萼寬度', fontsize=13)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.title(u'SVM分類', fontsize=15)
plt.show()
split(資料,分割位置,軸=1(水平分割) or 0(垂直分割))。
x = x[:, :2]是為方便後期畫圖更直觀,故只取了前兩列特徵值向量訓練。
sklearn.model_selection.train_test_split隨機劃分訓練集與測試集。train_test_split(train_data,train_target,test_size=數字, random_state=0)
引數解釋:
train_data:所要劃分的樣本特徵集
train_target:所要劃分的樣本結果
test_size:樣本佔比,如果是整數的話就是樣本的數量
random_state:是隨機數的種子。
隨機數種子:其實就是該組隨機數的編號,在需要重複試驗的時候,保證得到一組一樣的隨機數。比如你每次都填1,其他引數一樣的情況下你得到的隨機陣列是一樣的。但填0或不填,每次都會不一樣。隨機數的產生取決於種子,隨機數和種子之間的關係遵從以下兩個規則:種子不同,產生不同的隨機數;種子相同,即使例項不同也產生相同的隨機數。
kernel=’linear’時,為線性核,C越大分類效果越好,但有可能會過擬合(defaul C=1)。
kernel=’rbf’時(default),為高斯核,gamma值越小,分類介面越連續;gamma值越大,分類介面越“散”,分類效果越好,但有可能會過擬合。
線性分類結果:
rbf核函式分類結果:
更多python及機器學習內容請訪問omegaxyz.com