从GridSearchCV中提取最佳管道用于cross_val_predict

如何从一个已拟合的GridSearchCV中提取最佳管道,以便将其传递给cross_val_predict

直接传递已拟合的GridSearchCV对象会导致cross_val_predict再次运行整个网格搜索,我只想让最佳管道接受cross_val_predict的评估。

我的自包含代码如下:

from sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.svm import SVCfrom sklearn.multiclass import OneVsRestClassifierfrom sklearn.pipeline import Pipelinefrom sklearn.grid_search import GridSearchCVfrom sklearn.model_selection import cross_val_predictfrom sklearn.model_selection import StratifiedKFoldfrom sklearn import metrics# fetch data datanewsgroups = fetch_20newsgroups(remove=('headers', 'footers', 'quotes'), categories=['comp.graphics', 'rec.sport.baseball', 'sci.med'])X = newsgroups.datay = newsgroups.target# setup and run GridSearchCVwordvect = TfidfVectorizer(analyzer='word', lowercase=True)classifier = OneVsRestClassifier(SVC(kernel='linear', class_weight='balanced'))pipeline = Pipeline([('vect', wordvect), ('classifier', classifier)])scoring = 'f1_weighted'parameters = {            'vect__min_df': [1, 2],            'vect__max_df': [0.8, 0.9],            'classifier__estimator__C': [0.1, 1, 10]            }gs_clf = GridSearchCV(pipeline, parameters, n_jobs=8, scoring=scoring, verbose=1)gs_clf = gs_clf.fit(X, y)### outputs: Fitting 3 folds for each of 12 candidates, totalling 36 fits# manually extract the best models from the grid search to re-build the pipelinebest_clf = gs_clf.best_estimator_.named_steps['classifier']best_vectorizer = gs_clf.best_estimator_.named_steps['vect']best_pipeline = Pipeline([('best_vectorizer', best_vectorizer), ('classifier', best_clf)])# passing gs_clf here would run the grind search again inside cross_val_predicty_predicted = cross_val_predict(pipeline, X, y)print(metrics.classification_report(y, y_predicted, digits=3))

我目前的做法是从best_estimator_手动重建管道。但我的管道通常有更多步骤,比如SVD或PCA,有时我会添加或删除步骤并重新运行网格搜索来探索数据。然后在手动重建管道时,这一步总是需要重复,这很容易出错。

有没有办法直接从已拟合的GridSearchCV中提取最佳管道,以便将其传递给cross_val_predict


回答:

y_predicted = cross_val_predict(gs_clf.best_estimator_, X, y)

有效并返回:

Fitting 3 folds for each of 12 candidates, totalling 36 fits[Parallel(n_jobs=4)]: Done  36 out of  36 | elapsed:   43.6s finished             precision    recall  f1-score   support          0      0.920     0.911     0.916       584          1      0.894     0.943     0.918       597          2      0.929     0.887     0.908       594avg / total      0.914     0.914     0.914      1775

[编辑] 当我再次尝试代码时,简单地传递pipeline(原始管道),它返回了相同的结果(传递best_pipeline也是如此)。所以你可能可以直接使用管道本身,但我对此不是100%确定。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注