【发布时间】:2018-07-27 15:54:08
【问题描述】:
我正在尝试使用 SKlearn 的 GridSearchCV 为我的估算器调整超参数。
第一步,估计器用来for是SequentialFeatureSelection,这是一个自定义库,执行wrapper based feature selection。这意味着迭代地添加新特征并确定估计器表现最佳的特征。因此,SequentialFeatureSelection 方法需要我的估算器。该库经过编程,可以完美地与 SKlearn 一起使用,因此我将其集成到 GridSearchCV 管道的第一步中,以将特征转换为选定的特征。
在第二步中,我想使用完全相同的分类器和完全相同的参数来拟合并预测结果。但是对于参数网格,我只能将参数设置为我传递给 SequentialFeatureSelector 的分类器或“clf”中的参数,我不能保证它们总是相同的。
最后,我想在之前的测试集上预测选定的特征和选定的参数。
On the bottom of the page of the SFS library,他们展示了如何将 SFS 与 GridSearchCV 结合使用,但是用于选择特征的 KNN 算法和用于预测的算法也使用不同的参数。当我在 traininf SFS 和 GridSearchCV 之后检查自己时,参数永远不会相同,即使我按照建议使用 clf.clone()。这是我的代码:
import sklearn.pipeline
import sklearn.tree
import sklearn.model_selection
import mlxtend.feature_selection
def sfs(x, y):
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2, random_state=0)
clf = sklearn.tree.DecisionTreeClassifier()
param_grid = {
"sfs__estimator__max_depth": [5]
}
sfs = mlxtend.feature_selection.SequentialFeatureSelector(clone_estimator=True, # Clone like in Tutorial
estimator=clf,
k_features=10,
forward=True,
floating=False,
scoring='accuracy',
cv=3,
n_jobs=1)
pipe = sklearn.pipeline.Pipeline([('sfs', sfs), ("clf", clf)])
gs = sklearn.model_selection.GridSearchCV(estimator=pipe,
param_grid=param_grid,
scoring='accuracy',
n_jobs=1,
cv=3,
refit=True)
gs = gs.fit(x_train, y_train)
# Both estimators should have depth 5!
print("SFS Final Estimator Depth: " + str(gs.best_estimator_.named_steps.sfs.estimator.max_depth))
print("CLF Final Estimator Depth: " + str(gs.best_estimator_._final_estimator.max_depth))
# Evaluate...
y_test_pred = gs.predict(x_test)
# Accuracy etc...
问题是,我如何确保它们始终在同一管道中设置相同的参数?
谢谢!
【问题讨论】:
标签: python machine-learning scikit-learn grid-search