我真的需要帮助来理解概率估计的过程。 所以我计算了语料库中二元组的数量:
import nltk
bigram_p = {}
for sentence in corpus:
tokens = sentence.split()
tokens = [START_SYMBOL] + tokens #Add a start symbol
#so the first word would count as bigram
bigrams = (tuple(nltk.bigrams(tokens)))
for bigram in bigrams:
if bigram not in bigram_p:
bigram_p[bigram] = 1
else:
bigram_p[bigram] += 1
for bigram in bigram_p:
if bigram[0] == '*':
bigram_p[bigram] = math.log(bigram_p[bigram]/unigram_p[('STOP',)],2)
else:
bigram_p[bigram] = math.log(bigram_p[bigram]/unigram_p[(word[0],)],2)
但我收到 KeyError - 数学域错误 - 我不明白为什么。请向我解释我的错误以及如何处理它。
请您参考如下方法:
我假设您在某些 math.log 行中遇到了该错误。该错误仅表示您传递的参数未定义 log 操作,例如
import math
# Input is zero
math.log(0) # ValueError: math domain error
# Input is negative
math.log(-1) # ValueError: math domain error
你的表达式之一 bigram_p[bigram]/unigram_p[('STOP',)] 或 math.log(bigram_p[bigram]/unigram_p[(word[0],) ] 正在生成零或负输入。
注意 python 2.7 中的除法运算符 (/) 是整数除法,因此如果两个参数都是整数,结果将被截断为整数:
1 / 2 # => 0, because 1 and 2 are integers
1. / 2 # => 0.5, because 1. is a float
1.0 / 2 # => 0.5, because 1.0 is a float
如果您想要更直观的除法运算符行为,请添加到您的文件中,
from __future__ import division
这是 docs如果您想了解更多相关信息,请访问该导入。
编辑:
如果您不能/不想使用导入技巧,您可以通过乘以 float n * 1.0 或使用内置函数将数字转换为 float float (n)。
