我真的需要帮助来理解概率估计的过程。所以我计算了语料库中的字数:
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 --数学域错误--我不明白为什么。请向我解释我的错误,以及如何处理它。
发布于 2015-12-04 05:52:34
我假设您在一些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],)]正在产生零或负输入。
注意,python2.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如果您想了解更多关于该导入的内容,下面是它的文档。
编辑:
如果您不能/不想使用导入技巧,则可以通过乘以浮动n * 1.0或内建函数float(n)将数字转换为浮动。
https://stackoverflow.com/questions/34074313
复制相似问题