【问题标题】:Implementing scikit-learn machine learning algorithm实现 scikit-learn 机器学习算法
【发布时间】:2013-08-13 22:05:05
【问题描述】:

链接: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

【问题讨论】:

  • 这与问题无关,但也许您想将数据存储到mysql中以供以后使用。抱歉打扰了。
  • 不用担心,感谢您的意见。问题是,除了获得情绪之外,我不打算做任何事情。我没有未来分析或类似的计划,这只是一个一次性项目。
  • print tweets 会得到什么?您是否尝试过为 X 创建自己的 NumPy 数组而不是使用 vectorizer.fit_transform
  • 如果我打印推文,我会得到一个推文列表,用单引号括起来,用逗号分隔,整个列表用方括号括起来。我没有考虑创建自己的 NumPy 数组,因为老实说我不知道​​怎么做 - 通常是 Java 编码器,而不是 Python
  • @PeterFoti:完成。这给了我: ValueError: Found array with dim 50. Expected 1

标签: python scikit-learn sentiment-analysis


【解决方案1】:

问题出在这里:

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)

【讨论】:

  • 我能再问一件事吗?我昨晚工作到很晚才意识到文件名的愚蠢错误。我没有读取文件,并且对于每个文件中的每一行,我都使用“X_test =”和“y_pred =”行。作为测试,我在此之后放置了一个打印语句,看看会发生什么。推文被正确阅读,没有错误出现。但是,一行推文并没有给出一个声明,而是生成了一个包含大约 31 个“否定”的列表,所有这些都用逗号分隔的单引号引起来。这是为什么呢?
  • @AndrewMartin:在 Python 中,字符串是可迭代的。可能,scikit-learn 开始迭代字符串并尝试对单个字符进行分类。尝试将推文包装在一个列表中,所以transform([tweet]) 而不是transform(tweet)。 (这可能看起来很麻烦,但 scikit-learn 的速度来自其面向批处理的 API 和实现,因此您提供给它的所有内容都被视为“可迭代的”,如果可能的话,是一批样本。)
  • 效果很好,但我注意到最后一件事。一切都变得消极。每条推文(到目前为止尝试了大约 30 条,其中一些是肯定的)。我的 vectorizer.fit_transform(tweets) 行仅产生我注意到的正输出(不确定是否有些是负的?)我更新了我的问题中的代码以显示我目前正在尝试如何做到这一点。
  • @AndrewMartin:你还在训练你的 CSV 文件中的一些推文吗?如果是这样,请尝试使用更大的集合,因为用小输入集训练好的分类器实际上是不可能的。对于此类任务,建议最少使用数百个训练样本。
  • 确实是这样。它处理推文的速度肯定比 nltk 分类器快很多。
【解决方案2】:

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

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)

【讨论】:

  • 我会研究这个(除了我已经尝试过的之外,可能还会尝试使用它)。但是,我确实想尝试并得到我正在工作的东西(如果只是因为我花了这么长时间!)
  • 虽然我想让我的原始代码正常工作,但我确实尝试过,但出现了这个错误:AttributeError: 'module' object has no attribute 'compat'
  • 我克隆了你的 repo 以解决 sci kit 问题,并试图弄清楚。你用的是什么版本的python?你安装了 TextBlob 吗?
  • 我安装了 TextBlob 并且正在使用 Python 2.7.3
  • 我无法完全解读该错误消息,我们没有在任何地方调用该代码中的“compat”属性。我也一直在研究其他代码。我也把 y 变成了一个 numpy 数组,现在我看到的是:Traceback (most recent call last): File "naive-BayesClassifier.py", line 44, in &lt;module&gt; classifier.fit(X, y) File "/Library/Python/2.7/site-packages/sklearn/naive_bayes.py", line 308, in fit X = X.astype(np.float) ValueError: could not convert string to float: all time low shall be my motivation for the rest of the week
猜你喜欢
  • 2013-01-29
  • 2014-07-13
  • 2019-03-25
  • 2016-06-18
  • 2018-04-23
  • 1970-01-01
  • 2020-12-10
  • 2017-08-22
  • 2018-08-03
相关资源
最近更新 更多