支撐向量機 SVM
image
分類算法中,一般用一條邊界來決策分類。這條就是決策邊界。但是決策邊界在很多時候都可以是多條 。那一條比較合適呢?數學理論的基礎下,當只有分類邊界離最近的分類點最遠的時候,這條邊界是最優秀的。 如圖,有三條邊界,中間的一條是離兩個分類結果最遠的,也就是最合適的。而上邊和下邊這兩條我們稱為支撐向量。當margin值最大時,中間的決策邊界泛化能力就最強,也就是最合適。
推出公式
image
image
d最大,也就是margin最大
Soft Margin SVM
當邊界不明確時,或者分類元素有異常時,決策邊界就很難定義,上面用的方法可能會定義出泛化能力非常差的決策邊界。所以我們要在邊界中加入一定的容錯率,這個容錯率就是Soft Margin SVM
image
可以給容錯加上比例
image
Scikit-learn 線性SVM
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target
X = X[y<2,:2]
y = y[y<2]
#使用標準化同一量綱
from sklearn.preprocessing import StandardScaler
standardScaler = StandardScaler()
standardScaler.fit(X)
X_standard = standardScaler.transform(X)
#使用線性SVM算法
from sklearn.svm import LinearSVC
#超參數C,容錯比例
svc = LinearSVC(C=1e9)
svc.fit(X_standard, y)
svc.coef_
svc.intercept_
Scikit-learn 多項式
from sklearn.svm import SVC
def PolynomialKernelSVC(degree, C=1.0):
return Pipeline([
("std_scaler", StandardScaler()),
("kernelSVC", SVC(kernel="poly", degree=degree, C=C))#使用kernel="poly"核函數
])
poly_kernel_svc = PolynomialKernelSVC(degree=3)
poly_kernel_svc.fit(X, y)
Scikit-learn 高斯核函數
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
def RBFKernelSVC(gamma):
return Pipeline([
("std_scaler", StandardScaler()),
("svc", SVC(kernel="rbf", gamma=gamma))#rbf 高斯核函數,gamma值越大越容易過擬合
])
svc = RBFKernelSVC(gamma=1)
svc.fit(X, y)
Scikit-learn SVM解決回歸問題
類似分類問題,但是,支撐向量機包含越多元素越好,然后取向量機中間的邊界。epsilon是向量機和邊界的距離
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
boston = datasets.load_boston()
X = boston.data
y = boston.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=666)
from sklearn.svm import LinearSVR
from sklearn.svm import SVR
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
def StandardLinearSVR(epsilon=0.1):
return Pipeline([
('std_scaler', StandardScaler()),
('linearSVR', LinearSVR(epsilon=epsilon))#
])
svr = StandardLinearSVR()
svr.fit(X_train, y_train)
svr.score(X_test, y_test)