支援向量機 (SVM) 是一類功能強大且用途廣泛的監督式機器學習演算法,對於分類任務特別有效。 Python 中的 scikit-learn 等函式庫提供了 SVM 的強大實現,使從業者和研究人員都可以使用它。此回應將闡明如何使用 scikit-learn 來實現 SVM 分類,詳細說明所涉及的關鍵功能並提供說明性範例。
支援向量機簡介
支援向量機的工作原理是找到最能將資料分為不同類別的超平面。在二維空間中,這個超平面只是一條線,但在更高維度中,它變成了平面或超平面。最佳超平面是最大化兩個類別之間的邊距的超平面,其中邊距定義為超平面與任一類別中最近的資料點(稱為支援向量)之間的距離。
Scikit-learn 和 SVM
Scikit-learn 是一個強大的機器學習 Python 函式庫,為資料探勘和資料分析提供簡單且有效率的工具。它基於 NumPy、SciPy 和 matplotlib 構建。 scikit-learn 中的「svm」模組提供了 SVM 演算法的實作。
關鍵功能
1. `svm.SVC`:這是使用 SVM 執行分類的主要類別。 SVC 代表支援向量分類。
2. `適合`:此方法用於根據給定資料訓練模型。
3. `預測`:模型訓練完成後,此方法用於預測給定測試資料的類別標籤。
4. `分數`:此方法用於評估模型在測試資料上的準確性。
5. `網格搜尋CV`:這用於超參數調整,以找到 SVM 模型的最佳參數。
使用 scikit-learn 實現 SVM 分類
讓我們考慮一下使用 scikit-learn 實作 SVM 分類所涉及的步驟。
第 1 步:導入庫
首先,導入必要的庫:
python import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC from sklearn.metrics import classification_report, confusion_matrix
第 2 步:載入資料集
出於演示目的,我們將使用 Iris 資料集,這是機器學習社群中著名的資料集:
python # Load the Iris dataset iris = datasets.load_iris() X = iris.data y = iris.target
第三步:分割資料集
將資料集分為訓練集和測試集:
python # Split the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
第 4 步:特徵縮放
特徵縮放對於 SVM 很重要,因為它對輸入特徵的縮放很敏感:
python # Standardize features by removing the mean and scaling to unit variance scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test)
第 5 步:訓練 SVM 模型
實例化 SVM 分類器並在訓練資料上進行訓練:
python # Create an instance of SVC and fit the data svc = SVC(kernel='linear', C=1.0) svc.fit(X_train, y_train)
在這裡,我們使用線性內核並將正則化參數“C”設為 1.0。核心參數指定用於分離資料的超平面的類型。常見的內核包括「線性」、「poly」(多項式)、「rbf」(徑向基底函數)和「sigmoid」。
第五步:做出預測
使用經過訓練的模型對測試資料進行預測:
python # Predict the class labels for the test set y_pred = svc.predict(X_test)
第 7 步:評估模型
使用混淆矩陣和分類報告等指標評估模型的表現:
python # Evaluate the model print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred))
混淆矩陣提供預測結果的摘要,而分類報告包括精確度、回想率、F1 分數和每個類別的支持度。
使用 GridSearchCV 調整超參數
超參數調整對於優化 SVM 模型的效能至關重要。 Scikit-learn 的 GridSearchCV 可用於對指定參數網格執行詳盡搜尋:
python from sklearn.model_selection import GridSearchCV # Define the parameter grid param_grid = { 'C': [0.1, 1, 10, 100], 'gamma': [1, 0.1, 0.01, 0.001], 'kernel': ['rbf'] } # Create a GridSearchCV instance grid = GridSearchCV(SVC(), param_grid, refit=True, verbose=2) grid.fit(X_train, y_train) # Print the best parameters and the corresponding score print("Best parameters found: ", grid.best_params_) print("Best score: ", grid.best_score_) # Use the best estimator to make predictions grid_predictions = grid.predict(X_test) # Evaluate the model with the best parameters print(confusion_matrix(y_test, grid_predictions)) print(classification_report(y_test, grid_predictions))
在此範例中,我們使用 RBF 內核在值網格中搜尋“C”和“gamma”。 「GridSearchCV」實例使用搜尋過程中找到的最佳參數重新擬合模型。
可視化決策邊界
為了更好地理解 SVM 分類器的工作原理,視覺化決策邊界通常很有用。這在二維特徵空間中更簡單。以下是使用合成資料集的範例:
python from sklearn.datasets import make_blobs # Generate a synthetic dataset X, y = make_blobs(n_samples=100, centers=2, random_state=6) # Fit the SVM model svc = SVC(kernel='linear', C=1.0) svc.fit(X, y) # Create a mesh to plot the decision boundary h = .02 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the class for each point in the mesh Z = svc.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # Plot the decision boundary plt.contourf(xx, yy, Z, alpha=0.8) plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', marker='o') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('SVM Decision Boundary') plt.show()
上面的程式碼產生一個包含兩個類別的合成資料集,用線性內核擬合 SVM 模型,並視覺化決策邊界。 `contourf` 函數用於繪製決策邊界,散佈圖顯示資料點。 「svm.SVC」、「fit」、「predict」和「score」等關鍵函數對於建立和評估 SVM 模型至關重要。使用「GridSearchCV」進行超參數調整可透過尋找最佳參數進一步增強模型效能。可視化決策邊界可以為分類器的行為提供有價值的見解。透過遵循這些步驟,我們可以使用 scikit-learn 有效地實現和優化 SVM 分類。
最近的其他問題和解答 使用Python的EITC/AI/MLP機器學習:
- 線性迴歸中的b參數(最佳擬合線的y截距)是如何計算的?
- 支援向量在定義 SVM 的決策邊界中扮演什麼角色?
- 在 SVM 最佳化的背景下,權重向量「w」和偏差「b」的意義是什麼?
- SVM 實作中「視覺化」方法的目的是什麼?
- SVM 實作中的「預測」方法如何決定新資料點的分類?
- 在機器學習背景下支援向量機 (SVM) 的主要目標是什麼?
- 解釋限制條件 (y_i (mathbf{x}_i cdot mathbf{w} + b) geq 1) 在 SVM 最佳化中的重要性。
- SVM 最佳化問題的目標是什麼?
- SVM 中特徵集的分類如何取決於決策函數的符號 (text{sign}(mathbf{x}_icdot mathbf{w} + b))?
- 超平面方程式 (mathbf{x} cdot mathbf{w} + b = 0) 在支援向量機 (SVM) 中的作用是什麼?
查看 EITC/AI/MLP Machine Learning with Python 中的更多問題和解答