除了在Matlab中使用PRTools工具箱中的svm算法,Python中一樣可以使用支持向量機(jī)做分類。因?yàn)镻ython中的sklearn庫也集成了SVM算法,本文的運(yùn)行環(huán)境是Pycharm。
一、導(dǎo)入sklearn算法包
Scikit-Learn庫已經(jīng)實(shí)現(xiàn)了所有基本機(jī)器學(xué)習(xí)的算法,具體使用詳見官方文檔說明:http://scikit-learn.org/stable/auto_examples/index.html。
skleran中集成了許多算法,其導(dǎo)入包的方式如下所示,
邏輯回歸:from sklearn.linear_model import LogisticRegression
樸素貝葉斯:from sklearn.naive_bayes import GaussianNB
K-近鄰:from sklearn.neighbors import KNeighborsClassifier
決策樹:from sklearn.tree import DecisionTreeClassifier
支持向量機(jī):from sklearn import svm
二、sklearn中svc的使用
(1)使用numpy中的loadtxt讀入數(shù)據(jù)文件
loadtxt()的使用方法:
fname:文件路徑。eg:C:/Dataset/iris.txt。
dtype:數(shù)據(jù)類型。eg:float、str等。
delimiter:分隔符。eg:‘,'。
converters:將數(shù)據(jù)列與轉(zhuǎn)換函數(shù)進(jìn)行映射的字典。eg:{1:fun},含義是將第2列對應(yīng)轉(zhuǎn)換函數(shù)進(jìn)行轉(zhuǎn)換。
usecols:選取數(shù)據(jù)的列。
以Iris蘭花數(shù)據(jù)集為例子:
由于從UCI數(shù)據(jù)庫中下載的Iris原始數(shù)據(jù)集的樣子是這樣的,前四列為特征列,第五列為類別列,分別有三種類別Iris-setosa, Iris-versicolor, Iris-virginica。
當(dāng)使用numpy中的loadtxt函數(shù)導(dǎo)入該數(shù)據(jù)集時,假設(shè)數(shù)據(jù)類型dtype為浮點(diǎn)型,但是很明顯第五列的數(shù)據(jù)類型并不是浮點(diǎn)型。
因此我們要額外做一個工作,即通過loadtxt()函數(shù)中的converters參數(shù)將第五列通過轉(zhuǎn)換函數(shù)映射成浮點(diǎn)類型的數(shù)據(jù)。
首先,我們要寫出一個轉(zhuǎn)換函數(shù):
def iris_type(s): it = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} return it[s]
接下來讀入數(shù)據(jù),converters={4: iris_type}中“4”指的是第5列:
path = u'D:/f盤/python/學(xué)習(xí)/iris.data' # 數(shù)據(jù)文件路徑 data = np.loadtxt(path, dtype=float, delimiter=',', converters={4: iris_type})
讀入結(jié)果:
(2)將Iris分為訓(xùn)練集與測試集
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)
1.split(數(shù)據(jù),分割位置,軸=1(水平分割) or 0(垂直分割))。
2.x = x[:, :2]是為方便后期畫圖更直觀,故只取了前兩列特征值向量訓(xùn)練。
3. sklearn.model_selection.train_test_split隨機(jī)劃分訓(xùn)練集與測試集。train_test_split(train_data,train_target,test_size=數(shù)字, random_state=0)
參數(shù)解釋:
- train_data:所要劃分的樣本特征集
- train_target:所要劃分的樣本結(jié)果
- test_size:樣本占比,如果是整數(shù)的話就是樣本的數(shù)量
- random_state:是隨機(jī)數(shù)的種子。
隨機(jī)數(shù)種子:其實(shí)就是該組隨機(jī)數(shù)的編號,在需要重復(fù)試驗(yàn)的時候,保證得到一組一樣的隨機(jī)數(shù)。比如你每次都填1,其他參數(shù)一樣的情況下你得到的隨機(jī)數(shù)組是一樣的。但填0或不填,每次都會不一樣。隨機(jī)數(shù)的產(chǎn)生取決于種子,隨機(jī)數(shù)和種子之間的關(guān)系遵從以下兩個規(guī)則:種子不同,產(chǎn)生不同的隨機(jī)數(shù);種子相同,即使實(shí)例不同也產(chǎn)生相同的隨機(jī)數(shù)。
(3)訓(xùn)練svm分類器
# 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())
kernel='linear'時,為線性核,C越大分類效果越好,但有可能會過擬合(defaul C=1)。
kernel='rbf'時(default),為高斯核,gamma值越小,分類界面越連續(xù);gamma值越大,分類界面越“散”,分類效果越好,但有可能會過擬合。
decision_function_shape='ovr'時,為one v rest,即一個類別與其他類別進(jìn)行劃分,
decision_function_shape='ovo'時,為one v one,即將類別兩兩之間進(jìn)行劃分,用二分類的方法模擬多分類的結(jié)果。
(4)計(jì)算svc分類器的準(zhǔn)確率
print clf.score(x_train, y_train) # 精度 y_hat = clf.predict(x_train) show_accuracy(y_hat, y_train, '訓(xùn)練集') print clf.score(x_test, y_test) y_hat = clf.predict(x_test) show_accuracy(y_hat, y_test, '測試集')
結(jié)果為:
如果想查看決策函數(shù),可以通過decision_function()實(shí)現(xiàn)
print 'decision_function:\n', clf.decision_function(x_train) print '\npredict:\n', clf.predict(x_train)
結(jié)果為:
decision_function中每一列的值代表距離各類別的距離。
(5)繪制圖像
1.確定坐標(biāo)軸范圍,x,y軸分別表示兩個特征
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] # 生成網(wǎng)格采樣點(diǎn) grid_test = np.stack((x1.flat, x2.flat), axis=1) # 測試點(diǎn) # print 'grid_test = \n', grid_testgrid_hat = clf.predict(grid_test) # 預(yù)測分類值grid_hat = grid_hat.reshape(x1.shape) # 使之與輸入的形狀相同
這里用到了mgrid()函數(shù),該函數(shù)的作用這里簡單介紹一下:
?假設(shè)假設(shè)目標(biāo)函數(shù)F(x,y)=x+y。x軸范圍1~3,y軸范圍4~6,當(dāng)繪制圖像時主要分四步進(jìn)行:
【step1:x擴(kuò)展】(朝右擴(kuò)展):
??????? [1 1 1]
[2 2 2]
[3 3 3]
【step2:y擴(kuò)展】(朝下擴(kuò)展):
[4 5 6]
[4 5 6]
[4 5 6]
【step3:定位(xi,yi)】:
[(1,4) (1,5) (1,6)]
[(2,4) (2,5) (2,6)]
[(3,4) (3,5) (3,6)]
【step4:將(xi,yi)代入F(x,y)=x+y】
因此這里x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j]后的結(jié)果為:
再通過stack()函數(shù),axis=1,生成測試點(diǎn)
2.指定默認(rèn)字體
mpl.rcParams['font.sans-serif'] = [u'SimHei'] mpl.rcParams['axes.unicode_minus'] = False
3.繪制
cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF']) cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b']) plt.pcolormesh(x1, x2, 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) # 圈中測試集樣本 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.grid() plt.show()
pcolormesh(x,y,z,cmap)這里參數(shù)代入x1,x2,grid_hat,cmap=cm_light繪制的是背景。
?scatter中edgecolors是指描繪點(diǎn)的邊緣色彩,s指描繪點(diǎn)的大小,cmap指點(diǎn)的顏色。
xlim指圖的邊界。
最終結(jié)果為:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
