前言:
隐马尔可夫预测模型主要有两种算法
近似算法
维特比算法(Viterbi algorithm)
目录
近似算法 维特比算法 CODE 实现一 近似算法
在每个时刻t选择在该时刻最有可能的状态
三 CODE 实现
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 09:22:49 2020
@author: chengxf2
"""
import numpy as np
A =[[0.5,0.2,0.3],
[0.3, 0.5,0.2],
[0.2, 0.3, 0.5]]
# 观测矩阵 'dry','dryish','damp', 'rainy'
B = [[0.5,0.5],
[0.4, 0.6],
[0.7, 0.3]]
PI = [0.2, 0.4, 0.4]
observations = [0,1,1] ##红, 白,红
class Viterbi:
"""
Args
A: 状态转移矩阵
B: 观测矩阵
PI: 初始概率
"""
def __init__(self,A, B, PI,O):
self.A = np.array(A,np.float)
self.B = np.array(B,np.float)
self.PI = np.array(PI,np.float)
self.O = np.array(O,np.int)
self.PSI = None ##概率最大值
self.DELTA = None ##概率最大值 对应的 路径
def Perdict(self):
T = len(self.O)
BestPath =[]
self.N, self.M = np.shape(self.B)
self.DELTA = np.zeros((T, self.N),np.int)
self.PSI = np.zeros((T, self.N), np.float)
print("\n **********step1 初始化*****************\n")
obser = self.O[0]
self.PSI[0]=np.multiply(self.PI, self.B[:,obser])
print("\n **********step2 递推*****************\n")
for t in range(1,T):
obser =self.O[t]
for i in range(self.N):
A = np.multiply(self.PSI[t-1] ,self.A[:,i])
index =self.DELTA[t,i]=np.argmax(A)
self.PSI[t,i]=A[index]*self.B[i,obser]
print("PSI ",self.PSI)
DelteI = np.argmax(self.PSI[-1])
BestPath.append(DelteI)
print("\n **********step3 最优路径*****************\n")
for t in reversed(range(T-1)):
index = self.DELTA[t+1,DelteI]
print("\n 时刻:",t,"=>时刻",t+1, "\t 最佳结点 ",index, "=>",DelteI)
DelteI = index
BestPath.append(DelteI)
BestPath.reverse()
print("\n 最佳路径: ",BestPath)
Vier = Viterbi(A,B,PI, observations)
Vier.Perdict()
作者:chengxf2