Conditional Probability Calculation

I am trying to make a Markov model and in relation to this I need to calculate conditional probability/mass probability of some letters. I have created a bigram of the freqency of the letters.

How would I manage to calculate the conditional probability/mass probability of my letters?

Upvotes: 1

Views: 4359

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226764

The simplest way to compute the conditional probability is to loop through the cases in the model counting 1) cases where the condition occurs and 2) cases where the condition and target letter occur. The conditional probability is the ratio of those two.

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'))

Upvotes: 5

Related Questions