【问题标题】:SciKit-learn's 'predict' function giving output in wrong formatSciKit-learn 的“预测”功能以错误的格式给出输出
【发布时间】:2015-11-02 14:47:30
【问题描述】:

我是 scikit 的新手,所以玩弄它。

问题背景: 我正在尝试在hackerRank 上玩“Byte the correct apple”比赛。 其中我们有两个文件,一个包含 apple the company 的文本,另一个包含 apple the fruit。现在我们必须从中学习,然后对新文本进行预测。

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

import numpy as np

from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer


from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from sklearn import svm
from sklearn.svm import LinearSVC

from sklearn.pipeline import Pipeline

appleComputers = [];
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

【问题讨论】:

  • 我是否正确假设输出是[0][1]
  • 是的,你是对的。输出为 0 或 1。

标签: python machine-learning scikit-learn text-classification


【解决方案1】:

predict 函数返回一个数组对象,如documentation 中所述。此数组对象对应于您的 labels 数组中的索引。要获得line 的预测,您需要尝试以下操作:

print labels[predicted]

【讨论】:

  • 是的,这个问题更基本,我输入的格式错误。仍然非常感谢 Harpal 的帮助:)
【解决方案2】:

我自己找到了答案。

对于

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]) 

【讨论】:

  • 字符串没有append 方法。我想你的意思是写:text_clf.predict([line]).
  • 是的@jme 你是对的。感谢您的指正。我会编辑答案
猜你喜欢
  • 2018-01-09
  • 2014-11-30
  • 2017-04-25
  • 2013-06-05
  • 2013-05-31
  • 2015-10-23
  • 1970-01-01
  • 2016-07-30
  • 2021-01-11
相关资源
最近更新 更多