【SVM 實作篇】用 Python 打造你的第一個支援向量機模型
接續上一篇的理論篇,這次我們動手實作一個 SVM 模型。
我們會使用 scikit-learn 這個機器學習套件,實際體驗 SVM 的訓練與調參流程。
一、準備環境
在 Python 中安裝 scikit-learn:
pip install scikit-learn
二、載入資料集
我們用最經典的 Iris 花卉資料集:
from sklearn import datasets
from sklearn.model_selection import train_test_split
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 只取兩類花作為簡化例子
X = X[y != 2]
y = y[y != 2]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
三、建立並訓練 SVM 模型
from sklearn.svm import SVC
# 建立支援向量機模型(使用 RBF 核)
model = SVC(kernel='rbf', C=1.0, gamma='scale')
# 訓練模型
model.fit(X_train, y_train)
四、進行預測與評估
from sklearn.metrics import accuracy_score
y_pred = model.predict(X_test)
print("準確率:", accuracy_score(y_test, y_pred))
輸出結果通常在 90% 以上。
五、視覺化決策邊界(可選)
import matplotlib.pyplot as plt
import numpy as np
# 取前兩個特徵繪圖
X_plot = X_train[:, :2]
model = SVC(kernel='rbf', C=1.0, gamma='auto')
model.fit(X_plot, y_train)
# 建立格點
x_min, x_max = X_plot[:, 0].min() - 1, X_plot[:, 0].max() + 1
y_min, y_max = X_plot[:, 1].min() - 1, X_plot[:, 1].max() + 1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
np.linspace(y_min, y_max, 100))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3)
plt.scatter(X_plot[:, 0], X_plot[:, 1], c=y_train)
plt.title("SVM 決策邊界視覺化")
plt.show()
這樣就能看到 SVM 如何畫出分隔線(或曲線)。
六、進階:調整參數(Grid Search)
SVM 的表現會受到 C 和 γ 的影響。
我們可以用 GridSearchCV 來自動找出最佳組合:
from sklearn.model_selection import GridSearchCV
param_grid = {
'C': [0.1, 1, 10],
'gamma': ['scale', 0.1, 1]
}
grid = GridSearchCV(SVC(kernel='rbf'), param_grid, cv=5)
grid.fit(X_train, y_train)
print("最佳參數:", grid.best_params_)
七、SVM 回歸範例(SVR)
除了分類,SVM 也能做回歸任務:
from sklearn.svm import SVR
import numpy as np
X = np.arange(0, 10, 0.1).reshape(-1, 1)
y = np.sin(X).ravel()
model = SVR(kernel='rbf', C=1.0, gamma=0.5)
model.fit(X, y)
y_pred = model.predict(X)
plt.scatter(X, y, label='True')
plt.plot(X, y_pred, color='r', label='SVR Prediction')
plt.legend()
plt.show()
八、結語
透過這篇實作,你已經能:
- 使用 SVM 進行分類;
- 調整超參數;
- 理解核函數的效果;
- 應用在回歸分析中。
雖然 SVM 看似「老派」,但它仍然是:
小型資料集、高維特徵分析、以及分類任務中最穩定的選擇之一。
