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.
|
|
|
|
|
|
|
|
|
|
"""
|
2010-11-02 18:38:06 +08:00
|
|
|
print __doc__
|
|
|
|
|
|
2010-05-17 17:25:35 +08:00
|
|
|
import numpy as np
|
|
|
|
|
import pylab as pl
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def my_kernel(x, y):
|
|
|
|
|
"""
|
|
|
|
|
We create a custom kernel:
|
|
|
|
|
|
|
|
|
|
(2 0)
|
|
|
|
|
k(x, y) = x ( ) y.T
|
|
|
|
|
(0 1)
|
|
|
|
|
"""
|
|
|
|
|
M = np.array([[2, 0], [0, 1.0]])
|
|
|
|
|
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-02-22 22:46:54 +08:00
|
|
|
clf = svm.SVC(kernel=my_kernel, C=100)
|
2010-05-17 17:25:35 +08:00
|
|
|
clf.fit(X, Y)
|
|
|
|
|
|
|
|
|
|
# Plot the decision boundary. For that, we will asign a color to each
|
|
|
|
|
# point in the mesh [x_min, m_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)
|
|
|
|
|
pl.set_cmap(pl.cm.Paired)
|
|
|
|
|
pl.pcolormesh(xx, yy, Z)
|
|
|
|
|
|
|
|
|
|
# Plot also the training points
|
2011-12-17 05:55:42 +08:00
|
|
|
pl.scatter(X[:, 0], X[:, 1], c=Y)
|
|
|
|
|
pl.title('3-Class classification using Support Vector Machine with custom'
|
2011-12-17 15:58:24 +08:00
|
|
|
' kernel')
|
2010-05-17 17:25:35 +08:00
|
|
|
pl.axis('tight')
|
|
|
|
|
pl.show()
|