如何在python中的conditionalFreqDist方法中使用bigrams时将值附加到生成器?

时间:2014-02-19 20:06:43

标签: python regex nlp nltk probability

上下文 我正在使用NLTK生成双字母组概率。我有一个语料库,我从中创建了双字母组合。 - > 'wordPairsBigram'指的是语料库中的二元组。 我有一句话“公司董事长说他明年会增加利润”。 - > 'wordPairSentence'指的是上述句子中的双字母。

问题:我需要生成双字母组概率。为此,我需要找到样本句子的条件频率分布,我将传递给ConditionalProbDist函数。我有以下代码来计算语料库中可用的句子的双字母组的条件频率。

fdListSentence1 = ConditionalFreqDist(wordBigram for wordBigram in wordPairsBigram if wordBigram in wordPairSentence1 )
print fdListSentence1.tabulate()

output:
        company   he said will year
     The    8    0    0    0    0
chairman    0    0    7    0    0
      he    0    0    0    2    0
    next    0    0    0    0    5
    said    0   21    0    0    0

问题该代码适用于语料库和示例句子中可用的所有双字母组合。 Sample语句中有一些bigrams,但语料库中没有。在计算频率分布时,它们不会被包括在内。

我想要什么?我想要句子中双字母的频率分布。如果句子中的二元组不存在于语料库中,我在制表时需要一个值0。

感谢任何帮助。我不知道如何在代码中包含我想要的内容。

1 个答案:

答案 0 :(得分:1)

您要做的是平滑分布。平滑有多种方法,请参阅https://en.wikipedia.org/wiki/Smoothing

以下是添加剂平滑的一种方法:

from nltk.corpus import brown
from nltk.util import bigrams
from nltk.probability import ConditionalFreqDist
from itertools import chain

train = brown.sents()[:100]
test = brown.sents()[101:110]

cfd = ConditionalFreqDist()
train_bigrams = list(chain(*[bigrams(i) for i in train]))
for bg in train_bigrams:
    cfd[bg[0]].inc(bg[1])

# Or if you prefer a one-liner. 
cfd = ConditionalFreqDist((bg[0],bg[1]) for bg in list(chain(*[bigrams(i) for i in train])))


for bg in list(chain(*[bigrams(i) for i in test])):
    prob = cfd[bg[0]].freq(bg[1])
    prob = 0.0001 if not prob else prob
    print bg, prob

<强> [OUT]:

('said', 'it') 0.125
('it', 'would') 0.0001
('would', 'force') 0.111111111111
('force', 'banks') 0.0001
('banks', 'to') 0.0001
('to', 'violate') 0.0001
('violate', 'their') 0.0001
('their', 'contractual') 0.0001
('contractual', 'obligations') 0.0001
('obligations', 'with') 0.0001
('with', 'depositors') 0.0001
('depositors', 'and') 0.0001
('and', 'undermine') 0.0001
('undermine', 'the') 0.0001
('the', 'confidence') 0.0001
('confidence', 'of') 0.0001
('of', 'bank') 0.0001
('bank', 'customers') 0.0001
('customers', '.') 0.0001
('``', 'If') 0.0001
('If', 'you') 0.0001
('you', 'destroy') 0.0001
('destroy', 'confidence') 0.0001
('confidence', 'in') 0.0001
('in', 'banks') 0.0001
('banks', ',') 0.0001
(',', 'you') 0.0001
('you', 'do') 0.0001
('do', 'something') 0.0001
('something', 'to') 0.0001
('to', 'the') 0.0727272727273
('the', 'economy') 0.0001
('economy', "''") 0.0001
("''", ',') 0.205882352941
(',', 'he') 0.0001
('he', 'said') 0.0001
('said', '.') 0.166666666667