python - 计算 PMI 的二元组和差异

标签 python nltk information-theory

假设我有以下文本:

text = "this is a foo bar bar black sheep  foo bar bar black sheep foo bar bar black sheep shep bar bar black sentence"

我可以使用 NLTK 计算二元组的 PMI,如下所示:

bigram_measures = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(word_tokenize(text))
for i in finder.score_ngrams(bigram_measures.pmi):
    print(i)

给出:

(('is', 'a'), 4.523561956057013)
(('this', 'is'), 4.523561956057013)
(('a', 'foo'), 2.938599455335857)
(('sheep', 'shep'), 2.938599455335857)
(('black', 'sentence'), 2.523561956057013)
(('black', 'sheep'), 2.523561956057013)
(('sheep', 'foo'), 2.353636954614701)
(('bar', 'black'), 1.523561956057013)
(('foo', 'bar'), 1.523561956057013)
(('shep', 'bar'), 1.523561956057013)
(('bar', 'bar'), 0.5235619560570131)

现在检查我自己的理解,我想找到 PMI 的 PMI('黑','羊')。 PMI计算公式为:

$$ pmi(w1,w2) = \ $$

文本中有 4 个“黑色”实例,文本中有 3 个“羊”实例,黑色和羊出现了 3 次,文本长度为 23。现在按照我的公式:

np.log((3/23)/((4/23)*(3/23)))

这给出了 1.749199854809259 而不是 2.523561956057013。我想知道为什么这里有差异?我在这里缺少什么?

最佳答案

我对PMI一无所知,但根据您的信息,PMI公式使用以2为底的对数而不是以e为底的对数。

来自NumPy's documentation , numpy.log 是以 e 为底的自然对数,这不是您想要的。

以下公式将为您提供 2.523561956057013 的结果:

math.log((3/23)/((4/23)*(3/23)), 2)

关于python - 计算 PMI 的二元组和差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71843760/

相关文章:

python - 使用 NLTK 的语义角色标记

python - 使集合无前缀

machine-learning - 互信息和预测准确性

text - 信息获取在文本分类中的工作原理

python - 在 Python 中使用 prints 创建数据框

Python pickle : ImportError: No module named __main__

python - for 循环列表 - 返回错误 "too many values to unpack"

python - 从文本文件列表中删除停用词

python - Flask 线程共享值

python - NLTK - 多标签分类