得到对应的类到predict_proba(GridSearchCV sklearn)

Get corresponding classes to predict_proba (GridSearchCV sklearn)

我正在使用 GridSearchCV 和管道对一些文本文档进行分类。一段代码:

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_'

我错过了什么?我想如果pipeline中最后的"step"是分类器,那么GridSearchCV的return也是分类器。因此可以使用该分类器的属性,例如类_.

尝试grid_search.best_estimator_.classes_

GridSearchCV 的 return 是一个 GridSearchCV 实例,它本身并不是一个真正的估计器。相反,它会为其尝试的每个参数组合实例化一个新的估计器(参见 the docs)。

你可能认为 return 值是一个分类器,因为当 refit=True 时你可以使用 predictpredict_proba 等方法,但是 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)

希望对您有所帮助。

如上面的评论所述,grid_search.best_estimator_.classes_ 返回了一条错误消息,因为它 returns 是一个没有属性 .classes_ 的管道。但是,通过首先调用管道的步骤分类器,我能够使用 类 属性。这是解决方案

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