【超详细】SVM 支持向量机实战:线性 / 非线性分类与决策边界可视化 - predict(X2_test)
一、SVM 支持向量机核心原理
1.1 基本概念
支持向量机(Support Vector Machine,SVM)是一种经典的二分类模型,其核心思想是寻找最优分类超平面,使得两类样本之间的间隔(Margin)最大化。
间隔:分类超平面到最近样本点的距离的 2 倍,SVM 的目标是最大化这个间隔支持向量:距离超平面最近的样本点,决定了最优超平面的位置,是 SVM 的核心分类超平面:对于二维数据,超平面退化为一条直线;三维为平面;高维为超平面
1.2 线性 SVM
对于线性可分数据,线性 SVM 的数学目标为:其中:
w:超平面法向量b:超平面截距:样本标签(±1)
为了求解方便,通常转化为对偶问题求解,引入拉格朗日乘子法,最终只有支持向量对应的拉格朗日乘子不为 0。
1.3 软间隔 SVM
实际数据往往不是完全线性可分的,引入惩罚参数 C构建软间隔 SVM:
C 越大:对分类错误的惩罚越重,模型越容易过拟合C 越小:对分类错误的惩罚越轻,模型越容易欠拟合
1.4 非线性 SVM(核函数)
对于非线性可分数据,SVM 通过核函数将低维数据映射到高维空间,使其在高维空间线性可分:
线性核:(适用于线性可分数据)高斯核(RBF):(适用于非线性数据)
越大:核函数越集中,模型越容易过拟合 越小:核函数越分散,模型越容易欠拟合
二、实战环境准备
2.1 依赖库安装
pip install numpy matplotlib scipy scikit-learn seaborn
2.2 数据集说明
本文使用经典的 SVM 测试数据集:
ex6data1.mat:线性可分数据(含少量异常点)ex6data2.mat:非线性可分数据(环形分布)
三、完整代码实现
3.1 数据加载与预处理
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
import seaborn as sns
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# 加载mat格式数据
def load_mat_data(file_path):
data = loadmat(file_path)
X = data['X']
y = data['y'].flatten()
y = y - 1 # 将标签从1/2转换为0/1,方便处理
return X, y
3.2 线性 SVM 实战(ex6data1)
# 处理线性数据集
print("=" * 50)
print("处理数据集:ex6data1.mat(线性数据)")
print("=" * 50)
# 加载数据并划分训练/测试集
X1, y1 = load_mat_data('C:/Users/lover/Downloads/ex6data1.mat')
X1_train, X1_test, y1_train, y1_test = train_test_split(
X1, y1, test_size=0.3, random_state=42
)
print(f"ex6data1 训练集大小: {X1_train.shape}, 标签数: {y1_train.shape}")
print(f"ex6data1 测试集大小: {X1_test.shape}, 标签数: {y1_test.shape}")
# 训练线性SVM模型
svm_model1 = SVC(kernel='linear', C=100, random_state=42)
svm_model1.fit(X1_train, y1_train)
# 模型评估
y1_train_pred = svm_model1.predict(X1_train)
y1_test_pred = svm_model1.predict(X1_test)
train_accuracy1 = accuracy_score(y1_train, y1_train_pred)
test_accuracy1 = accuracy_score(y1_test, y1_test_pred)
print(f"ex6data1 训练集准确率: {train_accuracy1:.4f}")
print(f"ex6data1 测试集准确率: {test_accuracy1:.4f}")
print("\nex6data1 分类报告(测试集):")
print(classification_report(y1_test, y1_test_pred))
3.3 非线性 SVM 实战(ex6data2)
# 处理非线性数据集
print("\n" + "=" * 50)
print("处理数据集:ex6data2.mat(非线性数据)")
print("=" * 50)
# 加载数据并划分训练/测试集
X2, y2 = load_mat_data('C:/Users/lover/Downloads/ex6data2.mat')
X2_train, X2_test, y2_train, y2_test = train_test_split(
X2, y2, test_size=0.3, random_state=42
)
print(f"ex6data2 训练集大小: {X2_train.shape}, 标签数: {y2_train.shape}")
print(f"ex6data2 测试集大小: {X2_test.shape}, 标签数: {y2_test.shape}")
# 训练RBF核SVM模型
svm_model2 = SVC(kernel='rbf', C=100, gamma=50, random_state=42)
svm_model2.fit(X2_train, y2_train)
# 模型评估
y2_train_pred = svm_model2.predict(X2_train)
y2_test_pred = svm_model2.predict(X2_test)
train_accuracy2 = accuracy_score(y2_train, y2_train_pred)
test_accuracy2 = accuracy_score(y2_test, y2_test_pred)
print(f"ex6data2 训练集准确率: {train_accuracy2:.4f}")
print(f"ex6data2 测试集准确率: {test_accuracy2:.4f}")
print("\nex6data2 分类报告(测试集):")
print(classification_report(y2_test, y2_test_pred))
3.4 优化的决策边界可视化函数
def plot_optimized_boundary(X, y, model, title, is_linear=True):
# 设置画布
plt.figure(figsize=(8, 6), dpi=100)
ax = plt.gca()
# 定义网格范围
x_min, x_max = X[:, 0].min() - 0.2, X[:, 0].max() + 0.2
y_min, y_max = X[:, 1].min() - 0.2, X[:, 1].max() + 0.2
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.005),
np.arange(y_min, y_max, 0.005))
if is_linear:
# 线性SVM决策边界和间隔 拼多多帮助力入口
Z = model.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# 填充间隔区域
ax.contourf(xx, yy, Z, levels=[-np.inf, -1, 1, np.inf],
colors=['#FFCCCC', '#CCE5FF'], alpha=0.3)
# 绘制决策边界和间隔
ax.contour(xx, yy, Z, levels=[-1, 0, 1],
linestyles=['--', '-', '--'],
colors=['#FF6B6B', '#4A6FE3', '#FF6B6B'],
linewidths=[1.2, 1.5, 1.2])
else:
# 非线性SVM决策区域
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# 填充决策区域
ax.contourf(xx, yy, Z, alpha=0.3, cmap='coolwarm')
# 绘制决策边界
ax.contour(xx, yy, Z, levels=[0.5], colors='#4A6FE3', linewidths=1.5)
# 绘制正负样本
pos_mask = (y == 1)
neg_mask = (y == 0)
# 正样本(蓝色×)
ax.scatter(X[pos_mask, 0], X[pos_mask, 1],
marker='x', color='#4A6FE3', s=60,
linewidths=1.5, label='Positive (1)')
# 负样本(橙色圆点)
ax.scatter(X[neg_mask, 0], X[neg_mask, 1],
marker='o', color='#FF9F43', s=60,
alpha=0.8, edgecolors='k', linewidths=0.8, label='Negative (0)')
# 突出显示支持向量
ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1],
s=150, facecolors='none', edgecolors='k', linewidths=1.5,
label='Support Vectors')
# 图表美化
ax.set_xlabel('Feature 1', fontsize=12, fontweight='bold')
ax.set_ylabel('Feature 2', fontsize=12, fontweight='bold')
ax.set_title(title, fontsize=14, fontweight='bold', pad=15)
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.grid(True, linestyle='--', alpha=0.4, color='#999999')
# 移除边框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#666666')
ax.spines['bottom'].set_color('#666666')
# 图例
ax.legend(loc='upper right', frameon=True, framealpha=0.9, fontsize=10)
plt.show()
# 绘制线性SVM决策边界
plot_optimized_boundary(X1, y1, svm_model1, "SVM Decision Boundary (ex6data1 - Linear Kernel)", is_linear=True)
# 绘制非线性SVM决策边界
plot_optimized_boundary(X2, y2, svm_model2, "SVM Decision Boundary (ex6data2 - RBF Kernel)", is_linear=False)
3.5 混淆矩阵可视化
# 混淆矩阵可视化(以ex6data2为例)
cm = confusion_matrix(y2_test, y2_test_pred)
plt.figure(figsize=(6, 5), dpi=100)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=['Class 0', 'Class 1'],
yticklabels=['Class 0', 'Class 1'])
plt.xlabel('Predicted', fontsize=11, fontweight='bold')
plt.ylabel('True', fontsize=11, fontweight='bold')
plt.title('Confusion Matrix (ex6data2 Test Set)', fontsize=12, fontweight='bold')
plt.show()
# 输出支持向量信息
print(f"\nex6data1 支持向量数量: {len(svm_model1.support_vectors_)}")
print(f"ex6data2 支持向量数量: {len(svm_model2.support_vectors_)}")
四、结果分析
4.1 线性 SVM 结果
ex6data1 数据集使用线性核 SVM,C=100 时模型拟合效果好,训练 / 测试准确率接近 100%决策边界图中可以清晰看到:
实线为决策边界(Z=0)虚线为间隔边界(Z=±1)空心圆点为支持向量,是决定决策边界的关键样本
4.2 非线性 SVM 结果
ex6data2 数据集使用 RBF 核 SVM,C=100、gamma=50 时,模型能很好拟合环形分布数据决策边界图中可以看到非线性的决策边界,完美分割环形数据混淆矩阵显示模型在测试集上的分类错误率极低
4.3 关键参数影响
C 值:C 越大,模型对错误的惩罚越重,容易过拟合;C 越小,模型越宽松,容易欠拟合gamma 值(RBF 核):gamma 越大,核函数的局部性越强,模型拟合能力越强,但容易过拟合;gamma 越小,模型越平滑,泛化能力越强
五、总结与拓展
5.1 核心总结
SVM 的核心是最大化分类间隔,支持向量是决定决策边界的关键线性核适用于线性可分数据,RBF 核适用于非线性数据参数调优(C、gamma)对 SVM 性能至关重要,需结合交叉验证决策边界可视化能直观展示 SVM 的分类效果
5.2 拓展方向
使用网格搜索(GridSearchCV)自动调优 C 和 gamma 参数尝试其他核函数(多项式核、sigmoid 核)处理多分类问题(One-vs-One / One-vs-Rest)结合 PCA 降维后再使用 SVM,提升高维数据处理效率
六、完整代码获取
本文所有代码已经过验证,可直接运行。只需将数据路径修改为你的本地路径即可。如果遇到问题,欢迎在评论区交流!
创作不易,如果本文对你有帮助,欢迎点赞、收藏、关注! ,超详细