当前位置: 代码迷 >> 综合 >> python sklearn.svm.SVC支持向量机实例
  详细解决方案

python sklearn.svm.SVC支持向量机实例

热度:87   发布时间:2023-12-08 23:52:30.0

分类

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm,datasetsdef make_meshgrid(x,y,h=.02):x_min,x_max=x.min()-1,x.max()+1y_min,y_max=y.min()-1,y.max()+1xx,yy=np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))return xx,yydef plot_contours(ax,clf,xx,yy,**params):z=clf.predict(np.c_[xx.ravel(),yy.ravel()])z=z.reshape(xx.shape)out=ax.contourf(xx,yy,z,**params)return outiris=datasets.load_iris()
x=iris.data[:,:2]
y=iris.targetc=1.0
models=(svm.SVC(kernel='linear',C=c),svm.LinearSVC(C=c,max_iter=10000),svm.SVC(kernel='rbf',gamma=0.7,C=c),svm.SVC(kernel='poly',degree=3,gamma='auto',C=c))
models=(clf.fit(x,y) for clf in models)titles=('SVC with linear kernel','LinearSVC(linear kernel)','SVC with RBF kernel','SVC with polynomial (degree 3) kernel')
fig,sub=plt.subplots(2,2)
plt.subplots_adjust(wspace=0.4,hspace=0.4)x0,x1=x[:,0],x[:,1]
xx,yy=make_meshgrid(x0,x1)for clf,title,ax in zip(models,titles,sub.flatten()):plot_contours(ax,clf,xx,yy,cmap=plt.cm.coolwarm,alpha=0.8)ax.scatter(x0,x1,c=y,cmap=plt.cm.coolwarm,s=20,edgecolors='k')ax.set_xlim(xx.min(),xx.max())ax.set_ylim(yy.min(),yy.max())ax.set_xlabel('sepal length')ax.set_ylabel('sepal width')ax.set_xticks(())ax.set_yticks(())ax.set_title(title)plt.show()

分割超平面

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_blobsX,y=make_blobs(n_samples=40,centers=2,random_state=6)
print(X,y)clf=svm.SVC(kernel='linear',C=1000)
clf.fit(X,y)
plt.scatter(X[:,0],X[:,1],c=y,s=30,cmap=plt.cm.Paired)ax=plt.gca()
xlim=ax.get_xlim()
ylim=ax.get_ylim()xx=np.linspace(xlim[0],xlim[1],30)
yy=np.linspace(ylim[0],ylim[1],30)
YY,XX=np.meshgrid(yy,xx)
print(YY)
xy=np.vstack([XX.ravel(),YY.ravel()]).T
Z=clf.decision_function(xy).reshape(XX.shape)ax.contour(XX,YY,Z,colors='k',levels=[-1,0,1],alpha=0.5,linestyles=['--','-','--'])
ax.scatter(clf.support_vectors_[:,0],clf.support_vectors_[:,1],s=100,linewidth=1,facecolors='none',edgecolors='k')
plt.show()