Britney Tran
Britney Tran

Reputation: 1

How do I turn an HMM model into Python code?

I am currently trying out a few algorithms and I saw a figure online and wanted to try and turn it into python code. However I am having trouble with the math not checking out. For example in this test case

0.16,0.54,0.01,0.9,0.58,f,t,f 

I am supposed to get 0.0070,0.9930, but in my code I am getting 0.6559328878553198, 0.29660957943506916.

Here are some other test cases I wrote out and solved by hand:

0.16,0.86,0.89,0.11,0.48,f,f,f,t--><0.5899,0.4101>
0.42,0.27,0.1,0.76,0.67,f,f,f,t--><0.1282,0.8718>
0.7,0.79,0.45,0.84,0.52,f,t,t,t,t--><0.8082,0.1918>
0.98,0.13,0.95,0.93,0.73,f,f,f,f,t--><0.5209,0.4791>
0.28,0.3,0.41,0.79,0.23,t,t,t,f,f--><0.1519,0.8481>

I am trying to output the probability: ⃗ P (Xt|⃗e 1:t).

This is the code I have:

def hmm_filtering(cpt_line):
    values = cpt_line.split(',')
    probabilities = [float(value) for value in values[:5]]
    evidence = [1 if value == 't' else 0 for value in values[5:]]

    px_given_e = 1.0
    px_given_not_e = 1.0

    for i, e_value in enumerate(evidence):
        if e_value:
            px_given_e *= probabilities[i]
            px_given_not_e *= (1 - probabilities[i])
        else:
            px_given_e *= (1 - probabilities[i])
            px_given_not_e *= probabilities[i]

    total_probability = px_given_e + px_given_not_e
    px_given_e /= total_probability
    px_given_not_e /= total_probability

    return "<{:.4f},{:.4f}>".format(px_given_e, px_given_not_e)

# test_input = "0.5,0.7,0.3,0.9,0.2,t,t"
test_input = "0.16,0.54,0.01,0.90,0.58,f,t,f"
result = hmm_filtering(test_input)
print(result)

I am unsure where did I go wrong with my math in the coding portion, can someone please help?

Upvotes: 0

Views: 55

Answers (0)

Related Questions