SciKit-learn的’predict’函数输出格式错误

我刚开始使用scikit,所以正在尝试使用它。

关于问题的背景:我正在尝试参与hackerRank上的“咬正确苹果”竞赛。我们会得到两个文件,一个包含苹果公司的文本,另一个包含苹果水果的文本。现在我们必须从中学习,然后对新文本进行预测。

虽然代码可以运行,但我的问题是:- 因为’line’(在下面的代码中)是一个单一输入,我应该得到一个单一数字的输出,不是零就是一。但我得到的是一个数组作为输出。- 我使用下面的代码是否接近于学习任何东西?

import numpy as npfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.linear_model import SGDClassifierfrom sklearn import svmfrom sklearn.svm import LinearSVCfrom sklearn.pipeline import PipelineappleComputers = [];appleFruits = [];labels = [];with open('apple-computers.txt','r') as f:    for line in f:        appleComputers.append(line)        labels.append(1);with open('apple-fruit.txt','r') as f:    for line in f:        appleFruits.append(line)        labels.append(0);text = appleComputers + appleFruits;labels = np.asarray(labels)#text_clf = Pipeline([('vect', CountVectorizer()),('tfidf', TfidfTransformer()),('clf', MultinomialNB()),])text_clf = Pipeline([('vect', CountVectorizer()),('tfidf', TfidfTransformer()),('clf', LinearSVC(loss='hinge', penalty='l2')),])text_clf = text_clf.fit(text, labels)line = 'I am talking about apple the fruit we eat.'line = 'I am talking about the product apple computer by Steve Jobs'predicted = text_clf.predict(line);print predicted

回答:

我自己找到了答案。

对于

predicted = text_clf.predict(line);

‘line’应该是一个列表而不是字符串,因为它在’fit’函数中是这样的。

即替换

line = 'I am talking about the product apple computer by Steve Jobs'

line = [];    line.append('I am talking about apple the fruit we eat.');

或者@jme建议我们可以使用

text_clf.predict([line]) 

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中创建了一个多类分类项目。该项目可以对…

发表回复

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