fork download
  1. """
  2. Forward(HMM, O)
  3.  
  4. A = [
  5. [] (indexed on the ending state)
  6. ] (indexed on the starting state)
  7.  
  8. A[start][end] -> transition from start to end
  9.  
  10. B = [
  11. [] (indexed on observation)
  12. ] (indexed on hidden state state)
  13.  
  14. B[state][observation] -> probability of state emitting observation
  15.  
  16. pi -> initial probabilities
  17. """
  18.  
  19. def forward(A, B, PI, O):
  20. a = [[0] * len(A) for _ in range(len(O))]
  21.  
  22. for i in range(len(A)):
  23. a[0][i] = PI[i] * B[i][O[0]]
  24.  
  25. for t in range(1, len(O)):
  26. for j in range(len(A)):
  27. a[t][j] = 0
  28.  
  29. for i in range(len(A)):
  30. a[t][j] = a[t][j] + a[t-1][i] * A[i][j]
  31.  
  32. a[t][j] = a[t][j] * B[j][O[t]]
  33.  
  34. p = 0
  35. for i in range(len(A)):
  36. p += a[len(O)-1][i]
  37.  
  38. return p
  39.  
  40.  
  41. A = [
  42. [0.5, 0.5],
  43. [0.4, 0.6]
  44. ]
  45. B = [
  46. [0.5, 0.4, 0.1],
  47. [0.2, 0.4, 0.4]
  48. ]
  49. PI = [0.2, 0.8]
  50.  
  51. O = [2, 0, 2]
  52.  
  53. print(forward(A, B, PI, O))
Success #stdin #stdout 0.03s 63276KB
stdin
Standard input is empty
stdout
0.028562