是否可以在scikit-learn中使用网格搜索调整参数来定制内核?

时间:2014-07-06 11:04:18

标签: python scikit-learn

我有一个自定义内核函数,我正在使用带有SVC的GridSearchCV函数(kernel = my_kernel)。

my_kernel函数使用参数k进行调整,因此我想知道是否可以配置param_grid选项来调整我的自定义内核函数的参数。

例如,可以如下调整RBF内核的gamma参数。我可以为自定义内核提供param_grid = dict(k = k_range)类型的选项吗?

gamma_range = 10. ** np.arange(-5, 4)
param_grid = dict(gamma=gamma_range)
grid = GridSearchCV(SVC(), param_grid=param_grid, cv=StratifiedKFold(y=Y, k=5))

3 个答案:

答案 0 :(得分:10)

执行此操作的一种方法是使用PipelineSVC(kernel='precomputed')并将自定义内核函数包装为sklearn估算工具(BaseEstimatorTransformerMixin的子类))。

例如,sklearn包含custom kernel function chi2_kernel(X, Y=None, gamma=1.0),它计算特征向量XY的内核矩阵。 此函数采用参数gamma,最好使用交叉验证进行设置。 我们可以对这个函数的参数进行网格搜索,如下所示:

from __future__ import print_function
from __future__ import division

import sys

import numpy as np

import sklearn
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.cross_validation import train_test_split
from sklearn.datasets import load_digits
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import accuracy_score
from sklearn.metrics.pairwise import chi2_kernel
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC

# Wrapper class for the custom kernel chi2_kernel
class Chi2Kernel(BaseEstimator,TransformerMixin):
    def __init__(self, gamma=1.0):
        super(Chi2Kernel,self).__init__()
        self.gamma = gamma

    def transform(self, X):
        return chi2_kernel(X, self.X_train_, gamma=self.gamma)

    def fit(self, X, y=None, **fit_params):
        self.X_train_ = X
        return self

def main():

    print('python: {}'.format(sys.version))
    print('numpy: {}'.format(np.__version__))
    print('sklearn: {}'.format(sklearn.__version__))
    np.random.seed(0)

    # Get some data to evaluate
    dataset = load_digits()
    X = dataset.data
    y = dataset.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)

    # Create a pipeline where our custom predefined kernel Chi2Kernel
    # is run before SVC.
    pipe = Pipeline([
        ('chi2', Chi2Kernel()),
        ('svm', SVC()),
    ])

    # Set the parameter 'gamma' of our custom kernel by
    # using the 'estimator__param' syntax.
    cv_params = dict([
        ('chi2__gamma', 10.0**np.arange(-9,4)),
        ('svm__kernel', ['precomputed']),
        ('svm__C', 10.0**np.arange(-2,9)),
    ])

    # Do grid search to get the best parameter value of 'gamma'.
    model = GridSearchCV(pipe, cv_params, cv=5, verbose=1, n_jobs=-1)
    model.fit(X_train, y_train)
    y_pred = model.predict(X_test)
    acc_test = accuracy_score(y_test, y_pred)

    print("Test accuracy: {}".format(acc_test))
    print("Best params:")
    print(model.best_params_)

if __name__ == '__main__':
    main()

输出:

    python: 2.7.3 (default, Dec 18 2014, 19:10:20)
    [GCC 4.6.3]
    numpy: 1.8.0
    sklearn: 0.16.1
    Fitting 5 folds for each of 143 candidates, totalling 715 fits
    [Parallel(n_jobs=-1)]: Done   1 jobs       | elapsed:    0.4s
    [Parallel(n_jobs=-1)]: Done  50 jobs       | elapsed:    2.7s
    [Parallel(n_jobs=-1)]: Done 200 jobs       | elapsed:    9.8s
    [Parallel(n_jobs=-1)]: Done 450 jobs       | elapsed:   21.6s
    [Parallel(n_jobs=-1)]: Done 701 out of 715 | elapsed:   34.8s remaining:    0.7s
    [Parallel(n_jobs=-1)]: Done 715 out of 715 | elapsed:   35.4s finished
    Test accuracy: 0.989898989899
    Best params:
    {'chi2__gamma': 0.01, 'svm__C': 10.0, 'svm__kernel': 'precomputed'}

在您的情况下,只需将chi2_kernel替换为计算内核矩阵的函数。

答案 1 :(得分:1)

用scikit-learn 0.19,你可以做到

from sklearn.kernel_ridge import KernelRidge
from sklearn.metrics.pairwise import chi2_kernel

reg_kridge=KernelRidge(kernel='chi2')
params_grid={"gamma":np.logspace(0,-4,5)}
reg=GridSearchCV(reg_kridge,params_grid, n_jobs=-1,cv=10,scoring='neg_mean_squared_error')
reg.fit(train, target)

答案 2 :(得分:0)

正如linked question中所述......如何使用auto-sklearn自动参数调整?它是sklearn的直接替代品,并且通常比手动调整的参数更好。