python - 实现 scikit-learn 机器学习算法

标签 python scikit-learn sentiment-analysis

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

我在代码中实现 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

最佳答案

问题出在这里:

X_test = vectorizer.fit_transform(sample_tweets)

fit_transform 旨在在训练集而非测试集上调用。在测试集上,调用transform

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

for tweet, sentiment in zip(list_of_sample_tweets, y_pred):
    print("Tweet: %s" % tweet)
    print("Sentiment: %s" % sentiment)

关于python - 实现 scikit-learn 机器学习算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18220015/

相关文章:

python - Python 2.7 中的 urllib.request

python - 在 python 中处理非常小的数字

python - 如何使用Python包安装Python代码以外的各种文件?

python - SKLearn 交叉验证 : How to pass info on fold examples to my scorer function?

nlp - 情绪分析的最佳算法方法

Python 2.7 - 时间偏移转换

python - 初学者问题,使用 sklearn,保存模型并测试单个数据帧

python - Scikit 学习 : Randomized Logistic Regression gives ValueError: output array is read-only

python - 创建阿拉伯语语料库

machine-learning - 使用 SentiWordNet 和 Apache OpenNLP 的情感分析工具