EX 4: SVM_with _custom _kernel.md
在範例七中介紹了SVM 不同內建 Kernel 的比較,此範例用來展示,如何自行設計 SVM 的 Kernel

(一)引入函式庫

引入函式如下:
    1.
    numpy : 產生陣列數值
    2.
    matplotlib.pyplot : 用來繪製影像
    3.
    sklearn.svm : SVM 支持向量機之演算法物件
    4.
    sklearn.datasets : 匯入內建資料庫
1
import numpy as np
2
import matplotlib.pyplot as plt
3
from sklearn import svm, datasets
Copied!
1
# import some data to play with
2
iris = datasets.load_iris()
3
X = iris.data[:, :2] # we only take the first two features. We could
4
# avoid this ugly slicing by using a two-dim dataset
5
Y = iris.target
Copied!
iris = datasets.load_iris() : 匯入內建資料庫鳶尾花的資料,將資料存入變數iris中

(二)SVM Model

1
def my_kernel(X, Y):
2
"""
3
We create a custom kernel:
4
5
(2 0)
6
k(X, Y) = X ( ) Y.T
7
(0 1)
8
"""
9
M = np.array([[2, 0], [0, 1.0]])
10
return np.dot(np.dot(X, M), Y.T)
Copied!
自行定義函式來設計出自己想要的 Kernel 型式
1
h = .02 # step size in the mesh
2
3
# we create an instance of SVM and fit out data.
4
clf = svm.SVC(kernel=my_kernel)
5
clf.fit(X, Y)
Copied!
svm.SVC 的 Kernel 設成自訂的 Kernel 型式
1
# Plot the decision boundary. For that, we will assign a color to each
2
# point in the mesh [x_min, x_max]x[y_min, y_max].
3
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
4
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
6
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Copied!
np.meshgrid : 生成網格採樣點
1
# Put the result into a color plot
2
Z = Z.reshape(xx.shape)
3
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
4
5
# Plot also the training points
6
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k')
7
plt.title('3-Class classification using Support Vector Machine with custom'
8
' kernel')
9
plt.axis('tight')
10
plt.show()
Copied!
最後利用以上指令將結果圖顯示出來,plt.pcolormesh會根據clf.predict的結果繪製分類圖。
plt.pcolormesh : 能夠利用色塊的方式直觀表現出分類邊界
以下為結果圖 :

(三)完整程式碼

Python source code: plot_custom_kernel.py
iPython source code: plot_custom_kernel.ipynb
1
"""
2
======================
3
SVM with custom kernel
4
======================
5
6
Simple usage of Support Vector Machines to classify a sample. It will
7
plot the decision surface and the support vectors.
8
9
"""
10
print(__doc__)
11
12
import numpy as np
13
import matplotlib.pyplot as plt
14
from sklearn import svm, datasets
15
16
# import some data to play with
17
iris = datasets.load_iris()
18
X = iris.data[:, :2] # we only take the first two features. We could
19
# avoid this ugly slicing by using a two-dim dataset
20
Y = iris.target
21
22
23
def my_kernel(X, Y):
24
"""
25
We create a custom kernel:
26
27
(2 0)
28
k(X, Y) = X ( ) Y.T
29
(0 1)
30
"""
31
M = np.array([[2, 0], [0, 1.0]])
32
return np.dot(np.dot(X, M), Y.T)
33
34
35
h = .02 # step size in the mesh
36
37
# we create an instance of SVM and fit out data.
38
clf = svm.SVC(kernel=my_kernel)
39
clf.fit(X, Y)
40
41
# Plot the decision boundary. For that, we will assign a color to each
42
# point in the mesh [x_min, x_max]x[y_min, y_max].
43
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
44
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
45
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
46
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
47
48
# Put the result into a color plot
49
Z = Z.reshape(xx.shape)
50
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
51
52
# Plot also the training points
53
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k')
54
plt.title('3-Class classification using Support Vector Machine with custom'
55
' kernel')
56
plt.axis('tight')
57
plt.show()
Copied!