GridSearchCV Pipeline 中的替代不同模型

2024-03-13

我想在 sklearn 中构建一个 Pipeline 并使用 GridSearchCV 测试不同的模型。

举个例子(请不要关注具体选择的型号):

reg = LogisticRegression()

proj1 = PCA(n_components=2)
proj2 = MDS()
proj3 = TSNE()

pipe = [('proj', proj1), ('reg' , reg)]

pipe = Pipeline(pipe)

param_grid = {
    'reg__c': [0.01, 0.1, 1],
}

clf = GridSearchCV(pipe, param_grid = param_grid)

在这里,如果我想尝试不同的降维模型,我需要编写不同的管道并手动比较它们。有简单的方法吗?

我想出的一种解决方案是定义我自己的从基本估计器派生的类:

class Projection(BaseEstimator):
    def __init__(self, est_name):
        if est_name == "MDS":
            self.model = MDS()
        ...
    ...
    def fit_transform(self, X):
        return self.model.fit_transform(X)

我认为它会起作用,我只需创建一个 Projection 对象并将其传递给 Pipeline,使用估计器的名称作为它的参数。

但对我来说,这种方式有点混乱并且不可扩展:它让我每次想要比较不同的模型时都定义新的类。为了继续这个解决方案,我们可以实现一个类来完成相同的工作,但是使用任意一组模型。对我来说这似乎过于复杂。

比较不同模型的最自然和Python式的方法是什么?


假设您想要使用 PCA 和 TruncatedSVD 作为维度缩减步骤。

pca = decomposition.PCA()
svd = decomposition.TruncatedSVD()
svm = SVC()
n_components = [20, 40, 64]

你可以这样做:

pipe = Pipeline(steps=[('reduction', pca), ('svm', svm)])

# Change params_grid -> Instead of dict, make it a list of dict
# In the first element, pass parameters related to pca, and in second related to svd

params_grid = [{
'svm__C': [1, 10, 100, 1000],
'svm__kernel': ['linear', 'rbf'],
'svm__gamma': [0.001, 0.0001],
'reduction':pca,
'reduction__n_components': n_components,
},
{
'svm__C': [1, 10, 100, 1000],
'svm__kernel': ['linear', 'rbf'],
'svm__gamma': [0.001, 0.0001],
'reduction':svd,
'reduction__n_components': n_components,
'reduction__algorithm':['randomized']
}]

现在只需将管道对象传递给 gridsearchCV

grd = GridSearchCV(pipe, param_grid = params_grid)

Calling grd.fit()将使用以下所有值在 params_grid 列表的两个元素上搜索参数one一次。

更详细的请看我的另一个回答:使用网格搜索获得最佳模型的“并行”管道 https://stackoverflow.com/questions/42266737/parallel-pipeline-to-get-best-model-using-gridsearch/42271829#42271829

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

GridSearchCV Pipeline 中的替代不同模型 的相关文章

随机推荐