参考资料
<PYTHON_MACHINE_LEARNING> chapter3
Maximum margin classifcation with
support vector machines
引言
在学习了逻辑回归之后,我们回顾一下目前已经学习的机器学习模型:Perceptron感知机, Adaline自适应线性单元, LogisticRegression逻辑回归, 这些模型有一个共同点:他们处理的都是样本线性可分的分类问题,为了处理非线性可分问题,我们引入了支持向量机SVM
线性可分VS线性不可分
- 线性可分
线性可分(Linearly Separable)指的是,对于一个样本,数据可以在空间中被一个或多个超平面(hyperplane)被分成显然的若干类。
In geometry a hyperplane is a subspace of one dimension less than its ambient space. If a space is 3-dimensional then its hyperplanes are the 2-dimensional planes, while if the space is 2-dimensional, its hyperplanes are the 1-dimensional lines. -- from wikipedia
-
线性不可分
定义则相反
边界(margin)与支持向量(SV)
对于一组线性可分的数据,我们知道能将他们分类的超平面(secision hyperplane)并不是唯一的,如何找到最佳的分类超平面呢?我们把与分类超平面平行且经过离分类超平面最近的样本点的平面称之为决策边界(decision boundary)
我们先定义一下分类间隔margin.,它是两个决策边界的距离。对于能使margin最大的那个超平面就是我们寻找的超平面。
这些在决策边界上的向量被称之为支持向量
这样的分类器被称之为支持向量机

现在我们来看一看这样做的数学意义
如图所示,两条决策边界分别被命名为 “negative hyperplane”,“positive hyperplane” 我们试图求出分类间隔也就是他们之间的距离
对于平面内两条平行直线
**
A(x-x1)+B(y-y1)=0
A(x-x2)+B(y-y2)=0
**
他们之间的距离可以表示为
d=|C1-C2|/√(A2+B2) ** C1=Ax1+By1, C2=Ax2+By2
令X1=[x1,y1]' , X2=[x2,y2]', w=[A,B]'**
则有
**
w'X1=C1
w'X2=C2
**
距离可以表示为
**
d = |C1-C2| / || w ||
**
这就是一般情况下两个平行的超平面的距离公式
对于支持向量机而言
分类间隔 margin
分类间隔可以这么得到


得到分类间隔

其中

当分类间隔 magrin 最大的时候,很显然,我们的模型能给出最大的区分度,相应的预测的准确性也就越高,所以,对于 支持向量机SVM 来说,它的实现是通过最大化分类间隔实现的。
对于一个 -1,1 的二分类,我们有

化简一下

我们的目标就是在这种条件下求出

的最大值
这个问题可以用 拉格朗日乗法子 解决,这里暂且按下不表
使用松弛变量处理非线性类问题
在线性不可分的情况下,无论怎么划分超平面,都会存在一些样本在边界之外,也就是说

这种情况下,我们使用松弛变量来放宽条件

这些松弛变量都是非负数,也就是说我们允许一定的偏差存在,但然,这也是有代价的,那就是我们要最小化的损失函数要相应的变大

这里的C就是惩罚因子,C越大,这意味着我们越重视这些偏差点的影响,需要注意的是,惩罚因子C不是一个变量,在拟合的时候C需要时一个定值,查看预测结果的时候需要检查结果是否理想,不理想的话需要更改C的值重新拟合一遍
sklearn.svm 的实现
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 22 11:08:17 2017
@author: Administrator
"""
from sklearn.svm import SVC
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from PDC import plot_decision_regions
import matplotlib.pyplot as plt
import numpy as np
Iris = datasets.load_iris()
x = Iris.data[:,[2,3]]
y = Iris.target
X_train,X_test,y_train,y_test = train_test_split(
x,y,test_size=0.3,random_state=0)
sc=StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)
svm = SVC(kernel='linear',C=1.0,random_state=0)
svm.fit(X_train_std,y_train)
X_combined_std = np.vstack((X_train_std,X_test_std))
y_combined = np.hstack((y_train,y_test))
plot_decision_regions(X=X_combined_std,y=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.show()
plt.savefig('Iris.png')
plt.show()
结果如下

网友评论