原創轉載請注明出處:https://www.cnblogs.com/agilestyle/p/12786022.html
SVC 的構造函數

這里有三個重要的參數 kernel、C 和 gamma
kernel
kernel 代表核函數的選擇,它有四種選擇,只不過默認是 rbf,即高斯核函數。
- linear:線性核函數
- poly:多項式核函數
- rbf:高斯核函數
- sigmoid:sigmoid 核函數
這四種函數代表不同的映射方式,在實際工作中,如何選擇這 4 種核函數?
- 線性核函數是在數據線性可分的情況下使用的,運算速度快,效果好。不足在於它不能處理線性不可分的數據。
- 多項式核函數可以將數據從低維空間映射到高維空間,但參數比較多,計算量大。
- 高斯核函數同樣可以將樣本映射到高維空間,但相比於多項式核函數來說所需的參數比較少,通常性能不錯,所以是默認使用的核函數。
- sigmoid 經常用在神經網絡的映射中。因此當選用 sigmoid 核函數時,SVM 實現的是多層神經網絡。
4 種核函數,除了第一種線性核函數外,其余 3 種都可以處理線性不可分的數據。
C
參數 C 代表目標函數的懲罰系數,懲罰系數指的是分錯樣本時的懲罰程度,默認情況下為 1.0。當 C 越大的時候,分類器的准確性越高,但同樣容錯率會越低,泛化能力會變差。相反,C 越小,泛化能力越強,但是准確性會降低。
gamma
參數 gamma 代表核函數的系數。

准備數據
import numpy as np from sklearn.datasets import load_breast_cancer from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split from sklearn.svm import SVC cancer = load_breast_cancer() # sklearn.utils.Bunch print(type(cancer)) # dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename']) print(cancer.keys()) # print(cancer.DESCR) features = cancer.data labels = cancer.target # (569, 30) print(features.shape) # (569,) print(labels.shape)
分割數據
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2)
建模訓練、評價模型
線性核
model_linear = SVC(C=1.0, kernel='linear') # 線性核 model_linear.fit(X_train, y_train) train_score = model_linear.score(X_train, y_train) test_score = model_linear.score(X_test, y_test) print('train_score:{0}; test_score:{1}'.format(train_score, test_score))
高斯核
model_rbf = SVC(C=1.0, kernel='rbf', gamma=0.1) # 高斯核 model_rbf.fit(X_train, y_train) train_score = model_rbf.score(X_train, y_train) test_score = model_rbf.score(X_test, y_test) print('train_score:{0}; test_score:{1}'.format(train_score, test_score)) gammas = np.linspace(0, 0.005, 30) param_grid = { 'gamma': gammas } model = GridSearchCV(SVC(), param_grid, cv=10) # 使用網格搜索和交叉驗證找出最佳gamma值 model.fit(X_train, y_train) print('best param:{0}; best score:{1}'.format(model.best_params_, model.best_score_))
多項式核
model_poly = SVC(kernel='poly', degree=2, gamma='scale') # 多項式核 2階 model_poly.fit(X_train, y_train) train_score = model_poly.score(X_train, y_train) test_score = model_poly.score(X_test, y_test) print('train_score:{0}; test_score:{1}'.format(train_score, test_score)) degrees = np.linspace(1, 10, 10) param_grid = { 'degree': degrees } model = GridSearchCV(SVC(kernel='poly', gamma='scale'), param_grid, cv=10) model.fit(X_train, y_train) print('best param:{0}; best score:{1}'.format(model.best_params_, model.best_score_))
Note:輸出的最佳參數可能會不一樣是因為交叉驗證時數據集的划分每次都不一樣。可以選擇得分最高的,也可以執行多次選擇取出現次數最多的那個。
Reference
https://time.geekbang.org/column/article/80712
https://scikit-learn.org/stable/modules/svm.html
https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html
