Skip to main content
 首页 » 编程设计

python之无论上下文如何,NLTK 的 NgramModel 始终为单词给出相同的概率

2025年05月04日15lyj

我正在使用 nltk 中的 NgramModel 来计算在句子中找到特定单词的概率。我的问题是,无论上下文如何,每个词每次都给出完全相同的概率!下面是一些示例代码,可以说明我的问题。

from nltk.corpus import brown 
from nltk.probability import LidstoneProbDist, WittenBellProbDist 
from nltk.model import NgramModel 
 
estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2) 
 
lm = NgramModel(3, brown.words(categories='news'), estimator=estimator) 
>>> print lm.prob("word", ["This is a context which generates a word"]) 
0.00493261081006 
>>> print lm.prob("word", ["This is a context of a word"]) 
0.00493261081006 
>>> print lm.prob("word", ["This word"]) 
0.00493261081006 
>>> print lm.prob("word", ["word"]) 
0.00493261081006 
>>> print lm.prob("word", ["adnga"]) 
0.00493261081006 

请您参考如下方法:

单词的上下文不应该包含单词本身,除非你有一个重复的单词。棕色语料库很小,所以除非你命中的是数据中实际观察到的卦,否则你会得到相同的答案。在我的示例中,我改用二元语法,这样我就不会经常使用平滑模型。在您的示例中,您每次都在使用平滑模型。第三,在实践中,LidstoneProbDist 非常糟糕,它是平滑时可能起作用的最简单的东西,而不是你想在实践中使用的东西。 SimpleGoodTuringProbDist 要好得多。

from nltk.corpus import brown 
from nltk.probability import LidstoneProbDist 
from nltk.model import NgramModel 
 
estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2) 
 
lm = NgramModel(2, brown.words(categories='news'), estimator=estimator) 
 
lm.prob("good", ["very"])          # 0.0024521936223426436 
lm.prob("good", ["not"])           # 0.0019510849023145812 
lm.prob("good", ["unknown_term"])  # 0.017437821314436573