题目阐释:

viterbi算法实现。 用python实现viterbi的hidden state 和 表现层的转移
动态规划问题,归结到
    相邻两个step之间存在 state转移概率,state2emibission转移概率。
    计算后可以得到每个step的每个state max_probablity
    由于step_n依赖于 step_n-1,跟 step_n-2无关,所以可以一直如此往复,得到最后的max_prob
整个问题抽象为,下一个step依赖于上一个step的所有state,所以只需要计算每一层step的所有state的prbo即可。

难点:

三层for循环,为了保留,计算每个step的state的概率,所以要 next_state 嵌套在 source_state之外。

states=['Rainy','Sunny']
observations=['walk','shop','clean']
observations=('walk','clean','walk')

emission_probability={'Rainy':{'walk':0.1,'shop':0.4,'clean':0.5},
                   'Sunny': {'walk': 0.6, 'shop': 0.3, 'clean': 0.1}
                    }
trans_probability={'Rainy':{'Rainy':0.7,'Sunny':0.3},
                     'Sunny':{'Rainy':0.4,'Sunny':0.6}
                     }
start_probability={'Rainy':0.6,'Sunny':0.4}

def vertibi(states,objservations,start_prob,trans_prob,emi_prob):
    T={state:[start_prob[state],[state],start_prob[state]] for state in states}
    for objservation in objservations:
        U={}
        for next_state in states:
            total=0
            argmax=None
            valmax=0
            for source_state in states:
                prob,v_path,v_prob=T[source_state]
                p=emi_prob[source_state][objservation]*trans_prob[source_state][next_state]
                prob*=p
                v_prob*=p

                if v_prob>valmax:
                    valmax=v_prob
                    argmax=v_path+[next_state]
                    total+=prob
            U[next_state]=[total,argmax,valmax]
        T=U

    total = 0
    argmax = None
    valmax = 0
    for state in states:
        prob, v_path, v_prob=T[state]
        if v_prob>valmax:
            argmax=v_path
            total=prob
            valmax=v_prob
    return total,argmax,valmax

total,argmax,valmax=vertibi(states,observations,start_probability,trans_probability,emission_probability)
print(total)
print(argmax)
print(valmax)



龙仔
12 声望4 粉丝