def hmm_viterbi(A,B,pi,O): δ = np.zeros((len(O),len(A))) #第一个局部 Ψ = np.zeros((len(O),len(A))) #第二个局部 # 1、初始化t=1时刻维特比的两个局部变量 δ[0] = pi*B[:,O[0]] # 2、递归求序列每一步的两个局部变量 for index in range(1,len(δ)): δ[index] = np.max(δ[index-1]*A.T,1)*B[:,O[index]] Ψ[index] = np.argmax(δ[index-1]*A.T,1) # 3、求最后一个概率最大对应的隐含标签 label = [δ[-1].argmax()] # 4、回溯求整个序列的隐含标签 for index,tag in enumerate(Ψ[::-1]): if index<len(Ψ)-1: label.append(int(tag[int(label[-1])])) return label[::-1] A = np.array([[0.5,0.2,0.3],[0.3,0.5,0.2],[0.2,0.3,0.5]]) B = np.array([[0.5,0.5],[0.4,0.6],[0.7,0.3]]) pi = np.array([0.2,0.4,0.4]) O = '维特比算法是一个分词方法' O = np.array([0,1,0]) hmm_viterbi(A, B, pi, O)