牛刀小试利使用Python利用维特比算法解决经典隐马尔科夫链问题

PS:折腾了半天终于将博客取回,为纪念这个历史时刻,打算将最近学习机器学习的记录同大家分享下!

以下是解决李航的《统计学习方法》中例10.2(盒子和彩球问题)的Python代码实现。Csdn对Word文档编辑的矩阵显示支持得不太好,算法思路请通过以下链接下载查看。

# -*- coding: UTF-8 -*-
"""
   维特比算法实现:解决盒子与球颜色问题
   KaiwiiHo
"""
import numpy as np

if __name__ == '__main__':
    """
    状态(盒子序号)Q:1,2,3
    观察值(球的颜色)V:红,白
    训练集产生的模型参数(A,B,π)
    """
    stateTransition = np.array([0.5,0.2,0.3,0.3,0.5,0.2,0.2,0.3,0.5]).reshape(3,3)#状态间转移概率矩阵A
    stateToObservationTransition = np.array([0.5,0.5,0.4,0.6,0.7,0.3]).reshape(3,2)#状态转移观察概率矩阵B
    startState = np.array([0.2,0.4,0.4])#状态初始化概率π
    """
       观察结果O:"red","white","red",对应序号为:0,1,0
    """
    observation = np.array([0,1,0])
    """
       迭代计算
    """
    resMaxProbability = []#记录在当前时刻出现当前观察值时,出现某状态的最大概率。
    resMaxState = []#为出现某状态的最大概率时,上一时刻的状态值。
    obs_index = 0
    for obs in observation:
        if obs_index == 0:
            #初始化状态
            curProbability = startState*stateToObservationTransition[:,observation[obs_index]]
            resMaxProbability.append(curProbability)
        else:
            previewMaxProbability = resMaxProbability[obs_index-1]
            curProbability = []
            curState = []
            for item in range(len(stateTransition)):
                temp = stateTransition[:,item]*previewMaxProbability
                curProbability.append(np.max(temp))
                curState.append(np.argmax(temp))
            curProbability = curProbability*stateToObservationTransition[:,observation[obs_index]]
            resMaxProbability.append(curProbability)
            resMaxState.append(curState)
        obs_index = obs_index + 1
    print(resMaxProbability)
    print("=================")
    print(resMaxState)
    """
    回溯
    """
    resState = []#推理所得的状态序列
    resMaxProbabilityLen = len(resMaxProbability)
    lastMaxState = np.argmax(resMaxProbability[resMaxProbabilityLen-1])
    resState.append(lastMaxState)
    curMaxProbabilityState = lastMaxState
    print(lastMaxState)
    for index in range(resMaxProbabilityLen-1):
        curMaxProbabilityState = resMaxState[resMaxProbabilityLen-2-index][curMaxProbabilityState]
        resState.append(curMaxProbabilityState)

    print("结果是:%s" % resState)



你可能感兴趣的:(机器学习,大数据分析)