获取相应的类到predict_proba(GridSearchCV sklearn)

Jos*_*ine 3 python scikit-learn text-classification

我正在使用GridSearchCV和一个管道来分类som文本文档.下面插入了一个代码段

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)
Run Code Online (Sandbox Code Playgroud)

我的问题是,当使用grid_serach.predict_proba(new_doc)然后想要找出概率对应的类时grid_search.classes_,我得到以下错误

AttributeError:'GridSearchCV'对象没有属性'classes_'

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

提前致谢!

ldi*_*rer 6

试试grid_search.best_estimator_.classes_.

返回GridSearchCV是一个GridSearchCV实际上并不是估计器的实例.相反,它为它尝试的每个参数组合实例化一个新的估算器(参见文档).

你可能会认为返回值是一个分类,因为你可以使用诸如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)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Jos*_*ine 6

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

grid_search.best_estimator_.named_steps['clf'].classes_
Run Code Online (Sandbox Code Playgroud)