首页 > 解决方案 > 如何在 scikit learn 中为新分类器测试看不见的句子

问题描述

我已经使用这个数据集创建了一个模型,我想插入一些句子来看看它们是如何分类的。我怎样才能做到这一点?

这是制作模型的代码:

from sklearn.datasets import fetch_20newsgroups
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics

cats = ['sci.space','rec.autos']
newsgroups_train = fetch_20newsgroups(subset='train',
                   remove=('headers', 'footers', 'quotes'), categories = cats)
newsgroups_test = fetch_20newsgroups(subset='test',
                   remove=('headers', 'footers', 'quotes'), categories = cats)

vectors_test = vectorizer.transform(newsgroups_test.data)
vectorizer = TfidfVectorizer()
vectors = vectorizer.fit_transform(newsgroups_train.data)
clf = MultinomialNB(alpha=.01)
clf.fit(vectors, newsgroups_train.target)
vectors_test = vectorizer.transform(newsgroups_test.data)
pred = clf.predict(vectors_test)
metrics.f1_score(newsgroups_test.target, pred, average='macro')

它返回的准确度是:0.97这表明存在过度拟合。

如前所述,我想测试未见数据的分类将如何发生。我该如何进行?

我试过的例子:

texts = ["The space shuttle is made in 2018", 
         "The exhaust is noisy.",
         "the windows are transparent."]
text_features = tfidf.transform(texts)
predictions = model.predict(text_features)
for text, predicted in zip(texts, predictions):
  print('"{}"'.format(text))
  print("  - Predicted as: '{}'".format(id_to_category[predicted]))
  print("")
 #this does not work as it is

它应该将每个句子分类到两个(sci.space、rec.autos)类别之一。

此外,欢迎您对整个代码提出任何其他建议。我想很好地学习这些过程。

标签: pythonscikit-learnnlp

解决方案


您使用的变量名称似乎与您在上面定义的名称不同。

在您制作模型的代码中:-您的模型称为 clf,因此当您之后使用它时,您应该编写 clf.predict(而不是 model.predict)-您的 TfidfVectorizer 称为矢量化器,因此当您之后使用它时使用相同的变量名称(不是像 tfidf 这样的新名称)

您的示例变为:

texts = ["The space shuttle is made in 2018", 
     "The exhaust is noisy.",
     "the windows are transparent."]
text_features = vectorizer.transform(texts)
predictions = clf.predict(text_features)
for text, predicted in zip(texts, predictions):
   print('"{}"'.format(text))
   print("  - Predicted as: '{}'".format(predicted))
   print("")

运行正常:

“航天飞机是 2018 年制造的” - 预测为:'1'

“排气很吵。” - 预测为:'0'

“窗户是透明的。” - 预测为:'1'

同样在您的培训代码中,确保这 3 行的顺序正确:

vectorizer = TfidfVectorizer()
vectors = vectorizer.fit_transform(newsgroups_train.data)
vectors_test = vectorizer.transform(newsgroups_test.data)

推荐阅读