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

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

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