这是统计学习方法中的一道题目,下面是维特比算法的代码实现:
1 import numpy as np 2 3 A = np.array([(0.5, 0.2, 0.3), (0.3, 0.5, 0.2), (0.2, 0.3, 0.5)]) 4 B = np.array([(0.5, 0.5), (0.4, 0.6), (0.7, 0.3)]) 5 P = np.array([(0.2, 0.4, 0.4)]) 6 o = np.array([(0, 1, 0)]) 7 8 T = 3 9 n = np.zeros((T, T)) 10 m = np.zeros((T, T)) 11 ans_t = np.zeros(T) 12 13 for i in range(3): #i代表第几步 14 for t in range(T): #t代表状态 15 if i == 0: #初始状态的处理 16 n[i][t] = P[i][t] * B[t][o[0][i]] 17 else: 18 for pre_t in range(T): 19 n[i][t] = max(n[i][t], n[i-1][pre_t] * A[pre_t][t]) 20 n[i][t] = n[i][t] * B[t][o[0][i]] 21 m[i][t] = np.array([n[i-1][j] * A[j, t] for j in range(T)]).argmax() 22 23 ans_t[T-1] = n[T-1, :].argmax() + 1 24 for t in range(T-2, -1, -1): 25 ans_t[t] = m[t+1][int(ans_t[t+1]) - 1] + 1 26 27 print(ans_t)