如何在 Python 中应用维特比算法

How to Apply Viterbi Algorithm in Python

我是 Python 的初学者。目前我正在学习维特比算法。我在Wiki中找到了代码,我想在Python中实现它。

我正在使用 online Python 来执行算法。但是,我遇到了一个问题。

将代码复制到在线 Python 站点后,它显示

'sh-4.3$ python main.py'

这是否意味着我没有任何输出?如何将数据插入在线 Python 网站?

要在线尝试维特比算法,您应该粘贴以下代码

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)

联机 ide 并在命令行 python main.py 中打印(如果您的文件名为 main.py)。或按编辑器上方的 Execute 按钮。