【问题标题】:Invalid parameter for sklearn estimator pipelinesklearn 估计器管道的参数无效
【发布时间】:2017-06-13 10:33:01
【问题描述】:

我正在使用 Python 2.7 和 sklearn 0.16 实现 O'Reilly 书籍“Python 机器学习简介”中的一个示例。

我正在使用的代码:

pipe = make_pipeline(TfidfVectorizer(), LogisticRegression())
param_grid = {"logisticregression_C": [0.001, 0.01, 0.1, 1, 10, 100], "tfidfvectorizer_ngram_range": [(1,1), (1,2), (1,3)]}
grid = GridSearchCV(pipe, param_grid, cv=5)
grid.fit(X_train, y_train)
print("Best cross-validation score: {:.2f}".format(grid.best_score_))

返回的错误归结为:

ValueError: Invalid parameter logisticregression_C for estimator Pipeline

这是与使用 v.0.16 中的 Make_pipeline 相关的错误吗?是什么导致了这个错误?

【问题讨论】:

    标签: python scikit-learn grid-search scikit-learn-pipeline


    【解决方案1】:

    估计器名称和Pipeline 中的参数之间应该有两个下划线 logisticregression__C。对tfidfvectorizer做同样的事情

    查看http://scikit-learn.org/stable/auto_examples/plot_compare_reduction.html#sphx-glr-auto-examples-plot-compare-reduction-py的示例

    【讨论】:

    • 我希望我能多次投票。 __ 成功了。谢谢
    • 在此链接中找不到文件:http://scikit-learn.org/stable/auto_examples/plot_compare_reduction.html#sphx-glr-auto-examples-plot-compare-reduction-py
    【解决方案2】:

    请注意,如果您使用带有投票分类器和列选择器的管道,您将需要多层名称:

    pipe1 = make_pipeline(ColumnSelector(cols=(0, 1)),
                          LogisticRegression())
    pipe2 = make_pipeline(ColumnSelector(cols=(1, 2, 3)),
                          SVC())
    votingClassifier = VotingClassifier(estimators=[
            ('p1', pipe1), ('p2', pipe2)])
    

    您将需要一个如下所示的参数网格:

    param_grid = { 
            'p2__svc__kernel': ['rbf', 'poly'],
            'p2__svc__gamma': ['scale', 'auto'],
        }
    

    p2 是管道的名称,svc 是您在该管道中创建的分类器的默认名称。第三个元素是你要修改的参数。

    【讨论】:

      【解决方案3】:

      对于在GridSearchCV 中使用Pipeline 的更一般的答案,模型的参数网格应以您在定义管道时提供的任何名称开头。例如:

      # Pay attention to the name of the second step, i. e. 'model'
      pipeline = Pipeline(steps=[
           ('preprocess', preprocess),
           ('model', Lasso())
      ])
      
      # Define the parameter grid to be used in GridSearch
      param_grid = {'model__alpha': np.arange(0, 1, 0.05)}
      
      search = GridSearchCV(pipeline, param_grid)
      search.fit(X_train, y_train)
      

      在管道中,我们将名称 model 用于估计步骤。因此,在网格搜索中,任何 Lasso 回归的超参数都应该使用前缀 model__。网格中的参数取决于您在管道中给出的名称。在没有管道的普通GridSearchCV 中,网格将如下所示:

      param_grid = {'alpha': np.arange(0, 1, 0.05)}
      search = GridSearchCV(Lasso(), param_grid)
      

      您可以通过post 了解有关 GridSearch 的更多信息。

      【讨论】:

        【解决方案4】:

        您始终可以使用model.get_params().keys() [如果您仅使用模型] 或pipeline.get_params().keys() [如果您使用管道] 来获取可以调整的参数的键。

        【讨论】:

          猜你喜欢
          • 2018-06-24
          • 2020-09-11
          • 2020-05-31
          • 2017-12-28
          • 2020-09-10
          • 2021-01-16
          • 2020-08-11
          • 2021-06-01
          • 2021-08-17
          相关资源
          最近更新 更多