2012-03-12 17:19:01 +08:00
|
|
|
"""
|
|
|
|
|
================================
|
|
|
|
|
SVM Exercise
|
|
|
|
|
================================
|
|
|
|
|
|
2013-07-22 21:48:44 +08:00
|
|
|
A tutorial exercise for using different SVM kernels.
|
|
|
|
|
|
2012-04-28 04:53:09 +08:00
|
|
|
This exercise is used in the :ref:`using_kernels_tut` part of the
|
|
|
|
|
:ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`.
|
2012-03-12 17:19:01 +08:00
|
|
|
"""
|
2013-02-01 22:04:03 +08:00
|
|
|
print(__doc__)
|
2012-03-12 17:19:01 +08:00
|
|
|
|
|
|
|
|
|
2011-12-18 19:39:53 +08:00
|
|
|
import numpy as np
|
2014-05-15 04:31:03 +08:00
|
|
|
import matplotlib.pyplot as plt
|
2012-04-28 04:53:09 +08:00
|
|
|
from sklearn import datasets, svm
|
2011-12-18 19:39:53 +08:00
|
|
|
|
|
|
|
|
iris = datasets.load_iris()
|
|
|
|
|
X = iris.data
|
|
|
|
|
y = iris.target
|
|
|
|
|
|
2012-04-28 04:53:09 +08:00
|
|
|
X = X[y != 0, :2]
|
2012-05-03 03:29:29 +08:00
|
|
|
y = y[y != 0]
|
2011-12-18 19:39:53 +08:00
|
|
|
|
|
|
|
|
n_sample = len(X)
|
|
|
|
|
|
|
|
|
|
np.random.seed(0)
|
|
|
|
|
order = np.random.permutation(n_sample)
|
|
|
|
|
X = X[order]
|
2020-06-24 22:51:51 +08:00
|
|
|
y = y[order].astype(float)
|
2011-12-18 19:39:53 +08:00
|
|
|
|
2017-02-03 22:21:03 +08:00
|
|
|
X_train = X[:int(.9 * n_sample)]
|
|
|
|
|
y_train = y[:int(.9 * n_sample)]
|
|
|
|
|
X_test = X[int(.9 * n_sample):]
|
|
|
|
|
y_test = y[int(.9 * n_sample):]
|
2011-12-18 19:39:53 +08:00
|
|
|
|
|
|
|
|
# fit the model
|
2019-03-27 23:01:11 +08:00
|
|
|
for kernel in ('linear', 'rbf', 'poly'):
|
2011-12-18 19:39:53 +08:00
|
|
|
clf = svm.SVC(kernel=kernel, gamma=10)
|
|
|
|
|
clf.fit(X_train, y_train)
|
|
|
|
|
|
2019-03-27 23:01:11 +08:00
|
|
|
plt.figure()
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.clf()
|
2017-06-28 20:56:27 +08:00
|
|
|
plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired,
|
|
|
|
|
edgecolor='k', s=20)
|
2011-12-18 19:39:53 +08:00
|
|
|
|
|
|
|
|
# Circle out the test data
|
2017-06-28 20:56:27 +08:00
|
|
|
plt.scatter(X_test[:, 0], X_test[:, 1], s=80, facecolors='none',
|
|
|
|
|
zorder=10, edgecolor='k')
|
2011-12-18 19:39:53 +08:00
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.axis('tight')
|
2012-04-28 04:53:09 +08:00
|
|
|
x_min = X[:, 0].min()
|
|
|
|
|
x_max = X[:, 0].max()
|
|
|
|
|
y_min = X[:, 1].min()
|
|
|
|
|
y_max = X[:, 1].max()
|
2011-12-18 19:39:53 +08:00
|
|
|
|
|
|
|
|
XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
|
|
|
|
|
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
|
|
|
|
|
|
|
|
|
|
# Put the result into a color plot
|
|
|
|
|
Z = Z.reshape(XX.shape)
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired)
|
2017-02-03 22:21:03 +08:00
|
|
|
plt.contour(XX, YY, Z, colors=['k', 'k', 'k'],
|
|
|
|
|
linestyles=['--', '-', '--'], levels=[-.5, 0, .5])
|
2011-12-18 19:39:53 +08:00
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.title(kernel)
|
|
|
|
|
plt.show()
|