如何将两个估计器对象传递给sklearn的GridSearchCV,使它们在每个步骤中具有相同的参数?

我试图使用SKlearn的GridSearchCV来调整我的估计器的超参数。

  1. 在第一步中,使用的估计器是SequentialFeatureSelection,这是一个自定义库,用于执行基于包装器的特征选择。这意味着迭代地添加新特征,并识别出估计器表现最佳的特征。因此,SequentialFeatureSelection方法需要我的估计器。这个库编写得非常好,可以与SKlearn一起使用,因此我在GridSearchCV管道的第一步中将其集成,以转换为所选的特征。

  2. 在第二步中,我希望使用完全相同的分类器和完全相同的参数来拟合和预测结果。然而,使用参数网格,我只能将参数设置为传递给SequentialFeatureSelector的分类器,或者设置为’clf’中的参数,我无法保证它们总是相同的。

  3. 最后,使用选定的特征和选定的参数,我希望在之前保留的测试集上进行预测。

在SFS库的页面底部,他们展示了如何将SFS与GridSearchCV一起使用,但在那里用于选择特征和用于预测的KNN算法也使用了不同的参数。当我自己检查在训练SFS和GridSearchCV之后,参数永远不会相同,即使我使用了提议的clf.clone()。这是我的代码:

import sklearn.pipelineimport sklearn.treeimport sklearn.model_selectionimport mlxtend.feature_selectiondef 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...

问题是,如何确保它们在同一个管道中始终设置相同的参数?

谢谢!


回答:

我找到了一种解决方案,我重写了SequentialFeatureSelector (SFS) 类的一些方法,以便在转换后也使用其估计器进行预测。这是通过引入一个自定义SFS类’CSequentialFeatureSelector’来实现的,该类重写了SFS的以下方法:

  1. 在fit(self, X, y)方法中,不仅执行正常的拟合,还对转换后的数据进行self.estimator的拟合,以便为SFS类实现predict和predict_proba方法。

  2. 我为SFS类实现了predict和predict_proba方法,这些方法调用已拟合的self.estimator的predict和predict_proba方法。

因此,我只剩下一个估计器,用于SFS和预测。

这里是一些代码:

import sklearn.pipelineimport sklearn.treeimport sklearn.model_selectionimport mlxtend.feature_selectionclass CSequentialFeatureSelector(mlxtend.feature_selection.SequentialFeatureSelector):    def predict(self, X):        X = self.transform(X)        return self.estimator.predict(X)    def predict_proba(self, X):        X = self.transform(X)        return self.estimator.predict_proba(X)    def fit(self, X, y):        self.fit_helper(X, y) # fit helper is the 'old' fit method, which I copied and renamed to fit_helper        self.estimator.fit(self.transform(X), y)        return selfdef 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": [3, 4, 5]    }    sfs = mlxtend.feature_selection.SequentialFeatureSelector(clone_estimator=True,                                                              estimator=clf,                                                              k_features=10,                                                              forward=True,                                                              floating=False,                                                              scoring='accuracy',                                                              cv=3,                                                              n_jobs=1)    # Now only one object in the pipeline (in fact this is not even needed anymore)    pipe = sklearn.pipeline.Pipeline([('sfs', sfs)])    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)    print("SFS Final Estimator Depth: " + str(gs.best_estimator_.named_steps.sfs.estimator.max_depth))    y_test_pred = gs.predict(x_test)    # Evaluate performance of y_test_pred

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注