1

I am a beginner to Python. Currently I am learning the Viterbi algorithm. I found the code in Wiki, and I would like to implement it in Python.

I am using online Python to execute the algorithm. However, I encounter a problem.

After I copy the code into the online Python site, it shows

'sh-4.3$ python main.py'

Does this mean I don't have any output? How can I insert data into online Python site?

1 Answer 1

2

To try Viterbi algorithm online you should paste following code

def viterbi(obs, states, start_p, trans_p, emit_p):
V=[{}]
    for i in states:
        V[0][i]=start_p[i]*emit_p[i][obs[0]]
    # Run Viterbi when t > 0
    for t in range(1, len(obs)):
        V.append({})
        for y in states:
            (prob, state) = max((V[t-1][y0] * trans_p[y0][y] * emit_p[y][obs[t]], y0) for y0 in states)
            V[t][y] = prob
        for i in dptable(V):
            print (i)
        opt=[]
        for j in V:
            for x,y in j.items():
                if j[x]==max(j.values()):
                    opt.append(x)
    #the highest probability
    h=max(V[-1].values())
    print ('The steps of states are '+' '.join(opt)+' with highest probability of %s'%h)
    #it prints a table of steps from dictionary

def dptable(V):
    yield " ".join(("%10d" % i) for i in range(len(V)))
    for y in V[0]:
        yield "%.7s: " % y+" ".join("%.7s" % ("%f" % v[y]) for v in V)

states = ('Healthy', 'Fever')
observations = ('normal', 'cold', 'dizzy')
start_probability = {'Healthy': 0.6, 'Fever': 0.4}
transition_probability = {
'Healthy' : {'Healthy': 0.7, 'Fever': 0.3},
'Fever' : {'Healthy': 0.4, 'Fever': 0.6}
}
emission_probability = {
'Healthy' : {'normal': 0.5, 'cold': 0.4, 'dizzy': 0.1},
'Fever' : {'normal': 0.1, 'cold': 0.3, 'dizzy': 0.6}
}

viterbi(observations,
                   states,
                   start_probability,
                   transition_probability,
                   emission_probability)

to online ide and print in command line python main.py (if your file named main.py). Or press Execute button above editor.

Sign up to request clarification or add additional context in comments.

3 Comments

It works! Thanks. By the way, I am new to Python. May I know why after the last line, which is Viterbi (observations, states, start_probability, transition_probability, emission_probability), the code outputs somethings?
I understand now. It works because we are calling the function viterbi, right?
@Idonknow Yes. And there are two print statements inside function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.