2016-11-01 55 views
2

我试图用GridSearchCV和管道建立一个多输出模型。 Pipeline给我带来麻烦,因为标准分类器示例没有包装分类器的OneVsRestClassifier()。我使用scikit学习0.18和3.5蟒Scikit学习多输出分类器使用:GridSearchCV,管道,OneVsRestClassifier,SGDClassifier

## Pipeline: Train and Predict 
## SGD: support vector machine (SVM) with gradient descent 
from sklearn.multiclass import OneVsRestClassifier 
from sklearn.pipeline import Pipeline 
from sklearn.linear_model import SGDClassifier 

clf = Pipeline([ 
       ('vect', CountVectorizer(ngram_range=(1,3), max_df=0.50)), 
       ('tfidf', TfidfTransformer()), 
       ('clf', SGDClassifier(loss='modified_huber', penalty='elasticnet', 
              alpha=1e-4, n_iter=5, random_state=42, 
              shuffle=True, n_jobs=-1)), 
       ]) 

ovr_clf = OneVsRestClassifier(clf) 

from sklearn.model_selection import GridSearchCV 
parameters = {'vect__ngram_range': [(1,1), (1,3)], 
       'tfidf__norm': ('l1', 'l2', None), 
       'estimator__loss': ('modified_huber', 'hinge',), 
      } 

gs_clf = GridSearchCV(estimator=pipeline, param_grid=parameters, 
         scoring='f1_weighted', n_jobs=-1, verbose=1) 
gs_clf = gs_clf.fit(X_train, y_train) 

但是,这产生了错误: ....

ValueError: Invalid parameter estimator for estimator Pipeline(steps=[('vect', CountVectorizer(analyzer='word', binary=False, decode_error='strict', dtype=, encoding='utf-8', input='content', lowercase=True, max_df=0.5, max_features=None, min_df=1, ngram_range=(1, 3), preprocessor=None, stop_words=None, strip...er_t=0.5, random_state=42, shuffle=True, verbose=0, warm_start=False), n_jobs=-1))]). Check the list of available parameters with estimator.get_params().keys() .

那么,什么是传递参数通过OneVsRestClassifier到CLF的正确方法使用param_grid和Pipeline?我是否需要将流水线中的分类器和tdidf分开?

回答

6

将OneVsRestClassifier()作为管道本身的一个步骤,将SGDClassifier作为OneVsRestClassifier的估计器。 你可以这样下去。

pipeline = Pipeline([ 
       ('vect', CountVectorizer(ngram_range=(1,3), max_df=0.50)), 
       ('tfidf', TfidfTransformer()), 
       ('clf', OneVsRestClassifier(SGDClassifier(loss='modified_huber', penalty='elasticnet', 
              alpha=1e-4, n_iter=5, random_state=42, 
              shuffle=True, n_jobs=-1))), 
       ]) 

其余的代码可以保持不变。 OneVsRestClassifier充当其他估计器的包装。

+2

工作! (1)我移动管道内的OneVsRestClassifier以包装SGDClassifier。 (2)我将前缀'clf__'添加到param_grid处理估计器参数中,即'clf__estimator__penalty'。 – MyopicVisage