Created
September 3, 2014 09:19
-
-
Save goldsborough/ee7212e207243385a2de to your computer and use it in GitHub Desktop.
Forward algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
states = ("Sad","Happy") | |
observations = ("Crying","Laughing","Eating") | |
stateM = {'Sad': 0.3, 'Happy': 0.7} | |
transM = {'Sad': {'Sad': 0.3, 'Happy': 0.7}, 'Happy': {'Sad': 0.4, 'Happy': 0.6}} | |
observM = {'Sad': {'Crying': 0.7, 'Laughing': 0.1, 'Eating': 0.2}, 'Happy': {'Crying': 0.1, 'Laughing': 0.6, 'Eating': 0.3}} | |
observS = ["Laughing","Eating","Laughing"] | |
bayes = lambda a,b: ((a/(a+b)),(b/(a+b))) | |
def forward(states,observations,statesM,transM,observM,observSeq): | |
stateLen = len(states) | |
sM = statesM.copy() # don't change the original | |
forward_p = [] | |
# for every observation in the sequence | |
for o in observSeq: | |
newstates = sM.copy() #temporary copy | |
#state matrix * transition matrix | |
for col in range(stateLen): | |
val = 0 | |
for n in range(stateLen): | |
val += sM[states[n]] * transM[states[n]][states[col]] | |
newstates[states[col]] = val | |
sM = newstates.copy() | |
#new state matrix * observation | |
for s in sM: | |
sM[s] *= observM[s][o] | |
sM = {states[n]:i for n,i in enumerate(bayes(sM[states[0]],sM[states[1]]))} | |
forward_p.append(sM) | |
return forward_p | |
print(forward(states,observations,stateM,transM,observM,observS)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment