1、定義分類模型決策區域可視化的函數

import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02): # 定義顏色和標記符號,通過顏色列圖表生成顏色示例圖 marker = ('o', 'x', 's', 'v', '^') colors = ('lightgreen', 'blue', 'red', 'cyan', 'gray') cmap = ListedColormap(colors[:len(np.unique(y))]) # 可視化決策邊界 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.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # 繪制所有的樣本點 for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=marker[idx], s=73, label=cl) # 使用小圓圈高亮顯示測試集的樣本 if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], c='', alpha=1.0, linewidth=1, edgecolors='black', marker='o', s=135, label='test set')
2、准備數據

from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler iris = datasets.load_iris() X = iris.data[:, [2, 3]] y = iris.target # 划分測試集和訓練集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=0) # 對特征值進行標准化 sc = StandardScaler() sc.fit(X_train) X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) # 將標准化后的訓練數據和測試數據重新整合到一起 X_combined_std = np.vstack((X_train_std, X_test_std)) y_combined = np.hstack((y_train, y_test))
3、訓練模型、繪制圖形
from sklearn.svm import SVC import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = 'SimHei' plt.rcParams['axes.unicode_minus'] = False svm = SVC(kernel='rbf', random_state=0, gamma=0.10, C=10.0) svm.fit(X_train_std, y_train) plt.figure(figsize=(12, 7)) plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150)) plt.title('核 SVM 模型的決策區域', fontsize=19, color='w') plt.xlabel('標准化處理后的花瓣長度', fontsize=15) plt.ylabel('標准化處理后的花瓣寬度', fontsize=15) plt.legend(loc=2, scatterpoints=2)
圖形如下:
如圖所示,γ=0.10 相對角小,決策邊界較為寬松。
增大 γ 值:
from sklearn.svm import SVC import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = 'SimHei' plt.rcParams['axes.unicode_minus'] = False svm = SVC(kernel='rbf', random_state=0, gamma=10, C=10.0) svm.fit(X_train_std, y_train) plt.figure(figsize=(12, 7)) plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150)) plt.title('核 SVM 模型的決策區域', fontsize=19, color='w') plt.xlabel('標准化處理后的花瓣長度', fontsize=15) plt.ylabel('標准化處理后的花瓣寬度', fontsize=15) plt.legend(loc=2, scatterpoints=2)
圖形如下:
如圖所示,類別 0 和 1 的決策邊界隨 γ 值的增大緊湊了許多。此模型雖然隨訓練數據擬合的很好,但對未知數據會有較高的泛化誤差。