Created
January 25, 2019 07:33
-
-
Save jhaberstro/74b99b817f1b87d02bb55d6a0077599b to your computer and use it in GitHub Desktop.
WebPPL Hidden Markov Model Inference
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
/* | |
Dealer repeatedly flips a coin. Sometimes the coin is fair, with P(heads) = 0.5, | |
sometimes it’s loaded, with P(heads) = 0.8. Dealer occasionally switches coins, | |
invisibly to you. Given an list of observed coin flips, infer if the coin was | |
fair for each individual flip. | |
*/ | |
var hmm = function(n, initial, transitionf, observef) { | |
var impl = function(N) { | |
if (N > 1) { | |
var state = impl(N - 1) | |
var next_hidden = transitionf(state.hidden[state.hidden.length - 1]) | |
var next_observed = observef(next_hidden) | |
return { hidden: state.hidden.concat([next_hidden]), observed: state.observed.concat([next_observed]) } | |
} | |
else return { hidden: [initial], observed: [observef(initial)] } | |
} | |
return impl(n) | |
} | |
var sometimes_change_coin = function(previous_fair_state) { | |
return flip(0.9) ? previous_fair_state : !previous_fair_state | |
} | |
var do_flip = function(is_fair) { | |
var is_head = is_fair ? flip(0.5) : flip(0.8) | |
return is_head ? "H" : "T" | |
} | |
var post = Infer({method: 'MCMC', samples: 1000, lag: 100, burn: 50, | |
model: function() { | |
var data = ["H", "H", "H", "H", "H", "H", "T", "H", "T", "H", "T", "H", "T"] | |
var model = hmm(data.length, flip(0.5), sometimes_change_coin, do_flip) | |
condition(sum(map2(function(a, b) { return a == b}, data, model.observed)) == data.length) | |
return model.hidden | |
}}) | |
viz.marginals(post) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment