包括缩放和PCA作为GridSearchCV的参数

2024-09-26 17:45:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用GridSearchCV运行逻辑回归,但我想对比使用缩放和PCA时的性能,所以我不想在所有情况下都使用它

我基本上希望将PCA和缩放作为GridSearchCV的“参数”

我知道我可以制作这样的管道:

mnl = LogisticRegression(fit_intercept=True, multi_class="multinomial")

pipe = Pipeline([
    ('scale', StandardScaler()),
    ('mnl', mnl)])

params_mnl = {'mnl__solver': ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'],
              'mnl__max_iter':[500,1000,2000,3000]}

问题是,在这种情况下,缩放将应用于所有折叠,对吗? 有没有办法让它“包含”在gridsearch中

编辑:

我只是读了this answer,尽管它与我想要的相似,但实际上并不是这样,因为在这种情况下,定标器将应用于GridSearch中的最佳估计器

我想做的是,比如说

params_mnl = {'mnl__solver': ['newton-cg', 'lbfgs']}

我想用Scaler+newton-cg、No-Scaler+newton-cg、Scaler+lbfgs、No-Scaler+lbfgs运行回归


Tags: no参数管道情况newtonparams逻辑性能
2条回答

您可以将StandardScaler()的参数with_meanwith_std设置为False以表示无标准化。在GirdSearchCV中,参数para_grid可以设置为

param_grid = [{'scale__with_mean': [False],
               'scale__with_std': [False],
               'mnl__solver': ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'],
               'mnl__max_iter':[500,1000,2000,3000]
              },
              {'mnl__solver': ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'],
              'mnl__max_iter':[500,1000,2000,3000]}
]

然后列表中的第一个dict是“No Scaler+mnl”,第二个dict是“Scaler+mnl”

参考:

https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html

https://scikit-learn.org/stable/tutorial/statistical_inference/putting_together.html

编辑: 我认为如果你也考虑打开/关闭PCA,这会很复杂。。。也许您需要定义一个定制的PCA,它派生原始PCA。然后定义额外的布尔参数,它决定是否应该执行PCA

class MYPCA(PCA):
    def __init__(self, PCA_turn_on, *args):
        super().__init__(*args)
        self.PCA_turn_on = PCA_turn_on
    
    def fit(X, y=None):
        if (PCA_turn_on == True):
            return super().fit(X, y=None)
        else:
            pass

    # same for other methods defined in PCA

the documentationPipeline

A step’s estimator may be replaced entirely by setting the parameter with its name to another estimator, or a transformer removed by setting it to ‘passthrough’ or None.

例如:

pipe = Pipeline([
    ('scale', StandardScaler()),
    ('mnl', mnl),
])

params = {
    'scale': ['passthrough', StandardScaler()],
    'mnl__solver': ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'],
    'mnl__max_iter': [500, 1000, 2000, 3000],
}

相关问题 更多 >

    热门问题