【问题标题】:Understanding NLTK collocation scoring for bigrams and trigrams了解二元组和三元组的 NLTK 搭配评分
【发布时间】:2012-01-30 19:11:47
【问题描述】:

背景:

我正在尝试比较成对的单词,以查看在美国英语中哪对单词比另一对单词“更有可能出现”。我的计划是/曾经是使用 NLTK 中的搭配工具对单词对进行评分,得分较高的对最有可能。

方法:

我使用 NLTK 在 Python 中编写了以下代码(为简洁起见,删除了几个步骤和导入):

bgm    = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(tokens)
scored = finder.score_ngrams( bgm.likelihood_ratio  )
print scored

结果:

然后,我使用 2 个单词对检查了结果,其中一个应该很可能同时出现,另一个不应该出现(“roasted cashews”和“gasoline cashews”)。我很惊讶地看到这些单词配对得分相同:

[(('roasted', 'cashews'), 5.545177444479562)]
[(('gasoline', 'cashews'), 5.545177444479562)]

在我的测试中,我预计“烤腰果”的得分会高于“汽油腰果”。

问题:

  1. 我对搭配的使用有误解吗?
  2. 我的代码不正确吗?
  3. 我认为分数应该不同的假设是错误的吗?如果是,为什么?

非常感谢您提供任何信息或帮助!

【问题讨论】:

  • 另外一条评论:将所有 4 个词组合在一起,即“烤腰果汽油腰果”,给出了相似的结果,因为所有的二元组分数都是相同的。

标签: python nlp nltk


【解决方案1】:

NLTK 搭配文档对我来说似乎很不错。 http://www.nltk.org/howto/collocations.html

您需要为记分员提供一些实际相当大的语料库以供使用。这是一个使用 NLTK 中内置的布朗语料库的工作示例。运行大约需要 30 秒。

import nltk.collocations
import nltk.corpus
import collections

bgm    = nltk.collocations.BigramAssocMeasures()
finder = nltk.collocations.BigramCollocationFinder.from_words(
    nltk.corpus.brown.words())
scored = finder.score_ngrams( bgm.likelihood_ratio  )

# Group bigrams by first word in bigram.                                        
prefix_keys = collections.defaultdict(list)
for key, scores in scored:
   prefix_keys[key[0]].append((key[1], scores))

# Sort keyed bigrams by strongest association.                                  
for key in prefix_keys:
   prefix_keys[key].sort(key = lambda x: -x[1])

print 'doctor', prefix_keys['doctor'][:5]
print 'baseball', prefix_keys['baseball'][:5]
print 'happy', prefix_keys['happy'][:5]

输出看起来很合理,对棒球很有效,对医生和快乐则不太适用。

doctor [('bills', 35.061321987405748), (',', 22.963930079491501), 
  ('annoys', 19.009636692022365), 
  ('had', 16.730384189212423), ('retorted', 15.190847940499127)]

baseball [('game', 32.110754519752291), ('cap', 27.81891372457088), 
  ('park', 23.509042621473505), ('games', 23.105033513054011), 
  ("player's",    16.227872863424668)]

happy [("''", 20.296341424483998), ('Spahn', 13.915820697905589), 
 ('family', 13.734352182441569), 
 (',', 13.55077617193821), ('bodybuilder', 13.513265447290536)

【讨论】:

  • 好的,这解释了我的一些误解。有没有一种方便的方法来搜索二元组并获得相对分数?仍在寻找一种使用模式,可以让我检查给定的二元组的相关性。并感谢您的回答,非常有帮助!
  • 您可以将代码按原样与大型语料库一起使用,并将分数保存在双字母键控字典中,或者保留您提供的更多原始单字母和双字母频率计数(nltk 称为这些 FreqDist)当您想比较特定的二元组时,进入内置的二元组计分器。
  • 谢谢!昨晚我使用自定义语料库运行了一个非常酷的解决方案。它在一些困难的主题上做得很好。感谢您解除对我的阻止!
猜你喜欢
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 2011-09-17
  • 2016-10-05
相关资源
最近更新 更多