Created
December 9, 2021 10:05
-
-
Save Moligaloo/35975c59761f5d19673a5b82f2b80b82 to your computer and use it in GitHub Desktop.
Viterbi algorithm written in MoonScript
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
obs = {'normal', 'cold', 'dizzy'} | |
states = {'Healthy', 'Fever'} | |
start_p = { | |
Healthy: 0.6, | |
Fever: 0.4 | |
} | |
trans_p = { | |
Healthy: { | |
Healthy: 0.7, | |
Fever: 0.3 | |
}, | |
Fever: { | |
Healthy: 0.4, | |
Fever: 0.6 | |
} | |
} | |
emit_p = { | |
Healthy: { | |
normal: 0.5, | |
cold: 0.4, | |
dizzy: 0.1 | |
}, | |
Fever: { | |
normal: 0.1, | |
cold: 0.3, | |
dizzy: 0.6 | |
} | |
} | |
M = require 'moses' | |
-- viterbi algorithm | |
last_states = nil | |
path = for ob in *obs | |
probFunc = unless last_states | |
(state) -> start_p[state] * emit_p[state][ob] | |
else | |
(state) -> M.max [last_states[new_state] * trans_p[state][new_state] * emit_p[new_state][ob] for new_state in *states] | |
last_states = {state, probFunc state for state in *states} | |
M.best(M.kvpairs(last_states), (a, b) -> a[2] > b[2])[1] | |
-- print result | |
for state in *path | |
print state |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment