繁体   English   中英

Python - 使用Pointwise互信息的情感分析

[英]Python - Sentiment Analysis using Pointwise Mutual Information

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作为用于情感分析的无监督分类方法的示例。

正如文中所解释的,如果短语与“差”这个词更强烈相关,则短语的语义方向是否定的;如果短语与“优秀”这个词更强烈地相关,则短语的语义方向是肯定的。

上面的代码计算短语的SO。 我使用谷歌计算命中数并计算SO。(因为AltaVista现在不存在)

计算出的值非常不稳定。 他们没有坚持特定的模式。 例如,SO(“丑陋产品”)为2.85462098541,而SO(“美丽产品”)为1.71395061117。 虽然前者预计是负面而另一个是积极的。

代码有问题吗? 是否有更简单的方法来计算任何Python库(如NLTK)的短语(使用PMI)的SO? 我试过NLTK但是却找不到任何计算PMI的显式方法。

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

在数学上,对于双字母,你可以简单地考虑:

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

以编程方式,假设你已经计算了语料库中unigrams和bigrams的所有频率,你这样做:

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库的代码片段,但它处于预开发阶段( 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)]

[OUT]:

-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提取:“扩展对数似然度量以改进搭配识别”,请参阅http://goo.gl/5ebTJJ

Python库DISSECT包含一些计算共生矩阵上的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

关于PMI方法的GitHub代码

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

相关: 计算两个字符串之间的逐点互信息

要回答结果不稳定的原因,请务必了解Google搜索不是字频率的可靠来源。 引擎返回的频率仅仅是在查询多个单词时特别不准确并且可能相互矛盾的估计。 这不是为了抨击谷歌,但它不是频率计数的实用工具。 因此,您的实施可能没问题,但在此基础上的结果仍然可能是非感性的。

有关此问题的更深入讨论,请阅读Adam Kilgarriff撰写的“ Googleology是一门糟糕的科学 ”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM