支持向量機:核函數?

下面顯示了三種不同類型的SVM核函數。當數據點不可線性分離時,多項式和RBF特別有用。 輸入:

print(__doc__)


# 代碼來源: Ga?l Varoquaux
# 執照: BSD 3 clause

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


# 我們的數據集與標簽
X = np.c_[(.4-.7),
          (-1.5-1),
          (-1.4-.9),
          (-1.3-1.2),
          (-1.1-.2),
          (-1.2-.4),
          (-.51.2),
          (-1.52.1),
          (11),
          # --
          (1.3.8),
          (1.2.5),
          (.2-2),
          (.5-2.4),
          (.2-2.3),
          (0-2.7),
          (1.32.1)].T
Y = [0] * 8 + [1] * 8

# 圖像的編號
fignum = 1

# 擬合模型
for kernel in ('linear''poly''rbf'):
    clf = svm.SVC(kernel=kernel, gamma=2)
    clf.fit(X, Y)

    # 繪制直線,點和最接近平面的向量
    plt.figure(fignum, figsize=(43))
    plt.clf()

    plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
                facecolors='none', zorder=10, edgecolors='k')
    plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired,
                edgecolors='k')

    plt.axis('tight')
    x_min = -3
    x_max = 3
    y_min = -3
    y_max = 3

    XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
    Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])

    # 將結果放入顏色圖
    Z = Z.reshape(XX.shape)
    plt.figure(fignum, figsize=(43))
    plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired)
    plt.contour(XX, YY, Z, colors=['k''k''k'], linestyles=['--''-''--'],
                levels=[-.50.5])

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)

    plt.xticks(())
    plt.yticks(())
    fignum = fignum + 1
plt.show()

腳本的總運行時間:(0分鐘0.229秒)