帶有自定義核函數的支持向量機?

在這個案例中,我們簡單使用支持向量機對樣本進行分類,并繪制決策面和支持向量。

輸入:

print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets

# 導入數據以便處理
iris = datasets.load_iris()
X = iris.data[:, :2
# 我們僅僅使用前兩個特征,我們可以通過使用二維數據集來避免復雜的切片
Y = iris.target


def my_kernel(X, Y):
    """
    我們創建一個自定義的核函數:

                 (2  0)
    k(X, Y) = X  (    ) Y.T
                 (0  1)
    """

    M = np.array([[20], [01.0]])
    return np.dot(np.dot(X, M), Y.T)


h = .02  # 設置網格中的步長

# 我們創建一個SVM實例并擬合數據。
clf = svm.SVC(kernel=my_kernel)
clf.fit(X, Y)

# 繪制決策邊界。為此,我們將為網格[x_min,x_max] x [y_min,y_max]中的每個點分配顏色。
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
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()])

# 將結果放入顏色圖
Z = Z.reshape(xx.shape)
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

# 繪制訓練點
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k')
plt.title('3-Class classification using Support Vector Machine with custom'
          ' kernel')
plt.axis('tight')
plt.show()

腳本的總運行時間:0分鐘0.196秒