我刚开始使用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])