def MLdecode(data, hmm): s='' for c in data: emiA = a.getEmissionProbability(0, c, hmm) emiB = a.getEmissionProbability(1, c, hmm) if a.compareProbability(emiA, emiB)==1: s+='A' else: s+='B' return s
def getXi(data, hmm): alpha = a.forward(data, hmm) beta = a.backward(data, hmm) #likelihood=beta[0][0] xi = [[[0,0],[0,0]]] beta.append([[1, 0], [1,0]]) for t in range(len(data)): xi.append([[0,0],[0,0]]) t = 0 for h in range(len(data)): t+=1 for i in range(0, 2): for j in range(0, 2): ptrans = a.getTransitionProbability(i, j, hmm)[0] if t<len(data)-1: pemit = a.getEmissionProbability(j, data[t+1], hmm)[0] else: pemit = 1 #temp = a.multiplyProbability(alpha[t][i], ptrans) #temp = a.multiplyProbability(temp, pemit) #temp = a.multiplyProbability(temp, beta[t+1][j]) #xi[t][i][j]=a.divideProbability(temp, likelihood) #print str(i)+" "+str(j) #print xi #print xi[t][i][j] xi[t][i][j]=alpha[t][i][0]*ptrans*pemit*beta[t+1][j][0] # xi[t][i][j]=temp return xi
def getXi(data, hmm): alpha = a.forward(data, hmm) beta = a.backward(data, hmm) likelihood = beta[0][0] xi = [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]] for t in range(len(data) - 1): xi.append([[[0, 0], [0, 0]], [[0, 0], [0, 0]]]) data = "#" + data t = 0 for h in range(len(data) - 1): for i in range(0, 2): for j in range(0, 2): ptrans = a.getTransitionProbability(i, j, hmm) pemit = a.getEmissionProbability(j, data[t + 1], hmm) temp = a.multiplyProbability(alpha[t][i], ptrans) temp = a.multiplyProbability(temp, pemit) temp = a.multiplyProbability(temp, beta[t + 1][j]) xi[t][i][j] = a.divideProbability(temp, likelihood) t += 1 return xi
def viterbi(data, hmm): alpha = [[[1,0],[0,0]]] t = 0 track = [[],[]] for c in data: t+=1 alpha.append([[0, 0],[0, 0]]) for j in range(0, 2): cand = [[0.0, 0],[0.0,0]] for i in range(0,2): ptrans = a.getTransitionProbability(i, j, hmm) cand[i]=a.multiplyProbability(alpha[t-1][i], ptrans) if a.compareProbability(cand[0], cand[1])==1: better=cand[0] track[j].append(0) else: better=cand[1] track[j].append(1) pemit = a.getEmissionProbability(j, c, hmm) prob = a.multiplyProbability(better, pemit) # print prob alpha[t][j]=prob # print alpha[t] #print scale[t] if a.compareProbability(alpha[t][0], alpha[t][1])==1: start=0 else: start=1 s = '' # print track[0] for i in range(len(track[0])-1, -1, -1): if start==0: s='A'+s else: s='B'+s start = track[start][i] return s