统计学习方法第11章条件随机场(CRF)的Viterbi算法例题11.3代码实践:
from numpy import *
'''
这里定义T为转移矩阵列代表前一个y(ij)代表由状态i转到状态j的概率,Tx矩阵x对应于时间序列
这里将书上的转移特征转换为如下以时间轴为区别的三个多维列表,维度为输出的维度
'''
T1=array([[0.6,1],[1,0]]);T2=array([[0,1],[1,0.2]])
#将书上的状态特征同样转换成列表,第一个是为y1的未规划概率,第二个为y2的未规划概率
S0=[1,0.5];S1=[0.8,0.5];S2=[0.8,0.5]
#这里根据例11.2的启发整合为一个矩阵
F0=S0;F1=T1+array(S1*len(T1)).reshape(shape(T1));F2=T2+array(S2*len(T2)).reshape(shape(T2))
#因为这里矩阵被我做了整合成F所以算法更加简单
def calcNextAlpha(alpha,F,m):
Ydict = {};nextAlpha=alpha[:]
for i in range(m):
midAlpha=alpha[:]+F[i]
alphaList=midAlpha.tolist()
value=max(alphaList)
nextAlpha[i]=value
Ydict[i]=alphaList.index(value)
return nextAlpha,Ydict
#这里的maxIndex+1是因为列表都是从0开始的,而书中的y是从1开始的
def calcResult(alpha,Ydict,m):
IList=[]
maxIndex=alpha.index(max(alpha))
IList.append(maxIndex+1)
for i in range(m-1,0,-1):
maxIndex=Ydict[i][maxIndex]
IList.append(maxIndex+1)
return IList
def viterbi(F0,F1,F2,num):
alpha=F0;m=len(F1)
Ydict={}
for i in range(1,num):
alpha,subDict =calcNextAlpha(alpha,eval('F%d' % i),m)
Ydict[i]=subDict
return calcResult(alpha,Ydict,num)
print(viterbi(F0,F1.T,F2.T,3))
结果:
[1, 2, 1]
made by zcl at CUMT
I know I can because I have a heart that beats