带有rbf内核的SVC与由rbf内核计算的X拟合的线性内核之间存在差异的原因是什么

时间:2019-03-27 07:39:25

标签: python scikit-learn kernel svc

我对SVC和内核方法(例如rbf)感到困惑。我的理解是,将带有rbf内核的SVC应用于fit(x,y),它计算形状为[n_samples, n_samples]的(x,xT)的rbf内核矩阵K,然后将该内核矩阵K转换为y铰链丢失。

根据这种直觉,我使用sklearn.svm.svcsklearn.metrics.pairwise.rbf_kernel比较以下结果:

 svc(kernel='rbf').fit(x,y)

 # and

 svc(kernel='precomputed').fit(rbf_kernel(x,x),y)

 # and

 svc(kernel='linear').fit(rbf_kernel(x,x),y)

我认为分类结果应该相同。这三个结果之间有些区别。

更具体地说,如果您按以下方式运行代码,则svc(kernel ='precomputed')。fit(rbf_kernel(x,x),y))与svc(kernel ='rbf')。fit(x ,y),但是svc(kernel ='linear')。fit(rbf_kernel(x,x),y)的效果不如其他两种方法。

有人可以帮我找出原因吗?谢谢。

from sklearn.datasets import make_moons, make_circles, make_classification
import numpy as np
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from matplotlib.colors import ListedColormap
import numpy as np
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt

h = .02  # step size in the mesh

names = [
    "RBF SVM",
    # "RP Ridge",
    "RBF-Precomp SVM",
    "RBF-Linear SVM",
]


classifiers = [
    SVC(gamma=1, C=1),
    SVC(kernel='precomputed',C=1,gamma=1),
    SVC(kernel="linear", C=1),
]

datasets = [
    make_moons(n_samples=200,noise=0, random_state=0),
    make_moons(n_samples=200,noise=0.2, random_state=0),
    make_circles(n_samples=200,noise=0, factor=0.5, random_state=0),
    make_circles(n_samples=200,noise=0.2, factor=0.5, random_state=0),]

figure = plt.figure(figsize=(int((len(classifiers)+1)*3), int(len(datasets)*3)))
i=1
# iterate over datasets
for ds_cnt, ds in enumerate(datasets):
    # preprocess dataset, split into training and test part
    X, y = ds
    X = StandardScaler().fit_transform(X)
    X_train, X_test, y_train, y_test = \
        train_test_split(X, y, test_size=.2, random_state=42)
    K_train = rbf_kernel(X_train,X_train,gamma=1)
    K_test = rbf_kernel(X_test,X_train,gamma=1)
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))

    # just plot the dataset first
    cm = plt.cm.RdBu
    cm_bright = ListedColormap(['#FF0000', '#0000FF'])
    ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
    if ds_cnt == 0:
        ax.set_title("Input data")
    # Plot the training points
    ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright,
               edgecolors='k')
    # Plot the testing points
    ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6,
               edgecolors='k', marker='*')
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xticks(())
    ax.set_yticks(())
    i += 1

    # iterate over classifiers
    for name, clf in zip(names, classifiers):

        ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
        if "Pre" in name:
            clf.fit(K_train,y_train)
            score = clf.score(K_test, y_test)
        elif "Linear" in name:
            clf.fit(K_train,y_train)
            score = clf.score(K_test, y_test)
        else:
            clf.fit(X_train, y_train)
            score = clf.score(X_test, y_test)

        # Plot the decision boundary. For that, we will assign a color to each
        # point in the mesh [x_min, x_max]x[y_min, y_max].
        # create test data from mesh grid
        mesh_data = np.c_[xx.ravel(), yy.ravel()]
        K_mesh = rbf_kernel(mesh_data, X_train,gamma=1)
        if "Pre" in name or "Linear" in name:
            Z = clf.decision_function(K_mesh)
        else:
            Z = clf.decision_function(mesh_data)

        # Put the result into a color plot
        Z = Z.reshape(xx.shape)
        # draw the every mesh grid, distinct them with colors in plt.cm.RdBu
        ax.contourf(xx, yy, Z, 66, cmap=cm, alpha=0.6)

        # Plot the training points
        ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright,
                   edgecolors='k')
        # Plot the testing points
        ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright,
                   edgecolors='k', alpha=0.6, marker='*')

        ax.set_xlim(xx.min(), xx.max())
        ax.set_ylim(yy.min(), yy.max())
        ax.set_xticks(())
        ax.set_yticks(())
        if ds_cnt == 0:
            ax.set_title(name)
        ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'),
                size=15, horizontalalignment='right')
        i += 1

plt.tight_layout()
plt.savefig('bench_test.png')

0 个答案:

没有答案