Python----Kernel SVM


什么是kernel

Kernel的其實就是將向量feature轉換與點積運算合並后的運算,如下,

 

概念上很簡單,但是並不是所有的feature轉換函數都有kernel的特性。

常見kernel

常見kernel有多項式,高斯和線性,各有利弊。

kernel SVM

在非線性的SVM算法中,如何將一組線性不可分的數據,利用從低維到高維的投射,使它變成在高維空間中線性可分的數據。將已經分割好的數據,投射回到原先的空間,及低維空間。

(1)一維空間

 

一維空間中的線性分類,找是否從在一個點,使一邊都是紅,一邊都是綠,顯然這樣的線性分類器是不存在的。所以將數據投射到二維的空間里,例如:

                

 

(2)二維

投射,保持X1軸和X2軸不變,增加第三個軸,將X1,X2兩個點投射到一個三維空間里,前兩個維度不變,第三個z與X1,X2有關系;在新的三維空間里,綠色和紅色就變成了線性可分。線性可分在不是二維的空間中,有一個超平面,將兩組數據分開。

(3)反向投射

三維空間中找到的分割的平面,與數據本身結構,根據這兩個信息,找出在原來數據空間二維空間中的分類界線。

核技巧在非線性SVM的應用

 

(1)非線性SVM最常用的核方程:

假設只有一個自變量X,而l已定,看成一個關於X的函數,此時的函數在空間中的形態

      l點就是(0,0)這個點

 

利用高斯核函數算出分類函數:

綠點所對應的高斯核函數的值,坐落在白色圈的里面(小山上);紅點所對應的高斯核函數的值,坐落在周圍深藍色圖像上。做出的投影圖。

σ:控制圈的半徑(大小)

     

(2)較復雜的二維

此時的核函數

 

實例

數據集

 

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, [2,3]].values
y = dataset.iloc[:, 4].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)

# Fitting Logistic Regression to the Training set
#訓練集擬合SVM的分類器
#從模型的標准庫中導入需要的類
from sklearn.svm import SVC
#創建分類器
classifier = SVC(kernel = 'rbf', random_state = 0)#rbf運用了高斯核
#運用訓練集擬合分類器
classifier.fit(X_train, y_train)

# Predicting the Test set results
#運用擬合好的分類器預測測試集的結果情況
#創建變量(包含預測出的結果)
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
#通過測試的結果評估分類器的性能
#用混淆矩陣,評估性能
#65,24對應着正確的預測個數;8,3對應錯誤預測個數;擬合好的分類器正確率:(65+24)/100
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Visualising the Training set results
#在圖像看分類結果
from matplotlib.colors import ListedColormap
#創建變量
X_set, y_set = X_train, y_train
#x1,x2對應圖中的像素;最小值-1,最大值+1,-1和+1是為了讓圖的邊緣留白,像素之間的距離0.01;第一行年齡,第二行年收入
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
#將不同像素點塗色,用擬合好的分類器預測每個點所屬的分類並且根據分類值塗色
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
#標注最大值及最小值
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
#為了滑出實際觀測的點(黃、藍)
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('orange', 'blue'))(i), label = j)
plt.title('Classifier (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
#顯示不同的點對應的值
plt.legend()
#生成圖像
plt.show()

# Visualising the Test set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('orange', 'blue'))(i), label = j)
plt.title('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

訓練集圖像顯示結果:

 

測試集圖像顯示結果:

 


免責聲明!

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



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