【发布时间】:2017-12-22 08:52:13
【问题描述】:
我正在尝试弄清楚如何为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
有人能告诉我定义这个管道/工作流的样子吗?我认为应该是这样的:
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)
它似乎没有出错,但我的一些担忧是:
- 我是否正确执行了嵌套交叉验证以使我的 RMSE 不偏不倚?
- 如果我想根据最佳 RMSE 选择最终模型,我应该对
cross_val_score和GridSearchCV都使用scoring="neg_mean_squared_error"吗? -
SelectKBest, f_classif是为KNeighborsRegressor模型选择功能的最佳选项吗? - 如何查看:
- 哪个特征子集被选为最佳
- 哪个 K 被选为最佳
非常感谢任何帮助!
【问题讨论】:
-
你的代码看起来很不错。另外,这种方法对我来说是正确的。您是否收到任何错误或意外结果?
-
您好,感谢您的评论。我更新了我的帖子,提供了更多关于我的担忧的信息。
标签: python scikit-learn pipeline feature-selection hyperparameters