一、SVM 相关概念
1.1 通俗易懂的 SVM 算法描述
SVM(支撑向量机)呢,简单来说就是在两类数据中间找一条“最宽的路”。这条路的中间线就是用来分类的边界(也叫“决策边界”),路越宽,分类的效果就越好。核心思想就是找“最宽的路”(最大间隔):假设这两类数据是路上的两群行人,SVM 的目标就是在这两群人中间划出一条最宽的隔离带(称为“间隔”),隔离带的中间线就是最终的分类边界。关键在于“边缘的人(支持向量)”:隔离带的宽度是由离边界最近的那几个行人(叫做“支撑向量”)决定的,其他行人对隔离带的位置和宽度没啥影响。允许“少量越界”:要是这两群人交错得很厉害(数据线性不可分),SVM 会允许少量行人暂时走进隔离带,不过还是会尽量让隔离带足够宽,平衡好分类错误和间隔大小(这就是“软间隔”)。核函数:当数据线性不可分的时候(就像缠绕的毛线团),把数据映射到高维空间,让它变得线性可分。
1.2 专业术语描述 SVM 相关概念
- 1.基本概念
- 定义:支持向量机(SVM)是一种常用于分类任务的机器学习算法,旨在通过一个“最佳”分隔线(在高维空间中是超平面)将不同类别的数据分开。
- 超平面:在二维空间中是一条直线,三维空间中是一个平面,更高维度空间中是一个多维空间的平面,是SVM用于分隔数据的决策边界。
- 支持向量:是离超平面最近的数据点,对确定分类边界至关重要,去掉它们分类边界可能改变。
- 最大间隔:SVM要找到的超平面需使两类数据点到该超平面的距离最大,可提高模型对未知数据的预测能力。
- 2.工作原理
- 线性可分情况:当数据集中的不同类别可通过一条直线(二维)或超平面(高维)分开时,SVM寻找的就是这个能使两边数据点离超平面距离最大的超平面。
- 非线性可分情况:现实中数据常是非线性可分的,SVM通过核技巧将原始数据映射到更高维空间,使数据在高维空间中线性可分,进而找到分隔超平面。常见的核函数有线性核、多项式核、径向基核(RBF核)等。
- 3.算法优势
- 高效分类:能有效分开不同类别的数据,处理高维数据有优势,适合数据维度高于样本数量的情况,如文本分类、基因数据分析等。
- 抗过拟合能力强:通过最大化间隔确定分类边界,对噪声数据和异常值不太敏感,提高了模型的泛化能力。
- 4.模型评估 训练好SVM模型后,常用精确度、召回率、F1分数等指标评估其性能。精确度是分类器预测为正的样本中实际为正的比例;召回率是所有实际为正的样本中分类器正确预测为正的比例;F1分数是精确度和召回率的调和平均值,综合评估分类模型性能。
- 5.模型调参 SVM有几个重要超参数需调参优化模型,如C参数,C越大对训练数据拟合能力越强但可能过拟合,C越小模型泛化能力越强但可能欠拟合;选择适合数据的核函数可提高模型准确性;用于RBF核的gamma参数,值越大影响范围越小,值越小影响范围越大。通常使用交叉验证来选择最优参数。
1.3 以代码方式,理解SVM
1.3.1 解决分类问题示例:使用 iris 数据集,训练SVM模型并预测
问题背景:根据鸢尾花的花瓣长度和宽度,将其分为3类(山鸢尾、变色鸢尾、维吉尼亚鸢尾)。这里简化为二分类问题(区分山鸢尾和变色鸢尾)。
数据特点:
- 输入特征:花瓣长度(cm)、花瓣宽度(cm)
- 输出标签:0(山鸢尾)、1(变色鸢尾)
代码分段解析
- 步骤1:导入库和数据
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
# 加载鸢尾花数据集(只取前两类)
iris = datasets.load_iris()
X = iris.data[:, 2:4] # 花瓣长度和宽度
y = iris.target.copy()
y[y == 2] = 1 # 将第三类(维吉尼亚鸢尾)也标记为1,转为二分类问题
# 拆分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
- 步骤2:数据标准化(SVM对尺度敏感)
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
- 步骤3:创建并训练SVM模型(线性核)
# 使用线性核的SVM分类器
svm_clf = SVC(kernel='linear', C=1.0) # C是软间隔的惩罚参数,C越小允许越多错误
svm_clf.fit(X_train_scaled, y_train)
- 步骤4:预测与评估
# 预测测试集
y_pred = svm_clf.predict(X_test_scaled)
accuracy = np.mean(y_pred == y_test)
print(f"分类准确率:{accuracy:.2f}")
- 步骤5:可视化决策边界和支撑向量
def plot_svm_decision_boundary(clf, ax=None, plot_support_vectors=True):
if ax is None:
ax = plt.gca()
x_min, x_max = X_train_scaled[:, 0].min() - 1, X_train_scaled[:, 0].max() + 1
y_min, y_max = X_train_scaled[:, 1].min() - 1, X_train_scaled[:, 1].max() + 1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
np.linspace(y_min, y_max, 100))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
ax.contourf(xx, yy, Z, alpha=0.2)
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xlabel('花瓣长度(标准化后)')
ax.set_ylabel('花瓣宽度(标准化后)')
if plot_support_vectors:
ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
s=300, linewidth=1, facecolors='none', edgecolors='k')
plt.figure(figsize=(8, 6))
plot_svm_decision_boundary(svm_clf)
plt.scatter(X_train_scaled[y_train==0, 0], X_train_scaled[y_train==0, 1], c='red', label='山鸢尾')
plt.scatter(X_train_scaled[y_train==1, 0], X_train_scaled[y_train==1, 1], c='blue', label='变色鸢尾')
plt.legend()
plt.title('SVM决策边界与支撑向量(线性核)')
plt.show()
- 完整且添加字体的代码如下
# 步骤1. 导入库和数据
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体为黑体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 加载鸢尾花数据集(只取前两类)
iris = datasets.load_iris()
X = iris.data[:, 2:4] # 花瓣长度和宽度
y = iris.target.copy()
y[y == 2] = 1 # 将第三类(维吉尼亚鸢尾)也标记为1,转为二分类问题
# 拆分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 步骤2:数据标准化(SVM对尺度敏感)P
# 数据标准化(SVM对尺度敏感)
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 步骤3:创建并训练SVM模型(线性核)
# 创建并训练SVM模型(线性核)
svm_clf = SVC(kernel='linear', C=1.0) # C是软间隔的惩罚参数,C越小允许越多错误
svm_clf.fit(X_train_scaled, y_train)
# 步骤4:预测与评估
# 预测与评估
y_pred = svm_clf.predict(X_test_scaled)
accuracy = np.mean(y_pred == y_test)
print(f"分类准确率:{accuracy:.2f}")
# 步骤5:可视化决策边界和支撑向量
def plot_svm_decision_boundary(clf, ax=None, plot_support_vectors=True):
if ax is None:
ax = plt.gca()
x_min, x_max = X_train_scaled[:, 0].min() - 1, X_train_scaled[:, 0].max() + 1
y_min, y_max = X_train_scaled[:, 1].min() - 1, X_train_scaled[:, 1].max() + 1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
np.linspace(y_min, y_max, 100))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
ax.contourf(xx, yy, Z, alpha=0.2)
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xlabel('花瓣长度(标准化后)')
ax.set_ylabel('花瓣宽度(标准化后)')
if plot_support_vectors:
ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
s=300, linewidth=1, facecolors='none', edgecolors='k')
plt.figure(figsize=(8, 6))
plot_svm_decision_boundary(svm_clf)
plt.scatter(X_train_scaled[y_train==0, 0], X_train_scaled[y_train==0, 1], c='red', label='山鸢尾')
plt.scatter(X_train_scaled[y_train==1, 0], X_train_scaled[y_train==1, 1], c='blue', label='变色鸢尾')
plt.legend()
plt.title('SVM分类决策边界可视化') # 明确的中文标题
plt.show()
分类准确率:1.00
- 代码输出解读:
1. 准确率:通常在二分类问题中可达90%以上(取决于数据和参数)。
2. 可视化结果:
背景颜色表示分类区域,中间的实线是决策边界,虚线是间隔边界(由支撑向量决定)。
黑色圆圈标记的点是支撑向量,它们决定了决策边界的位置。
1.3.2 解决回归问题示例:使用波士顿房价数据集,训练SVM模型并预测
- 实现代码
import numpy as np
import matplotlib.pyplot as plt
import warnings
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error, r2_score
# 忽略过时警告(波士顿房价数据集已被sklearn弃用)
warnings.filterwarnings('ignore')
# 加载波士顿房价数据集
boston = load_boston()
X = boston.data
y = boston.target
feature_names = boston.feature_names # 特征名称列表
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建SVM回归器(RBF核)
svr = SVR(kernel='rbf', C=100, gamma=0.1)
svr.fit(X_train, y_train)
# 预测并计算指标
y_pred = svr.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred) # R^2分数(越接近1越好)
print(f"均方误差(MSE):{mse:.2f}")
print(f"决定系数(R^2):{r2:.2f}")
# ------------------- 可视化部分 -------------------
plt.figure(figsize=(16, 12))
# 子图1:真实值vs预测值对比
plt.subplot(2, 2, 1)
plt.scatter(y_test, y_pred, alpha=0.7, edgecolor='k', c='royalblue')
# 绘制理想对角线(预测值=真实值)
plt.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=2, label='理想预测线')
plt.xlabel('真实房价 (千美元)')
plt.ylabel('预测房价 (千美元)')
plt.title(f'真实值 vs 预测值 (MSE={mse:.2f}, R^2={r2:.2f})')
plt.legend()
# 子图2:残差分析图(预测误差分布)
plt.subplot(2, 2, 2)
residuals = y_test - y_pred # 残差(真实值-预测值)
plt.scatter(y_pred, residuals, alpha=0.7, edgecolor='k', c='firebrick')
plt.axhline(y=0, color='k', linestyle='--', lw=2, label='无误差线')
plt.xlabel('预测房价 (千美元)')
plt.ylabel('残差 (真实值-预测值)')
plt.title('残差分析图(误差分布)')
plt.legend()
# 子图3:关键特征与目标变量关系(选择RM特征:平均房间数)
plt.subplot(2, 2, 3)
feature_idx = np.where(feature_names == 'RM')[0][0] # 获取"RM"特征的索引
plt.scatter(X_test[:, feature_idx], y_test,
alpha=0.6, edgecolor='k', c='goldenrod', label='真实值')
plt.scatter(X_test[:, feature_idx], y_pred,
alpha=0.6, edgecolor='k', c='darkgreen', marker='x', label='预测值')
plt.xlabel('平均房间数 (RM)')
plt.ylabel('房价 (千美元)')
plt.title('关键特征(RM)与房价的真实/预测关系')
plt.legend()
# 子图4:特征重要性(基于核模型的近似重要性)
plt.subplot(2, 2, 4)
# 计算特征重要性(通过排列重要性近似,需要安装scikit-learn>=0.23)
from sklearn.inspection import permutation_importance
result = permutation_importance(
svr, X_test, y_test, n_repeats=10, random_state=42, n_jobs=2
)
sorted_idx = result.importances_mean.argsort()[::-1] # 降序排列
plt.barh(feature_names[sorted_idx], result.importances_mean[sorted_idx],
color='mediumpurple', edgecolor='k')
plt.xlabel('排列重要性(对模型性能的影响程度)')
plt.title('特征重要性分析(基于排列重要性)')
plt.tight_layout()
plt.show()
测试集准确率:1.00
执行结果: