🎃支持向量机(SVM)是一种强大的分类算法,它通过找到数据点之间的最优边界来区分不同的类别。SVM在许多应用中表现出色,包括图像识别、生物信息学和文本分类等。以下是使用Python和scikit-learn库实现SVM分类器的示例代码,以及一个简介。
🎁简介
支持向量机是一种监督学习算法,用于分类和回归分析。它通过在特征空间中寻找最佳的线性超平面来区分不同的类别。在非线性可分的情况下,SVM通过使用核技巧将数据映射到更高维的空间,以找到最优的线性分割。
SVM的关键特性包括:
- 间隔最大化:SVM不仅尝试正确分类数据,还尝试最大化数据点到决策边界的距离。
- 核技巧:SVM可以使用不同的核函数(如线性、多项式、径向基函数等)来处理非线性问题。
- 稳健性:SVM对异常值和噪声具有较好的鲁棒性。
🎀示例代码
以下是使用SVM对鸢尾花(Iris)数据集进行分类的Python代码示例。
from sklearn import datasets
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SelectKBest, chi2
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# 加载鸢尾花数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建一个管道,将特征选择和SVM分类器结合起来
pipe = Pipeline([
('scaler', StandardScaler()),
('feature_selection', SelectKBest(chi2, k=2)), # 选择最佳2个特征
('svm', SVC())
])
# 设置参数网格,用于网格搜索
param_grid = {
'svm__C': [0.1, 1, 10],
'svm__gamma': ['scale', 'auto'],
'svm__kernel': ['linear', 'rbf']
}
# 使用网格搜索和交叉验证来找到最佳参数
grid_search = GridSearchCV(pipe, param_grid, cv=5, scoring='accuracy')
grid_search.fit(X_train, y_train)
# 获取最佳模型
best_model = grid_search.best_estimator_
# 预测测试集
y_pred = best_model.predict(X_test)
# 评估模型
print("Best parameters found: ", grid_search.best_params_)
print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
# 可视化决策边界
def plot_decision_boundary(X, y, model, features, title):
plt.figure(figsize=(8, 4))
for i in range(len(features)):
plt.subplot(1, len(features), i+1)
plt.subplots_adjust(hspace=0.3)
x_min, x_max = X[:, i].min() - 1, X[:, i].max() + 1
y_min, y_max = y.min() - 1, y.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
np.arange(y_min, y_max, 0.1))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.4)
plt.scatter(X[:, i], y, c='blue', s=20, edgecolor='k')
plt.title(f"Feature {features[i]}")
plt.show()
# 由于我们选择了两个特征,我们可以可视化这两个特征的决策边界
plot_decision_boundary(X_train[:, best_model.named_steps['feature_selection'].scores_.argsort()[:2]],
y_train,
best_model.named_steps['svm'],
iris.feature_names[:2],
"SVM Decision Boundary with Selected Features")
# 可视化PCA降维后的数据和决策边界
pca = PCA(n_components=2)
X_train_pca = pca.fit_transform(X_train)
X_test_pca = pca.transform(X_test)
plt.figure()
plot_decision_boundary(X_train_pca, y_train, best_model, ['PCA1', 'PCA2'], "SVM Decision Boundary on PCA Transformed Data")
plt.show()
🍔优化点说明:
- 参数调优:通过
GridSearchCV
进行了参数的网格搜索和交叉验证,以找到最佳的C
、gamma
和kernel
参数。 - 特征选择:使用
SelectKBest
结合chi2
统计量进行了特征选择,以减少特征维度并可能提高模型性能。 - 模型评估:除了准确率,还打印了详细的分类报告,包括精确度、召回率和F1分数。
- 模型解释性:通过可视化决策边界,我们可以看到模型是如何在选定的特征上进行分类的。
- PCA降维:在高维数据上,使用PCA进行降维可以减少计算复杂度并可能提高模型的泛化能力,同时也可视化了降维后的数据和决策边界。