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
|
|
|
|
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
|
2022-03-29 22:36:31 +08:00
|
|
|
from sklearn.inspection import DecisionBoundaryDisplay
|
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
|
2021-06-18 21:46:40 +08:00
|
|
|
# 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 = 0.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)
|
|
|
|
|
|
2022-03-29 22:36:31 +08:00
|
|
|
ax = plt.gca()
|
|
|
|
|
DecisionBoundaryDisplay.from_estimator(
|
|
|
|
|
clf,
|
|
|
|
|
X,
|
|
|
|
|
cmap=plt.cm.Paired,
|
|
|
|
|
ax=ax,
|
|
|
|
|
response_method="predict",
|
|
|
|
|
plot_method="pcolormesh",
|
|
|
|
|
shading="auto",
|
|
|
|
|
)
|
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 kernel")
|
|
|
|
|
plt.axis("tight")
|
|
|
|
|
plt.show()
|