1. 程式人生 > 實用技巧 >sklearn.svm.SVC 支援向量機引數詳解

sklearn.svm.SVC 支援向量機引數詳解

用法如下:

class sklearn.svm.SVC(*, C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape='ovr', break_ties=False, random_state=None)

可選引數

  • C:正則化引數。正則化的強度與C成反比。必須嚴格為正。懲罰是平方的l2懲罰。(預設1.0), 懲罰引數越小,容忍性就越大
  • kernel:核函式型別,可選‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’
  • degree:當選擇核函式為poly多項式時,表示多項式的階數
  • gamma:可選‘scale’和‘auto’,表示為“ rbf”,“ poly”和“ Sigmoid”的核心係數。預設是'scale',gamma取值為1 / (n_features * X.var());當選‘auto’引數時gamma取值為1 / n_features。
  • coef0:當核函式選為“ poly”和“ sigmoid”有意義。
  • shrinking:是否使用縮小的啟發式方法,預設是True。
  • probability:是否啟用概率估計,預設是False。必須在呼叫fit之前啟用此功能,因為該方法內部使用5倍交叉驗證,因而會減慢該方法的速度,並且predict_proba可能與dict不一致。
  • tol:演算法停止的條件,預設為0.001。cache_size:指定核心快取的大小(以MB為單位),預設是200。
  • class_weight:每個類樣本的權重,可以用字典形式給出,選擇'balanced',權重為n_samples / (n_classes * np.bincount(y));預設是None,表示每個樣本權重一致。
  • verbose:是否使用詳細輸出,預設是False。
  • max_iter:演算法迭代的最大步數,預設-1表示無限制
  • decision_function_shape:多分類的形式,1 vs 多(‘ovo’)還是1 vs 1(’ovr’),預設’ovr’.
  • break_ties:如果為true,decision_function_shape ='ovr',並且類別數> 2,則預測將根據Decision_function的置信度值打破平局;否則,將返回繫結類中的第一類。請注意,與簡單預測相比,打破平局的計算成本較高。
  • random_state:隨機種子,隨機打亂樣本。

可選標籤

  • support_:
  • support_vectors_:支援向量
  • n_support_:每個類的支援向量數量
  • dual_coef_:對偶係數;
  • coef_:原始問題的係數
  • intercept_:決策函式中的常數
  • fit_status_:如果正確擬合,則為0,否則為1(將發出警告)
  • classes_:類別
  • class_weight_:類別的權重
  • shape_fit_:訓練向量X的陣列尺寸。

資料準備:

# 引入資料
from sklearn import datasets
import numpy as np

iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target
print("Class labels:",np.unique(y))  #列印分類類別的種類


# 切分訓練資料和測試資料
from sklearn.model_selection import train_test_split
## 30%測試資料,70%訓練資料,stratify=y表示訓練資料和測試資料具有相同的類別比例
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=1,stratify=y)



from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
## 估算訓練資料中的mu和sigma
sc.fit(X_train)
## 使用訓練資料中的mu和sigma對資料進行標準化
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)



## 畫出決策邊界圖(只有在2個特徵才能畫出來)
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib.colors import ListedColormap

def plot_decision_region(X,y,classifier,resolution=0.02):
    markers = ('s','x','o','^','v')
    colors = ('red','blue','lightgreen','gray','cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min,x1_max = X[:,0].min()-1,X[:,0].max()+1
    x2_min,x2_max = X[:,1].min()-1,X[:,1].max()+1
    xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,resolution),
                         np.arange(x2_min,x2_max,resolution))
    Z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1,xx2,Z,alpha=0.3,cmap=cmap)
    plt.xlim(xx1.min(),xx1.max())
    plt.ylim(xx2.min(),xx2.max())

    # plot class samples
    for idx,cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y==cl,0],
                   y = X[y==cl,1],
                   alpha=0.8,
                   c=colors[idx],
                   marker = markers[idx],
                   label=cl,
                   edgecolors='black')

線性支援向量機:

## 線性支援向量機
from sklearn.svm import SVC
svm = SVC(kernel='linear',C=1.0,random_state=1)
svm.fit(X_train_std,y_train)
plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.show()

使用核函式對非線性分類問題建模(gamma=0.20)

## 使用核函式對非線性分類問題建模(gamma=0.20)
svm = SVC(kernel='rbf',random_state=1,gamma=0.20,C=1.0)    ##較小的gamma有較鬆的決策邊界
svm.fit(X_train_std,y_train)
plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.show()

使用核函式對非線性分類問題建模(gamma=100)

## 使用核函式對非線性分類問題建模(gamma=100)
svm = SVC(kernel='rbf',random_state=1,gamma=100.0,C=1.0,verbose=1)   
svm.fit(X_train_std,y_train)
plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.show()

從不同的gamma取值的影象來看:對於高斯核函式,增大gamma值,將增大訓練樣本的影響範圍,導致決策邊界緊縮和波動;較小的gamma值得到的決策邊界相對寬鬆。雖然較大的gamma值在訓練樣本中有很小的訓練誤差,但是很可能泛化能力較差,容易出現過擬合

全部程式碼(已摺疊)

# -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 10:12:48 2020

@author: Admin
"""


# 引入資料
from sklearn import datasets
import numpy as np

iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target
print("Class labels:",np.unique(y))  #列印分類類別的種類


# 切分訓練資料和測試資料
from sklearn.model_selection import train_test_split
## 30%測試資料,70%訓練資料,stratify=y表示訓練資料和測試資料具有相同的類別比例
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=1,stratify=y)



from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
## 估算訓練資料中的mu和sigma
sc.fit(X_train)
## 使用訓練資料中的mu和sigma對資料進行標準化
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)



## 畫出決策邊界圖(只有在2個特徵才能畫出來)
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib.colors import ListedColormap

def plot_decision_region(X,y,classifier,resolution=0.02):
    markers = ('s','x','o','^','v')
    colors = ('red','blue','lightgreen','gray','cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min,x1_max = X[:,0].min()-1,X[:,0].max()+1
    x2_min,x2_max = X[:,1].min()-1,X[:,1].max()+1
    xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,resolution),
                         np.arange(x2_min,x2_max,resolution))
    Z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1,xx2,Z,alpha=0.3,cmap=cmap)
    plt.xlim(xx1.min(),xx1.max())
    plt.ylim(xx2.min(),xx2.max())

    # plot class samples
    for idx,cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y==cl,0],
                   y = X[y==cl,1],
                   alpha=0.8,
                   c=colors[idx],
                   marker = markers[idx],
                   label=cl,
                   edgecolors='black')
        

## 線性支援向量機
from sklearn.svm import SVC
svm = SVC(kernel='linear',C=1.0,random_state=1)
svm.fit(X_train_std,y_train)
plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.show()
        


## 使用核函式對非線性分類問題建模(gamma=0.20)
svm = SVC(kernel='rbf',random_state=1,gamma=0.20,C=1.0)    ##較小的gamma有較鬆的決策邊界
svm.fit(X_train_std,y_train)
plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.show()



## 使用核函式對非線性分類問題建模(gamma=100)
svm = SVC(kernel='rbf',random_state=1,gamma=100.0,C=1.0,verbose=1)   
svm.fit(X_train_std,y_train)
plot_decision_region(X_train_std,y_train,classifier=svm,resolution=0.02)
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.show()