scikitlearn机器学习算法的实现

2024-09-29 21:55:22 发布

您现在位置:Python中文网/ 问答频道 /正文

链接:https://stackoverflow.com/questions/18154278/is-there-a-maximum-size-for-the-nltk-naive-bayes-classifer

我在代码中实现scikit学习机器学习算法时遇到问题。scikit learn的一位作者在我上面链接的问题上帮了我一把,但我不能完全让它发挥作用,因为我最初的问题是关于另一个问题的,我认为最好还是打开一个新的问题。在

这段代码接收tweets的输入,并将它们的文本和情感读入字典。然后,它解析每一行文本,并将文本添加到一个列表中,并将其情感添加到另一个列表中(根据作者在上述链接问题中的建议)。在

然而,尽管使用了链接中的代码并尽我所能查找API,但我认为我遗漏了一些东西。运行下面的代码首先给我一组用冒号分隔的输出,如下所示:

  (0, 299)  0.270522159585
  (0, 271)  0.32340892262
  (0, 266)  0.361182814311
  : :
  (48, 123) 0.240644787937

其次是:

^{pr2}$

然后:

ValueError: empty vocabulary; perhaps the documents only contain stop words

我分配分类器的方式不对吗?这是我的代码:

test_file = 'RawTweetdataset/SmallSample.csv'
#test_file = 'RawTweetDataset/Dataset.csv'
sample_tweets = 'SampleTweets/FlumeData2.txt'
csv_file = csv.DictReader(open(test_file, 'rb'), delimiter=',', quotechar='"')

tweetsDict = {}

for line in csv_file:
    tweetsDict.update({(line['SentimentText'],line['Sentiment'])})

tweets = []
labels = []
shortenedText = ""
for (text, sentiment) in tweetsDict.items():
    text = HTMLParser.HTMLParser().unescape(text.decode("cp1252", "ignore"))
    exclude = set(string.punctuation)
    for punct in string.punctuation:
        text = text.replace(punct,"")
    cleanedText = [e.lower() for e in text.split() if not e.startswith(('http', '@'))]
    shortenedText = [e.strip() for e in cleanedText if e not in exclude]

    text = ' '.join(ch for ch in shortenedText if ch not in exclude)
    tweets.append(text.encode("utf-8", "ignore"))
    labels.append(sentiment)

vectorizer = TfidfVectorizer(input='content')
X = vectorizer.fit_transform(tweets)
y = labels
classifier = MultinomialNB().fit(X, y)

X_test = vectorizer.fit_transform(sample_tweets)
y_pred = classifier.predict(X_test)

更新:当前代码:

all_files = glob.glob (tweet location)
for filename in all_files:
    with open(filename, 'r') as file:
        for line file.readlines():
            X_test = vectorizer.transform([line])
            y_pred = classifier.predict(X_test)
            print line
            print y_pred

这通常会产生如下结果:

happy bday trish
['negative'] << Never changes, always negative

Tags: csv代码textintest文本forlabels
2条回答

问题在于:

X_test = vectorizer.fit_transform(sample_tweets)

fit_transform旨在对训练集而不是测试集调用。在测试集上,调用transform。在

另外,sample_tweets是一个文件名。在将其传递给矢量器之前,您应该打开它并阅读其中的tweets。如果你这样做了,那么你最终应该能够做一些

^{pr2}$

要在TextBlob中执行此操作(如注释中所述),您可以这样做

from text.blob import TextBlob

tweets = ['This is tweet one, and I am happy.', 'This is tweet two and I am sad']

for tweet in tweets:
    blob = TextBlob(tweet)
    print blob.sentiment #Will return (Polarity, Subjectivity)

相关问题 更多 >

    热门问题