机器学习模型3——支持向量机SVM

前置知识

拉格朗日乘子法

支持向量机SVM

SVM:SVM全称是supported vector machine(⽀持向量机),即寻找到⼀个超平⾯使样本分成两类,并且间隔最⼤。
SVM能够执⾏线性或⾮线性分类、回归,甚⾄是异常值检测任务。它是机器学习领域最受欢迎的模型之⼀。
SVM特别适⽤于中⼩型复杂数据集的分类。
SVM是⼀种⼆类分类模型
它的基本模型是在特征空间中寻找间隔最⼤化的分离超平⾯的线性分类器。

  • 1)当训练样本线性可分时,通过硬间隔最⼤化,学习⼀个线性分类器,即线性可分⽀持向量机;
  • 2)当训练数据近似线性可分时,引⼊松弛变量,通过软间隔最⼤化,学习⼀个线性分类器,即线性⽀持向量 机;
  • 3)当训练数据线性不可分时,通过使⽤核技巧及软间隔最⼤化,学习⾮线性⽀持向量机。

主要内容:
在这里插入图片描述
所有点到所有分割面的最小距离(垂直距离)的最大值。
软间隔和硬间隔的区别在于:前者允许分割后的集合存在异类,即某些样本不满足约束;后者是完全分割,所有样本都必须划分正确,不允许有划分后的集合存在异类,可能导致过拟合。

线性可分支持向量机(硬间隔)

在这里插入图片描述
样本空间中任意点x到超平⾯(w,b)的距离可写成:
在这里插入图片描述
假设超平⾯(w, b)能将训练样本正确分类,即对于(x , y ) ∈ D,
若y = +1(正倒点),则有w x + b > 0;
若y = −1(负倒点),则有w x + b < 0;

在这里插入图片描述
如图所示,
在这里插入图片描述

距离超平⾯最近的⼏个训练样本点使上式等号成⽴,他们被称为“⽀持向量",
两个异类⽀持向量到超平⾯的距离之和为:
在这里插入图片描述
欲找到具有最⼤间隔的划分超平⾯,也就是要找到能满⾜式
在这里插入图片描述

中约束的参数w和b,使得γ最⼤。
也就是说:

在这里插入图片描述

拉格朗日乘子法求解w和b

第一步:做拉格朗日函数。
在这里插入图片描述

第二步:求参数得偏导,并令之为0。
在这里插入图片描述
但是目标函数还是不能求解,我们将求得的w和b,代⼊原⽬标函数的w和b中,得到的原函数的对偶函数。

对偶问题

实际上就是将目标函数的极小极大 值问题,转换成新函数的极大极小 值问题:
在这里插入图片描述

对偶函数:
在这里插入图片描述
于是我们就开始求解如下的式子:
在这里插入图片描述
只需要对上式求出极⼤值α,然后将α代⼊w求偏导的那个公式从⽽求出w.
将w代⼊超平⾯的表达式,计算b值;
现在的w,b就是我们要寻找的最优超平⾯的参数,代入可求得超平面。
这一部分的求解式子就不写了,理解就好,理解就好。

下面是截取的一个列子:

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

线性支持向量机(软间隔)

在这里插入图片描述w可以看作,正则项(惩罚项),
取平方,可以看作SVM自带L2正则项,防止过拟合
在这里插入图片描述

损失函数

损失函数相当于松弛因子,用来替代线性支持向量机目标函数式子中的松弛因子。
在这里插入图片描述对于损失函数的分析如下:
在这里插入图片描述
绿⾊:0/1损失

  • 当正例的点落在y=0这个超平⾯的下边,说明是分类正确,⽆论距离超平⾯所远多近,误差都是0.
  • 当这个正例的样本点落在y=0的上⽅的时候,说明分类错误,⽆论距离多远多近,误差都为1.

蓝⾊:SVM Hinge损失函数

  • 当⼀个正例的点落在y=1的直线上,距离超平⾯⻓度1,那么1-ξ=1,ξ=0,也就是说误差为0;
  • 当它落在距离超平⾯0.5的地⽅,1-ξ=0.5,ξ=0.5,也就是说误差为0.5;
  • 当它落在y=0上的时候,距离为0,1-ξ=0,ξ=1,误差为1;
  • 当这个点落在了y=0的上⽅,被误分到了负例中,距离算出来应该是负的,⽐如-0.5,那么1-ξ=-0.5,ξ=-1.5.误 差为1.5.
  • 以此类推,画在⼆维坐标上就是上图中蓝⾊那根线了。

红⾊:Logistic损失函数

  • 损失函数的公式为:ln(1 + exp(-yi) )
  • 当y = 0时,损失等于ln2,这样真丑,所以我们给这个损失函数除以ln2.
  • 这样到y = 0时,损失为1,即损失函数过(0,1)点

非线性支持向量机

其实就是高维空间的支持向量机
在这里插入图片描述

常见核函数

在这里插入图片描述

⼀般有如下指导规则:

1) 如果Feature的数量很⼤,甚⾄和样本数量差不多时,往往线性可分,这时选⽤LR或者线性核Linear;
2) 如果Feature的数量很⼩,样本数量正常,不算多也不算少,这时选⽤RBF核;
3) 如果Feature的数量很⼩,⽽样本的数量很⼤,这时⼿动添加⼀些Feature,使得线性可分,然后选⽤LR或 者线性核Linear;
4) 多项式核⼀般很少使⽤,效率不⾼,结果也不优于RBF;
5) Linear核参数少,速度快;RBF核参数多,分类结果⾮常依赖于参数,需要交叉验证或⽹格搜索最佳参 数,⽐较耗时;
6)应⽤最⼴的应该就是RBF核,⽆论是⼩样本还是⼤样本,⾼维还是低维等情况,RBF核函数均适⽤。

支持向量机回归

SVM回归是让尽可能多的实例位于预测线上,同时限制间隔违例(也就是不在预测线距上的实例)。 线距的宽度由超参数ε控制。

SVM优缺点

SVM的优点:
在⾼维空间中⾮常⾼效;
即使在数据维度⽐样本数量⼤的情况下仍然有效;
在决策函数(称为⽀持向量)中使⽤训练集的⼦集,因此它也是⾼效利⽤内存的;
通⽤性:不同的核函数与特定的决策函数⼀⼀对应;
SVM的缺点:
如果特征数量⽐样本数量⼤得多,在选择核函数时要避免过拟合;
对缺失数据敏感;
对于核函数的⾼维映射解释

支持向量机API

svm.LinearSVC([penalty, loss, dual, tol, C, ...])Linear Support Vector Classification.
svm.LinearSVR(*[, epsilon, tol, C, loss, ...])Linear Support Vector Regression.

svm.NuSVC(*[, nu, kernel, degree, gamma, ...])Nu-Support Vector Classification.
svm.NuSVR(*[, nu, C, kernel, degree, gamma, ...])Nu Support Vector Regression.

svm.OneClassSVM(*[, kernel, degree, gamma, ...])Unsupervised Outlier Detection.

svm.SVC(*[, C, kernel, degree, gamma, ...])C-Support Vector Classification.
svm.SVR(*[, kernel, degree, gamma, coef0, ...])Epsilon-Support Vector Regression.

svm.l1_min_c(X, y, *[, loss, fit_intercept, ...])Return the lowest bound for C such that for C in (l1_min_C, infinity) the model is guaranteed not to be empty.

支持向量机的分类器

LinearSVC线性支持向量机

 class sklearn.svm.LinearSVC(penalty='l2', loss='squared_hinge', *, dual=True, tol=0.0001, C=1.0, multi_class='ovr', fit_intercept=True, intercept_scaling=1, class_weight=None, verbose=0, random_state=None, max_iter=1000)

参数

  • penalty:{‘l1’, ‘l2’}, default=’l2’

  • loss:{‘hinge’, ‘squared_hinge’}, default=’squared_hinge’

  • dual: bool, default=True
    是否转化为对偶问题求解。当n_samples>n_features时,首选dual=False。

  • tol:float, default=1e-4
    停止标准公差。

  • C:float, default=1.0
    正则化系数。正则化的强度与C成反比。必须严格为正。⽤来控制损失函数的惩罚系数,类似于线性回归中的正则化系数。 C越⼤,相当于惩罚松弛变量,希望松弛变量接近0,即对误分类的惩罚增⼤,趋向于对训练集全分对的情 况,这样会出现训练集测试时准确率很⾼,但泛化能⼒弱,容易导致过拟合。 C值⼩,对误分类的惩罚减⼩,容错能⼒增强,泛化能⼒较强,但也可能⽋拟合。

  • multi_class:{‘ovr’, ‘crammer_singer’}, default=’ovr’
    如果y包含两个以上的类,则确定多类策略。“ovr”训练n_classes-one与rest分类器,而“cramersinger”优化所有类的联合目标。虽然从理论角度来看,cramer_singer很有趣,因为它是一致的,但在实践中很少使用,因为它很少导致更好的精度,而且计算成本更高。如果选择“cramer_singer”,则选项损失(loss)、惩罚(penalty)和对偶(dual)将被忽略。

  • fit_intercept:bool, default=True
    是否计算此模型的截距。如果设置为false,则计算中将不使用截距(即数据预计已居中)。

  • intercept_scaling:float, default=1

      When self.fit_intercept is True, instance vector x becomes [x, self.intercept_scaling], i.e. a “synthetic” feature with constant value equals to intercept_scaling is appended to the instance vector. The intercept becomes intercept_scaling * synthetic feature weight Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased.
    
  • class_weight:dict or ‘balanced’, default=None
    Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)).

  • verbose:int, default=0
    Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in liblinear that, if enabled, may not work properly in a multithreaded context.

  • random_state:int, RandomState instance or None, default=None
    Controls the pseudo random number generation for shuffling the data for the dual coordinate descent (if dual=True). When dual=False the underlying implementation of LinearSVC is not random and random_state has no effect on the results. Pass an int for reproducible output across multiple function calls. See Glossary.

  • max_iter:int, default=1000
    要运行的最大迭代次数。

属性:

  • coef_:ndarray of shape (1, n_features) if n_classes == 2 else (n_classes, n_features)
    Weights assigned to the features (coefficients in the primal problem).
    coef_ is a readonly property derived from raw_coef_ that follows the internal memory layout of liblinear.
  • intercept_: ndarray of shape (1,) if n_classes == 2 else (n_classes,)
    Constants in decision function.
  • classes_:ndarray of shape (n_classes,)
    The unique classes labels.
  • n_features_in_:int
    Number of features seen during fit.New in version 0.24.
  • feature_names_in_:ndarray of shape (n_features_in_,)
    Names of features seen during fit. Defined only when X has feature names that are all strings.
    n_iter_: int
    Maximum number of iterations run across all classes.
    很多都是和决策树或者线性回归的参数和属性是一样的,就不展开了。
    在这里插入图片描述

SVC非线性支持向量机(核函数)

 class sklearn.svm.SVC(*, C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape='ovr', break_ties=False, random_state=None)
  • kernel: 算法中采⽤的核函数类型,核函数是⽤来将⾮线性问题转化为线性问题的⼀种⽅法。 参数选择有RBF, Linear, Poly, Sigmoid或者⾃定义⼀个核函数。 默认的是"RBF",即径向基核,也就是⾼斯核函数; ⽽Linear指的是线性核函数, Poly指的是多项式核, Sigmoid指的是双曲正切函数tanh核;。
  • degree: 当指定kernel为’poly’时,表示选择的多项式的最⾼次数,默认为三次多项式;
    若指定kernel不是’poly’,则忽略,即该参数只对’poly’有⽤。 多项式核函数是将低维的输⼊空间映射到⾼维的特征空间。
  • coef0: 核函数常数值(y=kx+b中的b值), 只有‘poly’和‘sigmoid’核函数有,默认值是0。

NuSVC

Similar to SVC but uses a parameter to control the number of support vectors. The implementation is based on libsvm.

class sklearn.svm.NuSVC(*, nu=0.5, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape='ovr', break_ties=False, random_state=None)

nu: 训练误差部分的上限和⽀持向量部分的下限,取值在(0,1)之间,默认是0.5

参考

1.黑马机器学习
2.https://www.bilibili.com/video/BV1Ca411M7KA/?p=8&spm_id_from=333.880.my_history.page.click&vd_source=c35b16b24807a6dbe33f5473659062ac
3.《机器学习》周志华

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>