二分类支持向量机原理
二分类支持向量机(SVM)工作原理详解
定义和支持向量的概念
支持向量机(Support Vector Machine, SVM) 是一种监督学习算法,主要用于解决二分类问题。该方法通过寻找一个最优超平面来区分不同类别的样本点[^3]。
对于线性可分的数据集而言,存在多个可以将两类数据完全分开的超平面;然而,这些超平面并非都是理想的决策边界。为了找到最合适的那个,在所有可能划分空间中的直线里选出距离最近一对正负实例都尽可能远的一条作为最终判定标准——即所谓的最大间隔分离面(Maximum Margin Hyperplane)[^1]。
数学表达形式
假设给定训练样例集合 ( {(x_1,y_1),(x_2,y_2),...,(x_n,y_n)} ),其中每个输入特征向量( x_i\in R^n)对应标签( y_i=\pm1 )表示类别归属,则目标函数为:
[ \min_{w,b}\frac{1}{2}||w||^2 ]
约束条件:
[y_i(w·x_i+b)-1≥0,\quad i=1,...,N]
这里引入拉格朗日乘子法求解上述优化问题,并利用KKT(Karush-Kuhn-Tucker) 条件得到对偶问题的形式化描述。通过对原始最小化问题进行转换获得最大化问题并进一步简化计算过程,从而使得即使面对大规模数据也能高效完成模型构建任务[^2]。
软间隔与核技巧的应用
实际应用中往往难以满足严格的线性不可分情况下的硬边距要求(Hard Margin),因此允许一定程度上的误判现象发生,这就是软边距(Soft Margin)策略的核心思想所在。具体来说就是增加松弛变量ξi>0用于衡量违反不等式的程度,并调整损失项系数C控制整体泛化能力之间的平衡关系。
当遇到非线性的分布模式时,可以通过映射到更高维度的空间内再做线性分割操作实现有效识别目的。这一过程中常用的手段便是采用不同的核函数(kernel function),比如多项式核(Polynomial Kernel)、径向基函数(RBF kernel)等来进行隐式变换而不必显式地提高特征数量级带来的巨大开销。
from sklearn import datasets
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
# 绘制决策曲面
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0],
y=X[y == cl, 1],
alpha=0.8,
c=[cmap(idx)],
marker=markers[idx],
label=f'Class {cl}')
iris = datasets.load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
# 只保留两个类别
X = X[y != 2]
y = y[y != 2]
sc = StandardScaler()
sc.fit(X)
X_std = sc.transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_std, y, test_size=0.3, random_state=1, stratify=y)
svm = SVC(kernel='linear', C=1.0, random_state=1)
svm.fit(X_train, y_train)
plot_decision_regions(X_combined_std, y_combined,
classifier=svm, test_idx=range(105, 150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
相关推荐

















