如何从单个输入值获取分类报告

我使用自然语言处理(NLP)来对我的数据进行分类,我已经训练了我的数据,现在我想知道单个输入值的得分。我的数据包含服装和时尚相关的内容,应该返回它所属的类别。我想检查单个输入值的分类得分。我是这样做的:

bow4 = bow_transformer.transform([message4])tfidf4 = tfidf_transformer.transform(bow4)predicted =  spam_detect_model.predict(tfidf4)from sklearn.metrics import classification_reportprint (classification_report(data['Category Path'], predicted))

然后我收到了以下错误

“发现输入变量的样本数不一致:”

这是因为预测值的数组大小与数据不匹配。

如何从单个预测值查看分类报告?我想这样做是因为我想创建一个用户可以输入的Web应用程序。如果分类得分低于某个值(例如x),则会显示错误。

谢谢!

我的完整代码如下

import pandas as pdimport seaborn as snsfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerimport stringfrom nltk.corpus import stopwords#open filedata = pd.read_csv('cats.csv',sep=';')data['length'] = data['Product Name'].str.len()#remove all puncsdef 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 wordsprint(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 MultinomialNBspam_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 herefrom sklearn.metrics import classification_reportprint (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 = 0predicted = spam_detect_model.predict_proba(tfidf4)for x in spam_detect_model.classes_: #classes_ 给你标签,  proba  = round(predicted[0][counter],2)  if proba > 0.01: #只返回概率大于0.10%的标签      print(x + ' 概率 '+ str(proba))  counter +=1 ```

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注