sklearn库实现SVM

来源:互联网 发布:如何删除部落冲突数据 编辑:程序博客网 时间:2024/06/08 03:40

python scikit-learn库

实现SVM

1.SVC(Support Vector Classification)支持向量分类

基于libsvm实现的(libsvm详情参考 或者百科),数据拟合的时间复杂度是数据样本的二次方,这使得他很难扩展到10000个数据集。

当输入是多类别时(SVM最初是处理二分类问题的),通过一对一的方案解决,当然也有别的解决办法,比如说(以下为引用):其他多类分类方法。除了以上几种方法外,还有有向无环图SVM(Directed Acyclic Graph SVMs,简称DAG-SVMs)和对类别进行二进制编码的纠错编码SVMs。

SVC参数解释:

#SVC参数解释 #(1)C: 目标函数的惩罚系数C,用来平衡分类间隔margin和错分样本的,default C = 1.0; #(2)kernel:参数选择有RBF, Linear, Poly, Sigmoid, 默认的是"RBF"; #(3)degree:if you choose 'Poly' in param 2, this is effective, degree决定了多项式的最高次幂; #(4)gamma:核函数的系数('Poly', 'RBF' and 'Sigmoid'), 默认是gamma = 1 / n_features; #(5)coef0:核函数中的独立项,'RBF' and 'Poly'有效; #(6)probablity: 可能性估计是否使用(true or false); #(7)shrinking:是否进行启发式; #(8)tol(default = 1e - 3): svm结束标准的精度; #(9)cache_size: 制定训练所需要的内存(以MB为单位); #(10)class_weight: 每个类所占据的权重,不同的类设置不同的惩罚参数C, 缺省的话自适应; #(11)verbose: 跟多线程有关;#(12)max_iter: 最大迭代次数,default = 1, if max_iter = -1, no limited; #(13)decision_function_shape : ‘ovo’ 一对一, ‘ovr’ 多对多  or None 无, default=None #(14)random_state :用于概率估计的数据重排时的伪随机数生成器的种子。 # ps:7,8,9一般不考虑。 

sklearn中调用机器学习的方法都是一个道理,算法就是一个类,其中包含fit(),predict()等等许多方法,我们只要输入训练样本和标记,以及模型的一些可能的参数,自然就直接出分类的结果。

示例:

X = np.array([[-1,-1],[-2,-1],[1,1],[2,1]])y = np.array([1,1,2,2])from sklearn.svm import SVCneg = y[:] == 1pos = y[:] == 2axes = plt.gca()axes.scatter(X[pos][0],X[pos][1],marker='+',c='k',s=60,linewidth=2,label='Pass')axes.scatter(X[neg][0],X[neg][1],c='y',s=60,linewidth=2,label='Fail')#在散点图上输入预测点axes.scatter(-0.8,-1,c='r',s=60,linewidth=2,label='Predict')axes.legend(frameon=True, fancybox=True)#绘制散点图clf = SVC()clf.fit(X,y)                  #所有分类器都有这些性质print clf.fit(X,y)            #打印svc训练函数的参数print clf.predict([-0.8,-1])  #利用分类器训练结果预测输入list形式的特征向量

输出:

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,  decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',  max_iter=-1, probability=False, random_state=None, shrinking=True,  tol=0.001, verbose=False)[1]

这里写图片描述

2.NuSVC(Nu-Support Vector Classification)核支持向量分类

和SVC类似,也是基于libsvm实现的,但不同的是通过一个参数空值支持向量的个数

#NuSVC参数 #nu:训练误差的一个上界和支持向量的分数的下界。应在间隔(0,1 ]。 #其余同SVC import numpy as np  X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])  y = np.array([1, 1, 2, 2])  from sklearn.svm import NuSVC  clf = NuSVC()  clf.fit(X, y)   print clf.fit(X,y)  print(clf.predict([[-0.8, -1]]))    

3.LinearSVC(Linear Support Vector Classification)

线性支持向量分类

类似于SVC,但是其使用的核函数是”linear“上边介绍的两种是按照RBF(径向基函数)计算的,其实现也不是基于LIBSVM,所以它具有更大的灵活性在选择处罚和损失函数时,而且可以适应更大的数据集,他支持密集和稀疏的输入是通过一对一的方式解决的。

LinearSVC 参数解释  C:目标函数的惩罚系数C,用来平衡分类间隔margin和错分样本的,default C = 1.0;  loss :指定损失函数  penalty :  dual :选择算法来解决对偶或原始优化问题。当n_samples > n_features 时dual=false。  tol :(default = 1e - 3): svm结束标准的精度;  multi_class:如果y输出类别包含多类,用来确定多类策略, ovr表示一对多,“crammer_singer”优化所有类别的一个共同的目标  如果选择“crammer_singer”,损失、惩罚和优化将会被被忽略。  fit_intercept :  intercept_scaling :  class_weight :对于每一个类别i设置惩罚系数C = class_weight[i]*C,如果不给出,权重自动调整为 n_samples / (n_classes * np.bincount(y))  verbose:跟多线程有关

示例:

import numpy as npX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])y = np.array([1, 1, 2, 2])from sklearn.svm import LinearSVCclf = LinearSVC()clf.fit(X, y) print clf.fit(X,y)print(clf.predict([[-0.8, -1]] 

4.数据不平衡问题(Unbalanced problems)

对于非平衡级分类超平面,使用不平衡SVC找出最优分类超平面,基本的思想是,我们先找到一个普通的分类超平面,自动进行校正,求出最优的分类超平面

这里可以使用 SVC(kernel=”linear”)

针对下面的svc可以使用 clf=SGDClassifie(n_iter=100,alpha=0.01)代替

rng = np.random.RandomState(0)n_samples_1 = 1000n_samples_2 = 100X = np.r_[1.5*rng.randn(n_samples_1,2),0.5*rng.randn(n_samples_2,2)+[2,2]]#rng.randn(x,y)生成x*y的矩阵,元素都是标准化#这里先生成1000个[0~1.5]的[a,b]list#之后生成100个[2~2.5]的[a,b]list排在后面y = [0]*(n_samples_1)+[1]*(n_samples_2)#生成1000个[0]list,与100个[1]list排在后面print X.shapeprint Xprint y#随机生成数据集

输出结果:

(1100, 2)[[ 2.64607852  0.60023581] [ 1.46810698  3.3613398 ] [ 2.80133699 -1.46591682] ...,  [ 1.68550965  2.53503626] [ 1.68945865  2.86728609] [ 1.45085528  2.28630668]][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...,1, 1, 1]
clf = SVC(kernel='linear', C=1.0)  clf.fit(X, y)  w = clf.coef_[0]      a = -w[0] / w[1]      #a可以理解为斜率  xx = np.linspace(-5, 5)  #产生x值为-5至5的50个均匀的x坐标yy = a * xx - clf.intercept_[0] / w[1] #二维坐标下的直线方程由Ax+By=C#clf.coef_表示[A,B],C即为clf.intercept_h0 = plt.plot(xx, yy, 'k-', label='no weights')  #没有权重的分类直线# get the separating hyperplane using weighted classes  wclf = SVC(kernel='linear', class_weight={1: 10})  #设定两个类的权重为1:10wclf.fit(X, y)  ww = wclf.coef_[0]  wa = -ww[0] / ww[1]  wyy = wa * xx - wclf.intercept_[0] / ww[1]   #带权重的直线  # plot separating hyperplanes and samples  h1 = plt.plot(xx, wyy, 'k--', label='with weights')  plt.scatter(X[:, 0], X[:, 1], c=y,s=5,linewidth=0.5)  #s表示散点图点的大小plt.legend()  plt.axis('tight')  plt.show()

这里写图片描述

随机数种子RandomState

RandomState exposes a number of methods for generating random numbersdrawn from a variety of probability distributions.

使用示例:

prng = np.random.RandomState(123456789) # 定义局部种子prng.rand(2, 4)prng.chisquare(1, size=(2, 2)) # 卡方分布prng.standard_t(1, size=(2, 3)) # t 分布prng.poisson(5, size=10) # 泊松分布

clf.coef_,clf.intercept_用法

clf.coef_表示回归直线的参数

clf.intercept_表示回归直线截距

二维坐标下的直线方程由Ax+By=C,clf.coef_表示[A,B],C即为clf.intercept_

5.SVR(Support Vector Regression)支持向量回归

支持分类的支持向量机可以推广到解决回归问题,这种方法称为支持向量回归

支持向量分类所产生的模型仅仅依赖于训练数据的一个子集,因为构建模型的成本函数不关心在超出边界范围的点,类似的,通过支持向量回归产生的模型依赖于训练数据的一个子集,因为构建模型的函数忽略了靠近预测模型的数据集。

有三种不同的实现方式:支持向量回归SVR,nusvr和linearsvr。linearsvr提供了比SVR更快实施但只考虑线性核函数,而nusvr实现比SVR和linearsvr略有不同

from sklearn.svm import SVRX = np.sort(5 * np.random.rand(40, 1), axis=0)  #产生40组数据,每组一个数据,axis=0决定按列排列,=1表示行排列  y = np.sin(X).ravel()   #np.sin()输出的是列,和X对应,ravel表示转换成行 y[::5] += 3 * (0.5 - np.random.rand(8)) #每5个进行一下随机处理,噪声点svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)  svr_lin = SVR(kernel='linear', C=1e3)  svr_poly = SVR(kernel='poly', C=1e3, degree=2)  #三种回归核函数y_rbf = svr_rbf.fit(X, y).predict(X)  y_lin = svr_lin.fit(X, y).predict(X)  y_poly = svr_poly.fit(X, y).predict(X)  #可视化lw = 2  plt.scatter(X, y, color='darkorange', label='data')  plt.hold('on')  plt.plot(X, y_rbf, color='navy', lw=lw, label='RBF model')  plt.plot(X, y_lin, color='c', lw=lw, label='Linear model')  plt.plot(X, y_poly, color='cornflowerblue', lw=lw, label='Polynomial model')  plt.xlabel('data')  plt.ylabel('target')  plt.title('Support Vector Regression')  plt.legend()  plt.show()

输出:

这里写图片描述