scikit-learn FeatureUnion gridsearch over features of features

时间:2016-05-04 21:30:41

标签: python scikit-learn

如何在scikit中使用FeatureUnion学习,以便Gridsearch可以选择处理其部分?

下面的代码可以运行并设置一个FeatureUnion,其中包含用于单词的TfidfVectorizer和用于chars的TfidfVectorizer。

在进行Gridsearch时,除了测试已定义的参数空间之外,我还想仅使用其ngram_range参数测试'vect__wordvect'(没有用于字符的TfidfVectorizer),并且还仅使用'vect__lettervect'来测试小写参数True和False,另一个TfidfVectorizer被禁用。

编辑:基于maxymoo建议的完整代码示例。

如何做到这一点?

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.grid_search import GridSearchCV
from sklearn.datasets import fetch_20newsgroups

# setup the featureunion
wordvect = TfidfVectorizer(analyzer='word')
lettervect = CountVectorizer(analyzer='char')
featureunionvect = FeatureUnion([("lettervect", lettervect), ("wordvect", wordvect)])

# setup the pipeline
classifier = LogisticRegression(class_weight='balanced')
pipeline = Pipeline([('vect', featureunionvect), ('classifier', classifier)])

# gridsearch parameters 
parameters = {
            'vect__wordvect__ngram_range': [(1, 1), (1, 2)],  # commenting out these two lines
            'vect__lettervect__lowercase': [True, False],     # runs, but there is no parameterization anymore
            'vect__transformer_list': [[('wordvect', wordvect)],
                                        [('lettervect', lettervect)],
                                        [('wordvect', wordvect), ('lettervect', lettervect)]]}
gs_clf = GridSearchCV(pipeline, parameters)

# data
newsgroups_train = fetch_20newsgroups(subset='train', categories=['alt.atheism', 'sci.space'])

# gridsearch CV
gs_clf = GridSearchCV(pipeline, parameters)
gs_clf = gs_clf.fit(newsgroups_train.data, newsgroups_train.target)
for score in gs_clf.grid_scores_:
    print "gridsearch scores: ", score

1 个答案:

答案 0 :(得分:3)

FeatureUnion有一个名为transformer_list的参数,您可以使用该参数进行网格搜索;因此,在您的情况下,您的网格搜索参数将变为

parameters = {'vect__wordvect__ngram_range': [(1, 1), (1, 2)],
              'vect__lettervect__lowercase': [True, False],
              'vect__transformer_weights': [{"lettervect":1,"wordvect":0}, 
                                            {"lettervect":0,"wordvect":1}, 
                                            {"lettervect":1,"wordvect":1}]}