import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=50, centers=2, random_state=6)
clf = svm.SVC(kernel='linear', C=1000)
clf.fit(X, y)
# plot the samples
# paired表示两个两个相近色彩输出,比如浅蓝、深蓝;浅红、深红;浅绿,深绿这种。
plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired, edgecolors='k')
# plot the decision functions for both classifiers
#plt.plot()实际上会通过plt.gca()获得当前的Axes对象ax,然后再调用ax.plot()方法实现真正的绘图。
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# create grid to evaluate model
xx = np.linspace(xlim[0], xlim[1], 30)
yy = np.linspace(ylim[0], ylim[1], 30)
YY, XX = np.meshgrid(yy, xx)
#vstack返回结果为numpy的数组
xy = np.vstack([XX.ravel(), YY.ravel()]).T
# get the separating hyperplane
# desion函数告诉我们分类器生成的超平面的哪一侧(以及我们远离它的距离)
Z = clf.decision_function(xy).reshape(XX.shape)
# 把分类的决定边界画出来
# 等高线图显示矩阵 Z 的等值线
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'
)
plt.show()
SVM支持向量机sklearn代码V3
于 2020-07-24 16:29:19 首次发布