支持向量的定义:在训练过程中,SVM学习每个训练数据对于表示两个类别之间的决策边界的重要性。通常只有一部分训练数据点对于定义决策边界来说很重要:位于类别之间的边界上的那些店,这些点就叫做支持向量。
想要对新样本进行预测,需要测量它与每个支持向量之间的距离以及在训练过程中学到的支持向量的重要性(保存在SVC的dual_coef_属性中)做出来的。下面我们以forge数据集训练SVM为例,对应代码如下:
from sklearn.svm import SVC
import mglearn
x, y = mglearn.tools.make_handcrafted_dataset()
svm = SVC(kernel='rbf', C=10, gamma=0.1).fit(x, y)
mglearn.plots.plot_2d_separator(svm, x, eps=.5)
mglearn.discrete_scatter(x[:, 0], x[:, 1], y)
#画出支持向量
sv = svm.support_vectors_
#支持向量的类别标签有dual_coef_的正负号给出
sv_labels = svm.dual_coef_.ravel() > 0
mglearn.discrete_scatter(sv[:, 0], sv[:, 1], sv_labels, s=15, markeredgewidth=3)
plt.xlabel("Feature 0")
plt.ylabel("feature 1")
运行后结果如下: