sud*_*fee 24 python pipeline scikit-learn grid-search
我正在使用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_))
Run Code Online (Sandbox Code Playgroud)
返回的错误归结为:
ValueError: Invalid parameter logisticregression_C for estimator Pipeline
Run Code Online (Sandbox Code Playgroud)
这是与从v.0.16使用Make_pipeline相关的错误吗?导致此错误的原因是什么?
Viv*_*mar 29
在估算器名称和管道中
的参数之间应该有两个下划线logisticregression__C.做同样的事情tfidfvectorizer
请参阅http://scikit-learn.org/stable/auto_examples/plot_compare_reduction.html#sphx-glr-auto-examples-plot-compare-reduction-py上的示例
请注意,如果您使用带有投票分类器和列选择器的管道,则将需要多层名称:
pipe1 = make_pipeline(ColumnSelector(cols=(0, 1)),
LogisticRegression())
pipe2 = make_pipeline(ColumnSelector(cols=(1, 2, 3)),
SVC())
votingClassifier = VotingClassifier(estimators=[
('p1', pipe1), ('p2', pipe2)])
Run Code Online (Sandbox Code Playgroud)
您将需要一个如下所示的参数网格:
param_grid = {
'p2__svc__kernel': ['rbf', 'poly'],
'p2__svc__gamma': ['scale', 'auto'],
}
Run Code Online (Sandbox Code Playgroud)
p2是管道的名称,svc也是您在该管道中创建的分类器的默认名称。第三个元素是要修改的参数。
对于Pipeline在 a 中使用的更一般的答案,GridSearchCV模型的参数网格应该以您在定义管道时提供的任何名称开头。例如:
# 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)
Run Code Online (Sandbox Code Playgroud)
在管道中,我们使用model了估算器步骤的名称。因此,在网格搜索中,套索回归的任何超参数都应该带有前缀model__。网格中的参数取决于您在管道中指定的名称。在GridSearchCV没有管道的普通老式中,网格将如下所示:
param_grid = {'alpha': np.arange(0, 1, 0.05)}
search = GridSearchCV(Lasso(), param_grid)
Run Code Online (Sandbox Code Playgroud)
您可以从这篇文章中找到有关 GridSearch 的更多信息。
| 归档时间: |
|
| 查看次数: |
10840 次 |
| 最近记录: |