2010-04-23 13:52:16 +08:00
|
|
|
"""
|
2010-11-02 18:38:06 +08:00
|
|
|
==============
|
2010-04-23 13:52:16 +08:00
|
|
|
Non-linear SVM
|
2010-11-02 18:38:06 +08:00
|
|
|
==============
|
2010-04-23 13:52:16 +08:00
|
|
|
|
2010-11-02 18:38:06 +08:00
|
|
|
Perform binary classification using non-linear SVC
|
|
|
|
|
with RBF kernel. The target to predict is a XOR of the
|
|
|
|
|
inputs.
|
2010-08-20 21:45:14 +08:00
|
|
|
|
2015-07-15 09:37:08 +08:00
|
|
|
The color map illustrates the decision function learned by the SVC.
|
2021-10-22 21:33:22 +08:00
|
|
|
|
2010-04-23 13:52:16 +08:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import numpy as np
|
2014-05-15 04:31:03 +08:00
|
|
|
import matplotlib.pyplot as plt
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn import svm
|
2010-04-23 13:52:16 +08:00
|
|
|
|
2011-12-30 18:57:17 +08:00
|
|
|
xx, yy = np.meshgrid(np.linspace(-3, 3, 500), np.linspace(-3, 3, 500))
|
2010-04-23 13:52:16 +08:00
|
|
|
np.random.seed(0)
|
|
|
|
|
X = np.random.randn(300, 2)
|
2011-12-17 05:55:42 +08:00
|
|
|
Y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0)
|
2010-04-23 13:52:16 +08:00
|
|
|
|
|
|
|
|
# fit the model
|
2019-01-17 18:41:13 +08:00
|
|
|
clf = svm.NuSVC(gamma="auto")
|
2010-04-23 13:52:16 +08:00
|
|
|
clf.fit(X, Y)
|
|
|
|
|
|
2011-12-17 05:55:42 +08:00
|
|
|
# plot the decision function for each datapoint on the grid
|
2011-12-17 05:46:28 +08:00
|
|
|
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
|
2010-04-23 13:52:16 +08:00
|
|
|
Z = Z.reshape(xx.shape)
|
|
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.imshow(
|
|
|
|
|
Z,
|
|
|
|
|
interpolation="nearest",
|
2014-05-15 10:35:13 +08:00
|
|
|
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
|
|
|
|
|
aspect="auto",
|
|
|
|
|
origin="lower",
|
|
|
|
|
cmap=plt.cm.PuOr_r,
|
|
|
|
|
)
|
2014-05-15 04:31:03 +08:00
|
|
|
contours = plt.contour(xx, yy, Z, levels=[0], linewidths=2, linestyles="dashed")
|
2017-03-05 00:22:00 +08:00
|
|
|
plt.scatter(X[:, 0], X[:, 1], s=30, c=Y, cmap=plt.cm.Paired, edgecolors="k")
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.xticks(())
|
|
|
|
|
plt.yticks(())
|
|
|
|
|
plt.axis([-3, 3, -3, 3])
|
|
|
|
|
plt.show()
|