Bigram和trigram概率python

时间:2015-12-03 19:16:27

标签: python nltk

我真的需要帮助来理解概率估算的过程。 所以我计算了语料库中双字母的数量:

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 - 数学域错误 - 我无法理解为什么。请向我解释我的错误以及如何处理它。

1 个答案:

答案 0 :(得分:2)

我假设您在某些-11 行中收到了该错误。该错误仅表示您传递的参数没有定义11操作,例如

math.log

您的一个表达logimport math # Input is zero math.log(0) # ValueError: math domain error # Input is negative math.log(-1) # ValueError: math domain error 正在产生零输入或负输入。

请注意,python 2.7中的除法运算符(bigram_p[bigram]/unigram_p[('STOP',)])是整数除法,因此如果两个参数都是整数,则结果将被截断为整数:

math.log(bigram_p[bigram]/unigram_p[(word[0],)]

如果您想要更多直观分割操作的行为,请添加到您的文件中

/

如果您想了解有关该导入的详细信息,请参阅以下docs

编辑:

如果你不能/不想使用导入技巧,你可以通过乘以浮点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 来转换为浮点数。

相关问题