【问题标题】:Python - Sentiment Analysis using Pointwise Mutual InformationPython - 使用逐点互信息进行情感分析
【发布时间】:2014-04-02 19:46:33
【问题描述】:
from __future__ import division
import urllib
import json
from math import log


def hits(word1,word2=""):
    query = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s"
    if word2 == "":
        results = urllib.urlopen(query % word1)
    else:
        results = urllib.urlopen(query % word1+" "+"AROUND(10)"+" "+word2)
    json_res = json.loads(results.read())
    google_hits=int(json_res['responseData']['cursor']['estimatedResultCount'])
    return google_hits


def so(phrase):
    num = hits(phrase,"excellent")
    #print num
    den = hits(phrase,"poor")
    #print den
    ratio = num / den
    #print ratio
    sop = log(ratio)
    return sop

print so("ugly product")

我需要此代码来计算可用于将评论分类为正面或负面的 Point wise Mutual Information。基本上,我使用的是 Turney(2002):http://acl.ldc.upenn.edu/P/P02/P02-1053.pdf 指定的技术,作为情感分析的无监督分类方法的示例。

正如论文中所解释的,如果一个短语与“poor”这个词的关联度更高,那么它的语义方向就是负面的,如果它与“excellent”这个词的关联度更高,那么它的语义方向就是正面的。

上面的代码计算了一个短语的 SO。我使用谷歌来计算点击次数并计算 SO。(因为现在没有 AltaVista)

计算的值非常不稳定。他们不坚持特定的模式。 例如 SO("ugly product") 结果是 2.85462098541 而 SO("beautiful product") 是 1.71395061117。而前者预计是负面的,而另一个是正面的。

代码有问题吗?有没有一种更简单的方法可以用任何 Python 库(比如 NLTK)计算短语的 SO(使用 PMI)?我尝试了 NLTK,但找不到任何计算 PMI 的显式方法。

【问题讨论】:

  • 啊,我有 PMI 的代码,请稍等。一会儿我上传。

标签: python nlp nltk sentiment-analysis


【解决方案1】:

通常,计算 PMI 很棘手,因为公式会根据您要考虑的 ngram 的大小而变化:

在数学上,对于二元组,您可以简单地考虑:

log(p(a,b) / ( p(a) * p(b) ))

以编程方式,假设您已经计算了语料库中一元和二元的所有频率,您可以这样做:

def pmi(word1, word2, unigram_freq, bigram_freq):
  prob_word1 = unigram_freq[word1] / float(sum(unigram_freq.values()))
  prob_word2 = unigram_freq[word2] / float(sum(unigram_freq.values()))
  prob_word1_word2 = bigram_freq[" ".join([word1, word2])] / float(sum(bigram_freq.values()))
  return math.log(prob_word1_word2/float(prob_word1*prob_word2),2) 

这是来自 MWE 库的代码 sn-p,但它处于预开发阶段 (https://github.com/alvations/Terminator/blob/master/mwe.py)。但请注意,它是用于并行 MWE 提取,因此您可以通过以下方式“破解”它以提取单语 MWE:

$ wget https://dl.dropboxusercontent.com/u/45771499/mwe.py
$ printf "This is a foo bar sentence .\nI need multi-word expression from this text file.\nThe text file is messed up , I know you foo bar multi-word expression thingy .\n More foo bar is needed , so that the text file is populated with some sort of foo bar bigrams to extract the multi-word expression ." > src.txt
$ printf "" > trg.txt
$ python
>>> import codecs
>>> from mwe import load_ngramfreq, extract_mwe

>>> # Calculates the unigrams and bigrams counts.
>>> # More superfluously, "Training a bigram 'language model'."
>>> unigram, bigram, _ , _ = load_ngramfreq('src.txt','trg.txt')

>>> sent = "This is another foo bar sentence not in the training corpus ."

>>> for threshold in range(-2, 4):
...     print threshold, [mwe for mwe in extract_mwe(sent.strip().lower(), unigram, bigram, threshold)]

[出]:

-2 ['this is', 'is another', 'another foo', 'foo bar', 'bar sentence', 'sentence not', 'not in', 'in the', 'the training', 'training corpus', 'corpus .']
-1 ['this is', 'is another', 'another foo', 'foo bar', 'bar sentence', 'sentence not', 'not in', 'in the', 'the training', 'training corpus', 'corpus .']
0 ['this is', 'foo bar', 'bar sentence']
1 ['this is', 'foo bar', 'bar sentence']
2 ['this is', 'foo bar', 'bar sentence']
3 ['foo bar', 'bar sentence']
4 []

有关更多详细信息,我发现这篇论文是 MWE 提取的快速简单介绍:“Extending the Log Likelihood Measure to Improvement Collocation Identification”,请参阅http://goo.gl/5ebTJJ

【讨论】:

  • 这种方法对长文本以外的其他内容有用吗?让我们说Facebook cmets?或任何其他短文本?
  • 这完全取决于 PMI 对文本的反应,而且 PMI 似乎对高分母/低分子非常敏感,以允许误报。
【解决方案2】:

Python 库 DISSECT 在共现矩阵上包含 a few methods to compute Pointwise Mutual Information

例子:

#ex03.py
#-------
from composes.utils import io_utils
from composes.transformation.scaling.ppmi_weighting import PpmiWeighting

#create a space from co-occurrence counts in sparse format
my_space = io_utils.load("./data/out/ex01.pkl")

#print the co-occurrence matrix of the space
print my_space.cooccurrence_matrix

#apply ppmi weighting
my_space = my_space.apply(PpmiWeighting())

#print the co-occurrence matrix of the transformed space
print my_space.cooccurrence_matrix

Code on GitHub for the PMI methods.

参考:Georgiana Dinu、Nghia The Pham 和 Marco Baroni。 2013.DISSECT: DIStributional SEmantics Composition Toolkit.在系统演示程序中 ACL 2013,保加利亚索非亚

相关:Calculating pointwise mutual information between two strings

【讨论】:

    【解决方案3】:

    要回答您的结果为何不稳定,重要的是要知道 Google 搜索不是词频的可靠来源。引擎返回的频率只是在查询多个单词时特别不准确并且可能相互矛盾的估计。这不是要抨击谷歌,但它不是频率计数的实用程序。因此,您的实现可能没问题,但在此基础上的结果仍然可能毫无意义。

    如需更深入地讨论此事,请阅读 Adam Kilgarriff 的“Googleology is bad science”。

    【讨论】:

      猜你喜欢
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2011-11-21
      • 1970-01-01
      • 2012-11-09
      • 2013-11-15
      • 2020-03-26
      相关资源
      最近更新 更多