代码之家  ›  专栏  ›  技术社区  ›  tkja

从GridSearchCV中提取最佳管道以进行cross\u val\u预测

  •  3
  • tkja  · 技术社区  · 7 年前

    如何从拟合中提取最佳管道 GridSearchCV cross_val_predict ?

    直接通过配合 对象原因 cross\u val\u预测 cross\u val\u预测 评价

    from sklearn.datasets import fetch_20newsgroups
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.svm import SVC
    from sklearn.multiclass import OneVsRestClassifier
    from sklearn.pipeline import Pipeline
    from sklearn.grid_search import GridSearchCV
    from sklearn.model_selection import cross_val_predict
    from sklearn.model_selection import StratifiedKFold
    from sklearn import metrics
    
    # fetch data data
    newsgroups = fetch_20newsgroups(remove=('headers', 'footers', 'quotes'), categories=['comp.graphics', 'rec.sport.baseball', 'sci.med'])
    X = newsgroups.data
    y = newsgroups.target
    
    # setup and run GridSearchCV
    wordvect = 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 pipeline
    best_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_predict
    y_predicted = cross_val_predict(pipeline, X, y)
    print(metrics.classification_report(y, y_predicted, digits=3))
    

    我目前正在做的是从 best_estimator_ 但是我的管道通常有更多的步骤,如奇异值分解或主成分分析,有时我会添加或删除步骤,并重新运行网格搜索以探索数据。然后,当手动重新构建管道时,必须在下面重复此步骤,这很容易出错。

    GridSearchCV cross\u val\u预测

    2 回复  |  直到 7 年前
        1
  •  5
  •   Kevin    7 年前
    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       594
    
    avg / total      0.914     0.914     0.914      1775
    

    [编辑]当我再次尝试代码时 pipeline best_pipeline ). 所以你可以只处理管道本身,但我不是百分之百同意。

        2
  •  1
  •   Richard    7 年前

    根据需要命名gridsearch对象,然后使用fit方法获得结果。您不需要再次交叉验证,因为GridSearchCV基本上是使用不同参数的交叉验证(仅供参考,您可以在GridSearchCV中命名自己的cv对象,请查看sklearn文档中的GridSearchCV)。

    any_name = sklearn.grid_search.GridSearchCV(pipeline, param_grid=parameters)
    any_name.fit(X_train, y_train)
    

    下面是我找到的一个好指南的链接: https://www.civisanalytics.com/blog/workflows-in-python-using-pipeline-and-gridsearchcv-for-more-compact-and-comprehensive-code/