用法如下:
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()