将sklearn流水线+嵌套交叉验证放在一起进行KNN回归

Aus*_*tin 3 python pipeline feature-selection scikit-learn hyperparameters

我试图弄清楚如何为此构建工作流sklearn.neighbors.KNeighborsRegressor,包括:

  • 归一化特征
  • 特征选择(20个数字特征的最佳子集,无特定总数)
  • 在1到20的范围内交叉验证超参数K
  • 交叉验证模型
  • 使用RMSE作为误差指标

scikit-learn中有很多不同的选项,我在决定我需要的类时有点不知所措。

此外sklearn.neighbors.KNeighborsRegressor,我认为我需要:

sklearn.pipeline.Pipeline  
sklearn.preprocessing.Normalizer
sklearn.model_selection.GridSearchCV
sklearn.model_selection.cross_val_score

sklearn.feature_selection.selectKBest
OR
sklearn.feature_selection.SelectFromModel
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我定义此管道/工作流程的样子吗?我认为应该是这样的:

import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Normalizer
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import cross_val_score, GridSearchCV

# build regression pipeline
pipeline = Pipeline([('normalize', Normalizer()),
                     ('kbest', SelectKBest(f_classif)),
                     ('regressor', KNeighborsRegressor())])

# try knn__n_neighbors from 1 to 20, and feature count from 1 to len(features)
parameters = {'kbest__k':  list(range(1, X.shape[1]+1)),
              'regressor__n_neighbors': list(range(1,21))}

# outer cross-validation on model, inner cross-validation on hyperparameters
scores = cross_val_score(GridSearchCV(pipeline, parameters, scoring="neg_mean_squared_error", cv=10), 
                         X, y, cv=10, scoring="neg_mean_squared_error", verbose=2)

rmses = np.abs(scores)**(1/2)
avg_rmse = np.mean(rmses)
print(avg_rmse)
Run Code Online (Sandbox Code Playgroud)

它似乎没有出错,但是我的一些担忧是:

  • 我是否正确执行了嵌套的交叉验证,以使我的RMSE不受偏见?
  • 如果我想最终的模型根据最佳RMSE进行选择,我应该用scoring="neg_mean_squared_error"两个cross_val_scoreGridSearchCV
  • SelectKBest, f_classif用于选择KNeighborsRegressor模型特征的最佳选择吗?
  • 我怎么看:
    • 哪个功能子集被选为最佳
    • 哪个K被选为最佳

任何帮助是极大的赞赏!

mak*_*kis 6

您的代码似乎还可以。

对于scoring="neg_mean_squared_error"两个cross_val_scoreGridSearchCV,我会做同样的,以确保一切正常,可测试这一点的唯一方法是删除这两个中的一个,看看结果的变化。

SelectKBest是一个很好的方法,但您也可以使用此处SelectFromModel找到的其他方法

最后,为了获得最佳的参数功能得分,我对您的代码进行了一些修改,如下所示:

import ...


pipeline = Pipeline([('normalize', Normalizer()),
                     ('kbest', SelectKBest(f_classif)),
                     ('regressor', KNeighborsRegressor())])

# try knn__n_neighbors from 1 to 20, and feature count from 1 to len(features)
parameters = {'kbest__k':  list(range(1, X.shape[1]+1)),
              'regressor__n_neighbors': list(range(1,21))}

# changes here

grid = GridSearchCV(pipeline, parameters, cv=10, scoring="neg_mean_squared_error")

grid.fit(X, y)

# get the best parameters and the best estimator
print("the best estimator is \n {} ".format(grid.best_estimator_))
print("the best parameters are \n {}".format(grid.best_params_))

# get the features scores rounded in 2 decimals
pip_steps = grid.best_estimator_.named_steps['kbest']

features_scores = ['%.2f' % elem for elem in pip_steps.scores_ ]
print("the features scores are \n {}".format(features_scores))

feature_scores_pvalues = ['%.3f' % elem for elem in pip_steps.pvalues_]
print("the feature_pvalues is \n {} ".format(feature_scores_pvalues))

# create a tuple of feature names, scores and pvalues, name it "features_selected_tuple"

featurelist = ['age', 'weight']

features_selected_tuple=[(featurelist[i], features_scores[i], 
feature_scores_pvalues[i]) for i in pip_steps.get_support(indices=True)]

# Sort the tuple by score, in reverse order

features_selected_tuple = sorted(features_selected_tuple, key=lambda 
feature: float(feature[1]) , reverse=True)

# Print
print 'Selected Features, Scores, P-Values'
print features_selected_tuple
Run Code Online (Sandbox Code Playgroud)

使用我的数据的结果:

the best estimator is
Pipeline(steps=[('normalize', Normalizer(copy=True, norm='l2')), ('kbest', SelectKBest(k=2, score_func=<function f_classif at 0x0000000004ABC898>)), ('regressor', KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski',
         metric_params=None, n_jobs=1, n_neighbors=18, p=2,
         weights='uniform'))])

the best parameters are
{'kbest__k': 2, 'regressor__n_neighbors': 18}

the features scores are
['8.98', '8.80']

the feature_pvalues is
['0.000', '0.000']

Selected Features, Scores, P-Values
[('correlation', '8.98', '0.000'), ('gene', '8.80', '0.000')]
Run Code Online (Sandbox Code Playgroud)