我非常讨厌发布关于整个代码块的问题,但在过去的 3 个小时里我一直在研究这个问题,我无法理解正在发生的事情。我从 CSV 文件中检索到大约 600 条推文,这些推文具有不同的分值(介于 -2 到 2 之间),反映了对总统候选人的情绪。
但是,当我在任何其他数据上运行此训练样本时,只返回一个值(正值)。我已经检查了分数是否被正确添加并且它们是正确的。对我来说,从 600 条不同的训练集中将 85,000 条推文都评为“正面”,这对我来说是没有意义的。有人知道这里发生了什么吗?谢谢!
import nltk
import csv
tweets = []
import ast
with open('romney.csv', 'rb') as csvfile:
mycsv = csv.reader(csvfile)
for row in mycsv:
tweet = row[1]
try:
score = ast.literal_eval(row[12])
if score > 0:
print score
print tweet
tweets.append((tweet,"positive"))
elif score < 0:
print score
print tweet
tweets.append((tweet,"negative"))
except ValueError:
tweet = ""
def get_words_in_tweets(tweets):
all_words = []
for (words, sentiment) in tweets:
all_words.extend(words)
return all_words
def get_word_features(wordlist):
wordlist = nltk.FreqDist(wordlist)
word_features = wordlist.keys()
return word_features
def extract_features(document):
document_words = set(document)
features = {}
for word in word_features:
features['contains(%s)' % word] = (word in document_words)
return features
word_features = get_word_features(get_words_in_tweets(tweets))
training_set = nltk.classify.apply_features(extract_features, tweets)
classifier = nltk.NaiveBayesClassifier.train(training_set)
c = 0
with open('usa.csv', "rU") as csvfile:
mycsv = csv.reader(csvfile)
for row in mycsv:
try:
tweet = row[0]
c = c + 1
print classifier.classify(extract_features(tweet.split()))
except IndexError:
tweet = ""