Advertisement
Guest User

Untitled

a guest
Feb 24th, 2015
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. # Viterbi Algorithm
  2. # Christopher Zelazo (A10863450)
  3.  
  4. import math
  5. import sys
  6.  
  7. # Pull from sources
  8. with open("observations.txt") as f:
  9.     observations = f.read().split(' ')
  10.  
  11. with open("initialStateDistribution.txt") as f:
  12.     stateDistros = [line.rstrip() for line in f]
  13.  
  14. with open("emissionMatrix.txt") as f:
  15.     emmissions = [[line.split()[0], line.split()[1]] for line in f]
  16.  
  17. with open("transitionMatrix.txt") as f:
  18.     transitions = [line.rstrip().split(' ') for line in f]
  19.  
  20. lstar = [None] * 26
  21. sstar = [None] * 45000
  22. alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  23.             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  24. message = ""
  25.  
  26. def viterbi(s, t):
  27.     mathsLS = lstar[:]      # Does Python pass by reference? IDK YOLO
  28.     pi = float(stateDistros[s])
  29.     b = float(emmissions[s][int(observations[t])])
  30.     max = -sys.float_info.max
  31.  
  32.     if t != 0:
  33.         for i in range(26):
  34.             a = float(transitions[s][i])
  35.             next = mathsLS[i] + math.log(a)
  36.  
  37.             if next > max: max = next
  38.  
  39.     else:
  40.         max = math.log(pi)
  41.  
  42.     mathsLS[s] = (max + math.log(b))
  43.     return mathsLS
  44.  
  45. for (idx, t) in enumerate(observations):
  46.  
  47.     # Starlight, starbright
  48.     for s in range(26):
  49.         lstar = viterbi(s, int(t))[:]
  50.  
  51.     # Take it back now y'all
  52.     likelyIdx = 0
  53.     for i in range(26):
  54.         i_val = lstar[i]
  55.         likely_val = lstar[likelyIdx]
  56.  
  57.         likelyIdx = i if (i_val > likely_val) else likelyIdx
  58.  
  59.     # print likelyIdx
  60.  
  61.     sstar[idx] = likelyIdx
  62.  
  63.     # if idx % 1000 == 0 :
  64.     #   print lstar
  65.  
  66. print lstar
  67.  
  68. # print output
  69. for (idx, s) in enumerate(sstar):
  70.     if idx != 0:
  71.         if sstar[idx-1] == s:
  72.             continue
  73.  
  74.     message += alphabet[int(s)]
  75.  
  76. print message
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement