尝试使用二元语法来查找短语的概率
filename.txt
# 二元语法出现的次数bg_count = bigrams.count(('word1', 'word2'))# 文本中二元语法的概率 P(word1 word2)bg_count/number_of_bigrams
回答:
在二元语言模型中:
P(w1,w2,w3,...wn) = P(w1)*P(w2|w1)*P(w3|w2).....*P(wn-1|wn)
因此 P(life, might) = P(life)*P(might|life)
其中
P(life) = Count(life)/Number of unigrams
P(might|life) = Count(life, might)/Count(life)
使用二元模型计算 P(life might)
的代码:
p_life = s.count("life")/len(s)p_might_given_life = bigrams.count(('life', 'might'))/s.count('life')p_life_might = p_life * p_might_given_lifeprint (p_life_might)
输出:
0.0024752475247524753
对数概率
由于概率 <=1 且不安全地乘以许多小数,我们通常使用对数概率,因为它将乘法转换为加法。而且由于对数是一个单调递增函数,不同对数概率之间的比较将与实际概率的比较相同。
log(p_life_might) = log(p_life * p_might_given_life)
= log(p_life) + log(p_might_given_life)
代码:
print (math.log(p_life)+math.log(p_might_given_life))
输出:
-6.0014148779611505