6.2 支持向量机应用(上)

1 sklearn简单例子

# -*- coding:utf-8 -*-
from sklearn import svm

X=[[2,0],[1,1],[2,3]]
y=[0,0,1]
clf=svm.SVC(kernel='linear')
clf.fit(X,y)
print clf
print clf.support_vectors_  #get support vectors
print clf.n_support_ #get number of support vectors fot each class

2.sklearn画出决定界限

import numpy as np
import pylab as pl
from sklearn import svm

#create 40 separable points
np.random.seed(0)
X=np.r_[np.random.randn(20,2)-[2,2],np.random.randn(20,2)+[2,2]]
Y=[0]*20+[1]*20

#fit model
clf=svm.SVC(kernel='linear')
clf.fit(X,Y)

# get the separation hyperplane
w=clf.coef_[0]
a=-w[0]/w[1]
xx=np.linspace(-5,5)
yy=a*xx-(clf.intercept_[0]/w[1])

#plot the parallels to the separating hyperplane that pass through the support vectors
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_vectors_:",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,facecolor='none')
pl.scatter(X[:,0],X[:,1],c=Y)
#pl.axis('tight')
pl.show()

你可能感兴趣的:(深度学习基础课程笔记)