• Python入门练习(二)Viterbi算法


    资料见:http://en.wikipedia.org/wiki/Viterbi_algorithm

    代码如下

    C:Python26MyViterbiMyViterbi.py
    # -*- coding: cp936 -*-

    def forward_viterbi(obs, states, start_p, trans_p, emit_p):
       T 
    = {}
       
    for state in states:
           
    ##          prob.           V. path  V. prob.
           T[state] = (start_p[state], [state], start_p[state])
       
    for output in obs:
           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 
    = emit_p[source_state][output] * trans_p[source_state][next_state]
                   prob 
    *= p
                   v_prob 
    *= p
                   total 
    += prob
                   
    if v_prob > valmax:
                       argmax 
    = v_path + [next_state]
                       valmax 
    = v_prob
               U[next_state] 
    = (total, argmax, valmax)
           T 
    = U
       
    ## apply sum/max to the final states:
       total = 0
       argmax 
    = None
       valmax 
    = 0
       
    for state in states:
           (prob, v_path, v_prob) 
    = T[state]
           total 
    += prob
           
    if v_prob > valmax:
               argmax 
    = v_path
               valmax 
    = v_prob
       
    return (total, argmax, valmax)

    C:Python26MyViterbimyTestViterbi.py
    # -*- coding: cp936 -*-
    from MyViterbi import forward_viterbi
    states
    =('Rainy','Sunny')#元组
    observations=('walk','shop','clean')#元组
    start_probability={'Rainy':0.6,'Sunny':0.4}
    transition_probility
    ={
        
    'Rainy':{'Rainy':0.7,'Sunny':0.3},
        
    'Sunny':{'Rainy':0.4,'Sunny':0.6}
        }
    emission_probability
    ={
        
    'Rainy':{'walk':0.1,'shop':0.4,'clean':0.5},
        
    'Sunny':{'walk':0.6,'shop':0.3,'clean':0.1}
        }
    observation
    =('walk','clean','walk')


    c
    =forward_viterbi(observation,states,start_probability,transition_probility,emission_probability)
    print c

    别忘了在MyViterbi文件夹下加init.py

    直接运行myTestViterbi.py

    结果如下:

    (0.023729999999999994, ['Sunny', 'Rainy', 'Sunny', 'Sunny'], 0.0051839999999999994)

  • 相关阅读:
    将指定byte数组以16进制的形式打印到控制台
    Java输出当前的日期(年月日时分秒毫秒)
    JAVA API从MongoDB中读取数据
    Hbase API 写入操作代码,基于hbase-client 1.0.3版本
    关于ROW_NUMBER函数的使用(The use of ROW_NUMBER function )
    网络知识点
    C++学习笔记
    Linux网络编程--tinyhttpd
    Linux多线程编程
    inet_ntop返回值错误
  • 原文地址:https://www.cnblogs.com/finallyliuyu/p/1705974.html
Copyright © 2020-2023  润新知