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

标签 python machine-learning scikit-learn grid-search

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

  1. 第一步,估计器用于 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...

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

谢谢!

最佳答案

我找到了一个解决方案,其中我重写了 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

关于python - 如何将两个估计器对象传递给sklearn的GridSearchCV,以便它们在每个步骤中具有相同的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48831851/

相关文章:

python -\0 在 re.sub() 中不起作用。绕开?

python - 为什么多处理模块生成的进程不复制内存?

python - pytorch 中包含列表的张量是否有一个tensor.item() 等效项?

r - 如何在 R 中绘制基于规则的决策树

python - 防止随机森林回归器中数据泄漏的建议

python:字典获取方法默认值的问题

python - 使用Flickr API下载图片——Python

python - 如何在 Pandas 中获取盘中价格 - 成交量图?

python - scikit-learn load_mlcomp 异常 "Could not find dataset with metadata line: name: 20news-18828"

python - 如何在多变量/3D 中实现核密度估计