2010-05-17 17:25:35 +08:00
|
|
|
"""
|
|
|
|
|
======================
|
|
|
|
|
SVM with custom kernel
|
|
|
|
|
======================
|
|
|
|
|
|
|
|
|
|
Simple usage of Support Vector Machines to classify a sample. It will
|
|
|
|
|
plot the decision surface and the support vectors.
|
|
|
|
|
|
|
|
|
|
"""
|
2013-02-01 22:04:03 +08:00
|
|
|
print(__doc__)
|
2010-11-02 18:38:06 +08:00
|
|
|
|
2010-05-17 17:25:35 +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, datasets
|
2010-05-17 17:25:35 +08:00
|
|
|
|
|
|
|
|
# import some data to play with
|
|
|
|
|
iris = datasets.load_iris()
|
2011-12-17 05:55:42 +08:00
|
|
|
X = iris.data[:, :2] # we only take the first two features. We could
|
|
|
|
|
# avoid this ugly slicing by using a two-dim dataset
|
2010-05-17 17:25:35 +08:00
|
|
|
Y = iris.target
|
|
|
|
|
|
|
|
|
|
|
2015-07-29 22:52:28 +08:00
|
|
|
def my_kernel(X, Y):
|
2010-05-17 17:25:35 +08:00
|
|
|
"""
|
|
|
|
|
We create a custom kernel:
|
|
|
|
|
|
|
|
|
|
(2 0)
|
2015-07-29 22:52:28 +08:00
|
|
|
k(X, Y) = X ( ) Y.T
|
2010-05-17 17:25:35 +08:00
|
|
|
(0 1)
|
|
|
|
|
"""
|
|
|
|
|
M = np.array([[2, 0], [0, 1.0]])
|
2015-07-29 22:52:28 +08:00
|
|
|
return np.dot(np.dot(X, M), Y.T)
|
2010-11-06 22:42:55 +08:00
|
|
|
|
2010-05-17 17:25:35 +08:00
|
|
|
|
2011-12-17 05:55:42 +08:00
|
|
|
h = .02 # step size in the mesh
|
2010-05-17 17:25:35 +08:00
|
|
|
|
2010-11-06 22:42:55 +08:00
|
|
|
# we create an instance of SVM and fit out data.
|
2012-05-05 20:56:19 +08:00
|
|
|
clf = svm.SVC(kernel=my_kernel)
|
2010-05-17 17:25:35 +08:00
|
|
|
clf.fit(X, Y)
|
|
|
|
|
|
2013-04-12 02:51:28 +08:00
|
|
|
# Plot the decision boundary. For that, we will assign a color to each
|
2016-04-25 11:59:40 +08:00
|
|
|
# point in the mesh [x_min, x_max]x[y_min, y_max].
|
2011-12-17 05:55:42 +08:00
|
|
|
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
|
|
|
|
|
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
|
2010-05-17 17:25:35 +08:00
|
|
|
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
|
|
|
|
|
Z = clf.predict(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, cmap=plt.cm.Paired)
|
2010-05-17 17:25:35 +08:00
|
|
|
|
|
|
|
|
# Plot also the training points
|
2017-03-05 00:22:00 +08:00
|
|
|
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k')
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.title('3-Class classification using Support Vector Machine with custom'
|
2014-05-15 10:35:13 +08:00
|
|
|
' kernel')
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.axis('tight')
|
|
|
|
|
plt.show()
|