条件概率计算

Conditional Probability Calculation

我正在尝试制作马尔可夫模型,与此相关,我需要计算某些字母的条件 probability/mass 概率。 我创建了一个字母频率的二元组。

我如何设法计算我的字母的条件 probability/mass 概率?

计算条件概率的最简单方法是遍历模型中的案例,计算 1) 条件出现的案例和 2) 条件和目标字母出现的案例。条件概率是这两者的比率。

def cp(target, given):
    'Given is a one or two tuple and target is the letter following'
    g = 0.0
    g_and_t = 0.0
    n = len(given)
    for case, count in model.iteritems():
        if case[:n] == given:
            g += count
            if case[n] == target:
                g_and_t += count
    return g_and_t / g if g else 0.0

print cp(target='r', given=('f', 'o'))