【问题标题】:How to pass two estimator objects to sklearn's GridSearchCV so that they have the same parameters in each step?如何将两个估计器对象传递给 sklearn 的 GridSearchCV,以便它们在每个步骤中具有相同的参数?
【发布时间】:2018-07-27 15:54:08
【问题描述】:

我正在尝试使用 SKlearn 的 GridSearchCV 为我的估算器调整超参数。

  1. 第一步,估计器用来for是SequentialFeatureSelection,这是一个自定义库,执行wrapper based feature selection。这意味着迭代地添加新特征并确定估计器表现最佳的特征。因此,SequentialFeatureSelection 方法需要我的估算器。该库经过编程,可以完美地与 SKlearn 一起使用,因此我将其集成到 GridSearchCV 管道的第一步中,以将特征转换为选定的特征。

  2. 在第二步中,我想使用完全相同的分类器和完全相同的参数来拟合并预测结果。但是对于参数网格,我只能将参数设置为我传递给 SequentialFeatureSelector 的分类器或“clf”中的参数,我不能保证它们总是相同的。

  3. 最后,我想在之前的测试集上预测选定的特征和选定的参数。

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


    【解决方案1】:

    我找到了一个解决方案,在其中我覆盖了 SequentialFeatureSelector (SFS) 类的一些方法,以便也使用它的估计器来进行转换后的预测。这是通过引入自定义 SFS 类“CSequentialFeatureSelector”来完成的,该类会覆盖 SFS 中的以下方法:

    1. 在fit(self, X, y)方法中,不仅进行了正常的拟合,而且self.estimator也是对变换后的数据进行拟合,这样就可以实现predict和predict_proba SFS 类的方法。

    2. 我为 SFS 类实现了 predict 和 predict_probba 方法,它们调用拟合 self.estimator 的 predict 和 predict_probba 方法。

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

    以下是部分代码:

    import sklearn.pipeline
    import sklearn.tree
    import sklearn.model_selection
    import mlxtend.feature_selection
    
    
    class 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 self
    
    
    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": [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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-08
      • 2019-12-05
      • 2019-08-17
      • 2020-12-27
      • 2017-12-17
      • 2019-04-26
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多