我无法在我的代码中实现 scikit-learn 机器学习算法。scikit-learn 的一位作者在我上面链接的问题中帮助了我,但我不能让它正常工作,因为我最初的问题是关于另一件事,我认为最好打开一个新的.
此代码输入推文并将其文本和情绪读入字典。然后它解析每一行文本并将文本添加到一个列表中,并将其情绪添加到另一个列表中(根据上述链接问题中作者的建议)。
但是,尽管使用链接中的代码并尽我所能查找 API,但我认为我遗漏了一些东西。运行下面的代码首先会给我一堆用冒号分隔的输出,如下所示:
(0, 299) 0.270522159585
(0, 271) 0.32340892262
(0, 266) 0.361182814311
: :
(48, 123) 0.240644787937
其次是:
['negative', 'positive', 'negative', 'negative', 'positive', 'negative', 'negative', 'negative', etc]
接着:
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