支撐向量機(jī) SVM

支撐向量機(jī) SVM

image

分類算法中,一般用一條邊界來(lái)決策分類。這條就是決策邊界。但是決策邊界在很多時(shí)候都可以是多條 。那一條比較合適呢?數(shù)學(xué)理論的基礎(chǔ)下,當(dāng)只有分類邊界離最近的分類點(diǎn)最遠(yuǎn)的時(shí)候,這條邊界是最優(yōu)秀的。 如圖,有三條邊界,中間的一條是離兩個(gè)分類結(jié)果最遠(yuǎn)的,也就是最合適的。而上邊和下邊這兩條我們稱為支撐向量。當(dāng)margin值最大時(shí),中間的決策邊界泛化能力就最強(qiáng),也就是最合適。

推出公式

image

當(dāng)
image

d最大,也就是margin最大

Soft Margin SVM

當(dāng)邊界不明確時(shí),或者分類元素有異常時(shí),決策邊界就很難定義,上面用的方法可能會(huì)定義出泛化能力非常差的決策邊界。所以我們要在邊界中加入一定的容錯(cuò)率,這個(gè)容錯(cuò)率就是Soft Margin SVM

image

可以給容錯(cuò)加上比例

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]

#使用標(biāo)準(zhǔn)化同一量綱
from sklearn.preprocessing import StandardScaler

standardScaler = StandardScaler()
standardScaler.fit(X)
X_standard = standardScaler.transform(X)

#使用線性SVM算法
from sklearn.svm import LinearSVC

#超參數(shù)C,容錯(cuò)比例
svc = LinearSVC(C=1e9)
svc.fit(X_standard, y)

svc.coef_
svc.intercept_

Scikit-learn 多項(xiàng)式

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"核函數(shù)
    ])

poly_kernel_svc = PolynomialKernelSVC(degree=3)
poly_kernel_svc.fit(X, y)

Scikit-learn 高斯核函數(shù)

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 高斯核函數(shù),gamma值越大越容易過(guò)擬合
    ])

svc = RBFKernelSVC(gamma=1)
svc.fit(X, y)

Scikit-learn SVM解決回歸問(wèn)題

類似分類問(wèn)題,但是,支撐向量機(jī)包含越多元素越好,然后取向量機(jī)中間的邊界。epsilon是向量機(jī)和邊界的距離

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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容