支持向量机(一)

来源:互联网 发布:java常用包及类 编辑:程序博客网 时间:2024/06/05 17:05
 一.理论
1.背景
1)历史发展:1963年提出,目前的版本是1993年提出
2)历史地位:深度学习出现之前(2012),倍认为最成功、表现最好的算法‘
2.机器学习的一般框架
训练集--->提取特征向量 --->结合一定的算法(分类器:比如决策树、KNN)--->得到结果
3.介绍

1)例子


两类?那条线分割较好?

2)SVM寻找区分两类的超平面(hyper plane),使边际(margin)最大


3)思考:
总共有多少个超平面?无数个
如何选取边际最大的超平面(Max Margin Hyperplane)
超平面到一侧最近点的距离等于另一侧最近点的距离,两侧的两个超平面平行

4)线性可区分(linear separable)和线性不可区分(linear inseparable)


4.定义和建立公式

5.求解
二.实践

1.简单实例实现

1)代码

#SVM的简单实例from sklearn import svm#定义坐标x = [[2,0],[1,1],[2,3]]#对坐标进行分类,下边为0,上边为1y = [0,0,1]#核函数:线性clf = svm.SVC(kernel='linear')#模型生成clf.fit(x,y)print(clf)#支持向量的坐标print(clf.support_vectors_)# 支持向量的索引print(clf.support_)#每个类中包含支持向量的个数print(clf.n_support_)#对输入结果预测print(clf.predict([2,1]))
2)结果

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

2.图形方式显示分类结果

1)代码

# -*- coding: utf-8 -*-import numpy as np  #矩阵运算import matplotlib.pyplot as pl  #画图from sklearn import svm   #SVM#固定每次抓取的值np.random.seed(0)#随机产生均值为20,方差为2的正态分布数据X = np.r_[np.random.randn(20,2)-[2,2],np.random.randn(20,2)+[2,2]]#对顺训练数据进行分类Y = [0]*20+[1]*20print(X)print(Y)#建立模型clf = svm.SVC(kernel='linear')clf.fit(X,Y)#计算点斜式方程w = clf.coef_[0]#计算斜率a = - w[0]/w[1]#产生连续的X值xx = np.linspace(-5,5)#点斜式方程yy = a*xx-(clf.intercept_[0])/w[1]b = clf.support_vectors_[0]yy_down = a*xx+(b[1]-a*b[0])#取另外一类b = clf.support_vectors_[-1]yy_up = a*xx+(b[1])-a*b[0]print("w:",w)print("a:",a)print("support_vector:",clf.support_vectors_)print("clf.coef",clf.coef_)pl.plot(xx,yy,"k-")pl.plot(xx,yy_down,"k--")pl.plot(xx,yy_up,"k--")#把对应位置圈出来pl.scatter(clf.support_vectors_[:,0],clf.support_vectors_[:,1],s=80,facecolors="none")pl.scatter(X[:,0],X[:,1],c=Y,cmap=pl.cm.Paired)pl.axis("tight")pl.show()
2)结果
[[-0.23594765 -1.59984279] [-1.02126202  0.2408932 ] [-0.13244201 -2.97727788] ...,  [ 2.40234164  1.31518991] [ 1.12920285  1.42115034] [ 1.68844747  2.05616534]][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]w: [ 0.90230696  0.64821811]a: -1.39198047626support_vector: [[-1.02126202  0.2408932 ] [-0.46722079 -0.53064123] [ 0.95144703  0.57998206]]clf.coef [[ 0.90230696  0.64821811]]

原创粉丝点击