import numpy as np
invisible = ['Sunny','Rainy']
activity = ['walk', 'shop', 'clean']
pi = [0.4, 0.6]
trainsion_prob = [[0.3, 0.7],[0.6, 0.4]]
emission_prob = [[0.6, 0.3, 0.1], [0.1, 0.4, 0.5]]
obs_seq=[0,1,2]
def viterbi(transiton_prob,emit_prob,pi,obs_seq):
tansition_prob=np.array(transiton_prob)
emit_prob=np.array(emit_prob)
pi=np.array(pi)
obs_seq=[0,1,2]
Row=tansition_prob.shape[0]
Col=len(obs_seq)
F=np.zeros((Row,Col))
F[:,0]=pi*np.transpose(emit_prob[:,obs_seq[0]])
for t in range(1,Col):
list_max=[]
for n in range(Row):
list_x=list(np.array(F[:,t-1])*np.transpose(tansition_prob[:,n]))
list_p=[]
for i in list_x:
list_p.append(i)
list_max.append(max(list_p))
F[:,t]=np.array(list_max)*np.transpose(emit_prob[:,obs_seq[t]])
return F
F = viterbi(trainsion_prob, emission_prob, pi, obs_seq)
print(F)
i = 0
for i in range(3):
if (F[0][i] > F[1][i]):
print("Sunny")
else:
print("Rainy")
[[0.24 0.0216 0.004032]
[0.06 0.0672 0.01344 ]]
Sunny
Rainy
Rainy