2015-07-20 308 views
2

我正在使用GridSearchCV和一个管道来分类索姆文本文档。代码片断插入下面获取对应的类predict_proba(GridSearchCV sklearn)

clf = Pipeline([('vect', TfidfVectorizer()), ('clf', SVC())]) 
parameters = {'vect__ngram_range' : [(1,2)], 'vect__min_df' : [2], 'vect__stop_words' : ['english'], 
        'vect__lowercase' : [True], 'vect__norm' : ['l2'], 'vect__analyzer' : ['word'], 'vect__binary' : [True], 
        'clf__kernel' : ['rbf'], 'clf__C' : [100], 'clf__gamma' : [0.01], 'clf__probability' : [True]} 
grid_search = GridSearchCV(clf, parameters, n_jobs = -2, refit = True, cv = 10) 
grid_search.fit(corpus, labels) 

我的问题是使用grid_serach.predict_proba(new_doc)时,然后要找出什么类的概率对应于具有grid_search.classes_,我收到以下错误

AttributeError: 'GridSearchCV' object has no attribute 'classes_'

我有什么错过了什么?我认为如果管道中的最后一个“步骤”是一个分类器,那么GridSearchCV的返回也是一个分类器。因此可以使用该分类器的属性,例如classes_

谢谢先进!

回答

4

正如上面评论中提到的那样,grid_search.best_estimator_.classes_返回了一条错误消息,因为它返回的管道没有属性.classes_。但是,通过首先调用管道的步骤分类器,我可以使用classes属性。这里是解决方案

grid_search.best_estimator_.named_steps['clf'].classes_ 
+0

完美!非常感谢 – AbtPst

4

尝试grid_search.best_estimator_.classes_

GridSearchCV的返回是一个GridSearchCV实例,它本身并不是一个估计器。相反,它会为它尝试的每个参数组合实例化一个新的估计器(请参阅the docs)。

你可能会认为返回值是一个分类,因为你可以使用诸如predictpredict_probarefit=True,但GridSearchCV.predict_proba实际上看起来像(扰流从源):

def predict_proba(self, X): 
    """Call predict_proba on the estimator with the best found parameters. 
    Only available if ``refit=True`` and the underlying estimator supports 
    ``predict_proba``. 
    Parameters 
    ----------- 
    X : indexable, length n_samples 
     Must fulfill the input assumptions of the 
     underlying estimator. 
    """ 
    return self.best_estimator_.predict_proba(X) 

希望这有助于。

+0

'grid_search.best_estimator_.classes_'不起作用。我得到一个错误,说管道没有一个叫做classes_的属性。但是,我设法找到解决方案(请参阅答案)。 – Josefine

+0

好的。我认为这将是这种情况,但事实证明,我的例子与你的相似。 'grid_search.best_estimator_'是一个Pipeline对象,但我仍然可以获得'grid_search.best_estimator_.classes_'。 虽然我使用的是开发版本。 或者,您可以使用'steps'属性访问管道的每一步:'dict(grid_search.best_estimator_.steps)[“clf”] .class_'应该适合您。 – ldirer

+0

好吧,那么也许就是这样。我之前找到的解决方案几乎相同,我直接使用named_steps而不是在使用steps属性时创建字典(请参阅答案)。谢谢您的帮助! – Josefine

相关问题