python - 如何在 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)类别之一。
此外,欢迎您对整个代码提出任何其他建议。我想很好地学习这些过程。
解决方案
您使用的变量名称似乎与您在上面定义的名称不同。
在您制作模型的代码中:-您的模型称为 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)
推荐阅读
- asp.net-core - ASP.NET MVC Core - 业务层中的 ViewModel 并实现数据注释
- excel - 将保存在文件夹中的一个特定工作簿中的多个工作表合并到新文件中的一张工作表中
- github - GitHub 在我没有上传的情况下找到了我的个人资料图片。那个怎么样?
- api - 创建用于构建和开发 Vue 应用程序的虚假数据 (API)
- node.js - 从数据库中删除后,axios delete 给出 404
- sql - 如何将一行添加到另一行
- javascript - 使用 javascript 查询输入文本并检查值不起作用
- reporting-services - 如何使用主机名 (DNS) 而不是服务器名来配置报告服务
- php - 在 docker 上运行 lumen api 时出错(原因:php_network_getaddresses:getaddrinfo 失败:名称或服务未知)
- bazel - 您是否看到过 bazel 查询在第一次运行时没有返回结果,然后如果重复则可以正常工作的问题?