我使用 NLP 对我的数据进行分类,我已经训练了我的数据,现在我想知道单个输入值的分数。我的数据包含衣服和时尚元素,它应该返回它所属的类别。我想检查单个输入值的分类分数。 所以我这样做:
bow4 = bow_transformer.transform([message4])
tfidf4 = tfidf_transformer.transform(bow4)
predicted = spam_detect_model.predict(tfidf4)
from sklearn.metrics import classification_report
print (classification_report(data['Category Path'], predicted))
然后我收到以下错误
“发现输入变量的样本数量不一致:”
那是因为预测值的数组大小与数据不匹配。
如何从单个预测值中查看分类报告?我想这样做是因为我想创建一些网络应用程序,用户可以在其中进行输入。例如,如果分类分数低于 x,则会给出错误。
谢谢!
我的代码总体如下所示
import pandas as pd
import seaborn as sns
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import string
from nltk.corpus import stopwords
#open file
data = pd.read_csv('cats.csv',sep=';')
data['length'] = data['Product Name'].str.len()
#remove all puncs
def text_process(mess):
# Check characters to see if they are in punctuation
nopunc = [char for char in mess if char not in string.punctuation]
# Join the characters again to form the string.
nopunc = ''.join(nopunc)
# Now just remove any stopwords
return [word for word in nopunc.split() if word.lower() not in stopwords.words('english') if word.lower() not in stopwords.words('dutch')]
# Might take awhile...
bow_transformer = CountVectorizer(analyzer=text_process).fit(data['Product Name'])
# Print total number of vocab words
print(len(bow_transformer.vocabulary_))
messages_bow = bow_transformer.transform(data['Product Name'])
tfidf_transformer = TfidfTransformer().fit(messages_bow)
messages_tfidf = tfidf_transformer.transform(messages_bow)
from sklearn.naive_bayes import MultinomialNB
spam_detect_model = MultinomialNB().fit(messages_tfidf, data['Category Path'])
message4 = "some dummy data "
bow4 = bow_transformer.transform([message4])
tfidf4 = tfidf_transformer.transform(bow4)
predicted = spam_detect_model.predict(tfidf4)
#errors here
from sklearn.metrics import classification_report
print (classification_report(data['Category Path'], predicted))
最佳答案
经过反复试验终于找到了答案。
所以基本上你有一个可以看到类的 spam_detect_model.classes_
属性。
使用 predict_proba
您可以找到概率。所以现在您必须将它们连接在一起,这样您就可以使用 Python 中的 zip
方法来完成此操作。
所以对于其他在外面挣扎的人来说,它看起来像这样:
bow4 = bow_transformer.transform([message4])
tfidf4 = tfidf_transformer.transform(bow4)
counter = 0
predicted = spam_detect_model.predict_proba(tfidf4)
for x in spam_detect_model.classes_: #classes_ gives you the labels,
proba = round(predicted[0][counter],2)
if proba > 0.01: #only return the labels with a prob of larger then 0,10%
print(x + ' probility '+ str(proba))
counter +=1 ```
关于python - 如何从单个输入值获取分类报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59423204/