sklearn GridSearchCV:如何获取分类报告?

sklearn GridSearchCV: how to get classification report?

我是这样使用 GridSearchCV 的:

corpus = load_files('corpus')

with open('stopwords.txt', 'r') as f:
    stop_words = [y for x in f.read().split('\n') for y in (x, x.title())]

x = corpus.data

y = corpus.target

pipeline = Pipeline([
    ('vec', CountVectorizer(stop_words=stop_words)),
    ('classifier', MultinomialNB())])

parameters = {'vec__ngram_range': [(1, 1), (1, 2)],
              'classifier__alpha': [1e-2, 1e-3],
              'classifier__fit_prior': [True, False]}

gs_clf = GridSearchCV(pipeline, parameters, n_jobs=-1, cv=5, scoring="f1", verbose=10)

gs_clf = gs_clf.fit(x, y)

joblib.dump(gs_clf.best_estimator_, 'MultinomialNB.pkl', compress=1)

然后,在另一个文件中,对新文档(不是来自语料库)进行分类,我这样做:

  classifier = joblib.load(filepath) # path to .pkl file
  result = classifier.predict(tokenlist)

我的问题是:我从哪里获得 classification_report 所需的值?

在许多其他示例中,我看到人们将语料库分成训练集和测试集。 但是,由于我将 GridSearchCV 与 kfold-cross-validation 一起使用,因此我不需要这样做。 那么如何从 GridSearchCV?

中获取这些值呢?

最佳模型在clf.best_estimator_。您需要将训练数据与此相匹配;然后预测你的测试数据并使用 ytest 和 ypreds 作为分类报告。

如果您有 GridSearchCV 对象:

from sklearn.metrics import classification_report
clf = GridSearchCV(....)
clf.fit(x_train, y_train)
classification_report(y_test,clf.best_estimator_.predict(x_test))

如果您保存并加载了最佳估算器,则:

classifier = joblib.load(filepath)
classification_report(y_test,classifier.predict(x_test))