Python3中的支持向量機SVM的使用(有實例)


https://www.cnblogs.com/luyaoblog/p/6775342.html

首先,我們需要安裝scikit-learn

一、導入sklearn算法包 

在python中導入scikit-learn的方法:

scikit-learn里面已經實現了基本上所有基本機器學習的算法,具體的使用方法詳見官方文檔說明,http://scikit-learn.org/stable/auto_examples/index.html#support-vector-machines

scikit-learn中集成了許多算法,其導入包的方法如下所示:

邏輯回歸:from sklearn.linear_model import LogisticRegression

朴素貝葉斯:from sklearn.naive_bayes import GaussianNB

K-近鄰:from sklearn.neighbors import KNeighborsClassifier

決策樹:from sklearn.tree import DecisionTreeClassifier

支持向量機:from sklearn import svm

二、sklearn中svc的使用

(1)使用numpy中的loadtxt讀入數據文件

loadtxt()的使用方法:

def loadtxt(fname, dtype=float, comments='#', delimiter=None,
            converters=None, skiprows=0, usecols=None, unpack=False,
            ndmin=0, encoding='bytes', max_rows=None):

fname:文件路徑。eg:"G:\\SVM_Study\\iris.txt"

dtype:數據類型,如float,str等

delimiter:分隔符。eg','

converters:將數據列與轉換函數進行映射的字典。如:{1:fun}含義是將第二列對應轉換函數進行轉換。

usecols:選取數據的列。

以iris蘭花數據集為例子:

由於UCI數據庫中下載的Iris原始數據集的樣子是這樣的,前四列為特征列,第五列為類別列,分別有三種類別:Iris-setosa,Iris-versicolor,Iris-virginica

 

 當使用numpy中的loadtxt函數導入該數據集時,假設數據類型dtype為浮點型,但是很明顯第五列的數據類型並不是浮點型。

因此我們要二外做一個工作,即通過loadtxt()函數中的converters參數將第五列通過轉換函數映射成浮點類型的數據。

首先,我們要寫一個轉換函數:

def iris_type(s):
    it = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2}
    return it[s]

接下來,我們讀入數據,convetters={4:iris_type}中“4”指的是第五列。

textPath = "G:\\SVM_Study\\iris.txt"
data = np.loadtxt(textPath, dtype=float, delimiter=',', converters={4: iris_type})
print(data)

讀入結果:

 

 將Iris分為訓練集和測試集

 

 

完整代碼

from sklearn import svm
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import matplotlib as mpl

def iris_type(s):
    it = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2}
    return it[s]

def show_accuracy(a, b, tip):
    acc = a.ravel() == b.ravel()
    print(tip + "正確率:", np.mean(acc))

textPath = "G:\\SVM_Study\\iris.txt"
data = np.loadtxt(textPath, dtype=float, delimiter=',', converters={4: iris_type})
print(data)

x, y = np.split(data, (4,), axis=1)
print("y")
print(y)
# 所有行的前兩列
x = x[:, :2]
print("x")
print(x)
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6, test_size=0.4)
# 1. split(數據,分割位置,軸=1(水平分割) or 0(垂直分割))。
# 2. x = x[:, :2]是為方便后期畫圖更直觀,故只取了前兩列特征值向量訓練。
# 3. 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或不填,每次都會不一樣。隨機數的產生取決於種子,隨機數和種子之間的關系遵從以下兩個規則:種子不同,產生不同的隨機數;種子相同,即使實例不同也產生相同的隨機數。


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值越小,分類界面越連續;gamma值越大,分類界面越“散”,分類效果越好,但有可能會過擬合。
# decision_function_shape='ovr'時,為one v rest,即一個類別與其他類別進行划分,
# decision_function_shape='ovo'時,為one v one,即將類別兩兩之間進行划分,用二分類的方法模擬多分類的結果。

print(clf.score(x_train, y_train))
y_hat = clf.predict(x_train)
show_accuracy(y_hat, y_train, '訓練集')

print(clf.score(x_test, y_test))
y_hat = clf.predict(x_test)
show_accuracy(y_hat, y_test, '測試集')

print("decision_function:\n",clf.decision_function(x_train))
print("predict:\n",clf.predict(x_train))

# 第一列最大值,最小值
x1_min, x1_max = x[:, 0].min(), x[:, 0].max()

# 第二列最大值,最小值
x2_min, x2_max = x[:, 1].min(), x[:, 1].max()

x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j]
print("x1")
print(x1)
print("x2")
print(x2)
# 這里用到了mgrid()函數,該函數的作用這里簡單介紹一下:
# 假設假設目標函數F(x,y)=x+y。x軸范圍1~3,y軸范圍4~6,當繪制圖像時主要分四步進行:
# 【step1:x擴展】(朝右擴展):
# [1 1 1]
# [2 2 2]
# [3 3 3]
# 【step2:y擴展】(朝下擴展):
# [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
# [[4.3        4.3        4.3        ... 4.3        4.3        4.3       ]
#  [4.31809045 4.31809045 4.31809045 ... 4.31809045 4.31809045 4.31809045]
#  [4.3361809  4.3361809  4.3361809  ... 4.3361809  4.3361809  4.3361809 ]
#  ...
#  [7.8638191  7.8638191  7.8638191  ... 7.8638191  7.8638191  7.8638191 ]
#  [7.88190955 7.88190955 7.88190955 ... 7.88190955 7.88190955 7.88190955]
#  [7.9        7.9        7.9        ... 7.9        7.9        7.9       ]]

# x2
# [[2.        2.0120603 2.0241206 ... 4.3758794 4.3879397 4.4      ]
#  [2.        2.0120603 2.0241206 ... 4.3758794 4.3879397 4.4      ]
#  [2.        2.0120603 2.0241206 ... 4.3758794 4.3879397 4.4      ]
#  ...
#  [2.        2.0120603 2.0241206 ... 4.3758794 4.3879397 4.4      ]
#  [2.        2.0120603 2.0241206 ... 4.3758794 4.3879397 4.4      ]
#  [2.        2.0120603 2.0241206 ... 4.3758794 4.3879397 4.4      ]]

print("x1.flat")
print(x1.flat)
grid_test = np.stack((x1.flat, x2.flat), axis=1)
print("grid_test")
print(grid_test)

# 指定默認字體
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False

cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#FFA0FF'])
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[:, 0], x[:, 1], c=np.squeeze(y), edgecolors='k', s=50, cmap=cm_dark)
# plt.scatter(x_test[:, 0], x_test[:, 1], s=50, facecolors='none', zorder=10, cmap=cm_dark)
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()

# pcolormesh(x,y,z,cmap)這里參數代入x1,x2,grid_hat,cmap=cm_light繪制的是背景。
# scatter中edgecolors是指描繪點的邊緣色彩,s指描繪點的大小,cmap指點的顏色。
# xlim指圖的邊界。

得到的結果:

 


免責聲明!

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



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