9.2 示例:hello world!支持向量机

我们先演示支持向量机的基础使用,完整演示代码请见本书GitHub上的9-1.py。

导入库文件:


print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

创建40个随机点:


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 the model
clf = svm.SVC(kernel='linear')
clf.fit(X, Y)

构造超平面:


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])

调用matplotlib画图:


plt.plot(xx, yy, 'k-')
plt.plot(xx, yy_down, 'k--')
plt.plot(xx, yy_up, 'k--')
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
            s=80, facecolors='none')
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.axis('tight')
plt.show()

运行代码:


localhost:code maidou$ python 9-1.py 
None
localhost:code maidou$

SVM hello word代码如图9-9所示。

图9-9 SVM hello word代码